ID
stringlengths
36
36
Language
stringclasses
1 value
Repository Name
stringclasses
13 values
File Name
stringlengths
2
48
File Path in Repository
stringlengths
11
111
File Path for Unit Test
stringlengths
13
116
Code
stringlengths
0
278k
Unit Test - (Ground Truth)
stringlengths
78
663k
Code Url
stringlengths
91
198
Test Code Url
stringlengths
93
203
Commit Hash
stringclasses
13 values
8789345e-d2e1-4516-92fc-06e0e3d17d5f
cpp
google/quiche
cubic_bytes
quiche/quic/core/congestion_control/cubic_bytes.cc
quiche/quic/core/congestion_control/cubic_bytes_test.cc
#include "quiche/quic/core/congestion_control/cubic_bytes.h" #include <algorithm> #include <cmath> #include <cstdint> #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { namespace { const int kCubeScale = 40; const int kCubeCongestionWindowScale = 410; const uint64_t kCubeFactor = (UINT64_C(1) << kCubeScale) / kCubeCongestionWindowScale / kDefaultTCPMSS; const float kDefaultCubicBackoffFactor = 0.7f; const float kBetaLastMax = 0.85f; } CubicBytes::CubicBytes(const QuicClock* clock) : clock_(clock), num_connections_(kDefaultNumConnections), epoch_(QuicTime::Zero()) { ResetCubicState(); } void CubicBytes::SetNumConnections(int num_connections) { num_connections_ = num_connections; } float CubicBytes::Alpha() const { const float beta = Beta(); return 3 * num_connections_ * num_connections_ * (1 - beta) / (1 + beta); } float CubicBytes::Beta() const { return (num_connections_ - 1 + kDefaultCubicBackoffFactor) / num_connections_; } float CubicBytes::BetaLastMax() const { return (num_connections_ - 1 + kBetaLastMax) / num_connections_; } void CubicBytes::ResetCubicState() { epoch_ = QuicTime::Zero(); last_max_congestion_window_ = 0; acked_bytes_count_ = 0; estimated_tcp_congestion_window_ = 0; origin_point_congestion_window_ = 0; time_to_origin_point_ = 0; last_target_congestion_window_ = 0; } void CubicBytes::OnApplicationLimited() { epoch_ = QuicTime::Zero(); } QuicByteCount CubicBytes::CongestionWindowAfterPacketLoss( QuicByteCount current_congestion_window) { if (current_congestion_window + kDefaultTCPMSS < last_max_congestion_window_) { last_max_congestion_window_ = static_cast<int>(BetaLastMax() * current_congestion_window); } else { last_max_congestion_window_ = current_congestion_window; } epoch_ = QuicTime::Zero(); return static_cast<int>(current_congestion_window * Beta()); } QuicByteCount CubicBytes::CongestionWindowAfterAck( QuicByteCount acked_bytes, QuicByteCount current_congestion_window, QuicTime::Delta delay_min, QuicTime event_time) { acked_bytes_count_ += acked_bytes; if (!epoch_.IsInitialized()) { QUIC_DVLOG(1) << "Start of epoch"; epoch_ = event_time; acked_bytes_count_ = acked_bytes; estimated_tcp_congestion_window_ = current_congestion_window; if (last_max_congestion_window_ <= current_congestion_window) { time_to_origin_point_ = 0; origin_point_congestion_window_ = current_congestion_window; } else { time_to_origin_point_ = static_cast<uint32_t>( cbrt(kCubeFactor * (last_max_congestion_window_ - current_congestion_window))); origin_point_congestion_window_ = last_max_congestion_window_; } } int64_t elapsed_time = ((event_time + delay_min - epoch_).ToMicroseconds() << 10) / kNumMicrosPerSecond; uint64_t offset = std::abs(time_to_origin_point_ - elapsed_time); QuicByteCount delta_congestion_window = (kCubeCongestionWindowScale * offset * offset * offset * kDefaultTCPMSS) >> kCubeScale; const bool add_delta = elapsed_time > time_to_origin_point_; QUICHE_DCHECK(add_delta || (origin_point_congestion_window_ > delta_congestion_window)); QuicByteCount target_congestion_window = add_delta ? origin_point_congestion_window_ + delta_congestion_window : origin_point_congestion_window_ - delta_congestion_window; target_congestion_window = std::min(target_congestion_window, current_congestion_window + acked_bytes_count_ / 2); QUICHE_DCHECK_LT(0u, estimated_tcp_congestion_window_); estimated_tcp_congestion_window_ += acked_bytes_count_ * (Alpha() * kDefaultTCPMSS) / estimated_tcp_congestion_window_; acked_bytes_count_ = 0; last_target_congestion_window_ = target_congestion_window; if (target_congestion_window < estimated_tcp_congestion_window_) { target_congestion_window = estimated_tcp_congestion_window_; } QUIC_DVLOG(1) << "Final target congestion_window: " << target_congestion_window; return target_congestion_window; } }
#include "quiche/quic/core/congestion_control/cubic_bytes.h" #include <cmath> #include <cstdint> #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_clock.h" namespace quic { namespace test { namespace { const float kBeta = 0.7f; const float kBetaLastMax = 0.85f; const uint32_t kNumConnections = 2; const float kNConnectionBeta = (kNumConnections - 1 + kBeta) / kNumConnections; const float kNConnectionBetaLastMax = (kNumConnections - 1 + kBetaLastMax) / kNumConnections; const float kNConnectionAlpha = 3 * kNumConnections * kNumConnections * (1 - kNConnectionBeta) / (1 + kNConnectionBeta); } class CubicBytesTest : public QuicTest { protected: CubicBytesTest() : one_ms_(QuicTime::Delta::FromMilliseconds(1)), hundred_ms_(QuicTime::Delta::FromMilliseconds(100)), cubic_(&clock_) {} QuicByteCount RenoCwndInBytes(QuicByteCount current_cwnd) { QuicByteCount reno_estimated_cwnd = current_cwnd + kDefaultTCPMSS * (kNConnectionAlpha * kDefaultTCPMSS) / current_cwnd; return reno_estimated_cwnd; } QuicByteCount ConservativeCwndInBytes(QuicByteCount current_cwnd) { QuicByteCount conservative_cwnd = current_cwnd + kDefaultTCPMSS / 2; return conservative_cwnd; } QuicByteCount CubicConvexCwndInBytes(QuicByteCount initial_cwnd, QuicTime::Delta rtt, QuicTime::Delta elapsed_time) { const int64_t offset = ((elapsed_time + rtt).ToMicroseconds() << 10) / 1000000; const QuicByteCount delta_congestion_window = ((410 * offset * offset * offset) * kDefaultTCPMSS >> 40); const QuicByteCount cubic_cwnd = initial_cwnd + delta_congestion_window; return cubic_cwnd; } QuicByteCount LastMaxCongestionWindow() { return cubic_.last_max_congestion_window(); } QuicTime::Delta MaxCubicTimeInterval() { return cubic_.MaxCubicTimeInterval(); } const QuicTime::Delta one_ms_; const QuicTime::Delta hundred_ms_; MockClock clock_; CubicBytes cubic_; }; TEST_F(CubicBytesTest, AboveOriginWithTighterBounds) { const QuicTime::Delta rtt_min = hundred_ms_; int64_t rtt_min_ms = rtt_min.ToMilliseconds(); float rtt_min_s = rtt_min_ms / 1000.0; QuicByteCount current_cwnd = 10 * kDefaultTCPMSS; const QuicByteCount initial_cwnd = current_cwnd; clock_.AdvanceTime(one_ms_); const QuicTime initial_time = clock_.ApproximateNow(); const QuicByteCount expected_first_cwnd = RenoCwndInBytes(current_cwnd); current_cwnd = cubic_.CongestionWindowAfterAck(kDefaultTCPMSS, current_cwnd, rtt_min, initial_time); ASSERT_EQ(expected_first_cwnd, current_cwnd); const int max_reno_rtts = std::sqrt(kNConnectionAlpha / (.4 * rtt_min_s * rtt_min_s * rtt_min_s)) - 2; for (int i = 0; i < max_reno_rtts; ++i) { const uint64_t num_acks_this_epoch = current_cwnd / kDefaultTCPMSS / kNConnectionAlpha; const QuicByteCount initial_cwnd_this_epoch = current_cwnd; for (QuicPacketCount n = 0; n < num_acks_this_epoch; ++n) { const QuicByteCount expected_next_cwnd = RenoCwndInBytes(current_cwnd); current_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()); ASSERT_EQ(expected_next_cwnd, current_cwnd); } const QuicByteCount cwnd_change_this_epoch = current_cwnd - initial_cwnd_this_epoch; ASSERT_NEAR(kDefaultTCPMSS, cwnd_change_this_epoch, kDefaultTCPMSS / 2); clock_.AdvanceTime(hundred_ms_); } for (int i = 0; i < 54; ++i) { const uint64_t max_acks_this_epoch = current_cwnd / kDefaultTCPMSS; const QuicTime::Delta interval = QuicTime::Delta::FromMicroseconds( hundred_ms_.ToMicroseconds() / max_acks_this_epoch); for (QuicPacketCount n = 0; n < max_acks_this_epoch; ++n) { clock_.AdvanceTime(interval); current_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()); const QuicByteCount expected_cwnd = CubicConvexCwndInBytes( initial_cwnd, rtt_min, (clock_.ApproximateNow() - initial_time)); ASSERT_EQ(expected_cwnd, current_cwnd); } } const QuicByteCount expected_cwnd = CubicConvexCwndInBytes( initial_cwnd, rtt_min, (clock_.ApproximateNow() - initial_time)); current_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()); ASSERT_EQ(expected_cwnd, current_cwnd); } TEST_F(CubicBytesTest, DISABLED_AboveOrigin) { const QuicTime::Delta rtt_min = hundred_ms_; QuicByteCount current_cwnd = 10 * kDefaultTCPMSS; QuicPacketCount expected_cwnd = RenoCwndInBytes(current_cwnd); clock_.AdvanceTime(one_ms_); ASSERT_EQ(expected_cwnd, cubic_.CongestionWindowAfterAck(kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow())); current_cwnd = expected_cwnd; const QuicPacketCount initial_cwnd = expected_cwnd; for (int i = 0; i < 48; ++i) { for (QuicPacketCount n = 1; n < current_cwnd / kDefaultTCPMSS / kNConnectionAlpha; ++n) { ASSERT_NEAR( current_cwnd, cubic_.CongestionWindowAfterAck(kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()), kDefaultTCPMSS); } clock_.AdvanceTime(hundred_ms_); current_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()); expected_cwnd += kDefaultTCPMSS; ASSERT_NEAR(expected_cwnd, current_cwnd, kDefaultTCPMSS); } for (int i = 0; i < 52; ++i) { for (QuicPacketCount n = 1; n < current_cwnd / kDefaultTCPMSS; ++n) { ASSERT_NEAR( current_cwnd, cubic_.CongestionWindowAfterAck(kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()), kDefaultTCPMSS); } clock_.AdvanceTime(hundred_ms_); current_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()); } float elapsed_time_s = 10.0f + 0.1f; expected_cwnd = initial_cwnd / kDefaultTCPMSS + (elapsed_time_s * elapsed_time_s * elapsed_time_s * 410) / 1024; EXPECT_EQ(expected_cwnd, current_cwnd / kDefaultTCPMSS); } TEST_F(CubicBytesTest, AboveOriginFineGrainedCubing) { QuicByteCount current_cwnd = 1000 * kDefaultTCPMSS; const QuicByteCount initial_cwnd = current_cwnd; const QuicTime::Delta rtt_min = hundred_ms_; clock_.AdvanceTime(one_ms_); QuicTime initial_time = clock_.ApproximateNow(); current_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(600)); current_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()); for (int i = 0; i < 100; ++i) { clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10)); const QuicByteCount expected_cwnd = CubicConvexCwndInBytes( initial_cwnd, rtt_min, (clock_.ApproximateNow() - initial_time)); const QuicByteCount next_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()); ASSERT_EQ(expected_cwnd, next_cwnd); ASSERT_GT(next_cwnd, current_cwnd); const QuicByteCount cwnd_delta = next_cwnd - current_cwnd; ASSERT_GT(kDefaultTCPMSS * .1, cwnd_delta); current_cwnd = next_cwnd; } } TEST_F(CubicBytesTest, PerAckUpdates) { QuicPacketCount initial_cwnd_packets = 150; QuicByteCount current_cwnd = initial_cwnd_packets * kDefaultTCPMSS; const QuicTime::Delta rtt_min = 350 * one_ms_; clock_.AdvanceTime(one_ms_); QuicByteCount reno_cwnd = RenoCwndInBytes(current_cwnd); current_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()); const QuicByteCount initial_cwnd = current_cwnd; const QuicPacketCount max_acks = initial_cwnd_packets / kNConnectionAlpha; const QuicTime::Delta interval = QuicTime::Delta::FromMicroseconds( MaxCubicTimeInterval().ToMicroseconds() / (max_acks + 1)); clock_.AdvanceTime(interval); reno_cwnd = RenoCwndInBytes(reno_cwnd); ASSERT_EQ(current_cwnd, cubic_.CongestionWindowAfterAck(kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow())); for (QuicPacketCount i = 1; i < max_acks; ++i) { clock_.AdvanceTime(interval); const QuicByteCount next_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()); reno_cwnd = RenoCwndInBytes(reno_cwnd); ASSERT_LT(current_cwnd, next_cwnd); ASSERT_EQ(reno_cwnd, next_cwnd); current_cwnd = next_cwnd; } const QuicByteCount minimum_expected_increase = kDefaultTCPMSS * .9; EXPECT_LT(minimum_expected_increase + initial_cwnd, current_cwnd); } TEST_F(CubicBytesTest, LossEvents) { const QuicTime::Delta rtt_min = hundred_ms_; QuicByteCount current_cwnd = 422 * kDefaultTCPMSS; QuicPacketCount expected_cwnd = RenoCwndInBytes(current_cwnd); clock_.AdvanceTime(one_ms_); EXPECT_EQ(expected_cwnd, cubic_.CongestionWindowAfterAck(kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow())); QuicByteCount pre_loss_cwnd = current_cwnd; ASSERT_EQ(0u, LastMaxCongestionWindow()); expected_cwnd = static_cast<QuicByteCount>(current_cwnd * kNConnectionBeta); EXPECT_EQ(expected_cwnd, cubic_.CongestionWindowAfterPacketLoss(current_cwnd)); ASSERT_EQ(pre_loss_cwnd, LastMaxCongestionWindow()); current_cwnd = expected_cwnd; pre_loss_cwnd = current_cwnd; expected_cwnd = static_cast<QuicByteCount>(current_cwnd * kNConnectionBeta); ASSERT_EQ(expected_cwnd, cubic_.CongestionWindowAfterPacketLoss(current_cwnd)); current_cwnd = expected_cwnd; EXPECT_GT(pre_loss_cwnd, LastMaxCongestionWindow()); QuicByteCount expected_last_max = static_cast<QuicByteCount>(pre_loss_cwnd * kNConnectionBetaLastMax); EXPECT_EQ(expected_last_max, LastMaxCongestionWindow()); EXPECT_LT(expected_cwnd, LastMaxCongestionWindow()); current_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()); EXPECT_GT(LastMaxCongestionWindow(), current_cwnd); current_cwnd = LastMaxCongestionWindow() - 1; pre_loss_cwnd = current_cwnd; expected_cwnd = static_cast<QuicByteCount>(current_cwnd * kNConnectionBeta); EXPECT_EQ(expected_cwnd, cubic_.CongestionWindowAfterPacketLoss(current_cwnd)); expected_last_max = pre_loss_cwnd; ASSERT_EQ(expected_last_max, LastMaxCongestionWindow()); } TEST_F(CubicBytesTest, BelowOrigin) { const QuicTime::Delta rtt_min = hundred_ms_; QuicByteCount current_cwnd = 422 * kDefaultTCPMSS; QuicPacketCount expected_cwnd = RenoCwndInBytes(current_cwnd); clock_.AdvanceTime(one_ms_); EXPECT_EQ(expected_cwnd, cubic_.CongestionWindowAfterAck(kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow())); expected_cwnd = static_cast<QuicPacketCount>(current_cwnd * kNConnectionBeta); EXPECT_EQ(expected_cwnd, cubic_.CongestionWindowAfterPacketLoss(current_cwnd)); current_cwnd = expected_cwnd; current_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()); for (int i = 0; i < 40; ++i) { clock_.AdvanceTime(hundred_ms_); current_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()); } expected_cwnd = 553632; EXPECT_EQ(expected_cwnd, current_cwnd); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/congestion_control/cubic_bytes.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/congestion_control/cubic_bytes_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
e7f4235a-4f85-4973-acd0-fdcd09f31976
cpp
google/quiche
pacing_sender
quiche/quic/core/congestion_control/pacing_sender.cc
quiche/quic/core/congestion_control/pacing_sender_test.cc
#include "quiche/quic/core/congestion_control/pacing_sender.h" #include <algorithm> #include "quiche/quic/core/quic_bandwidth.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { namespace { static const uint32_t kInitialUnpacedBurst = 10; } PacingSender::PacingSender() : sender_(nullptr), max_pacing_rate_(QuicBandwidth::Zero()), application_driven_pacing_rate_(QuicBandwidth::Infinite()), burst_tokens_(kInitialUnpacedBurst), ideal_next_packet_send_time_(QuicTime::Zero()), initial_burst_size_(kInitialUnpacedBurst), lumpy_tokens_(0), pacing_limited_(false) {} PacingSender::~PacingSender() {} void PacingSender::set_sender(SendAlgorithmInterface* sender) { QUICHE_DCHECK(sender != nullptr); sender_ = sender; } void PacingSender::OnCongestionEvent(bool rtt_updated, QuicByteCount bytes_in_flight, QuicTime event_time, const AckedPacketVector& acked_packets, const LostPacketVector& lost_packets, QuicPacketCount num_ect, QuicPacketCount num_ce) { QUICHE_DCHECK(sender_ != nullptr); if (!lost_packets.empty()) { burst_tokens_ = 0; } sender_->OnCongestionEvent(rtt_updated, bytes_in_flight, event_time, acked_packets, lost_packets, num_ect, num_ce); } void PacingSender::OnPacketSent( QuicTime sent_time, QuicByteCount bytes_in_flight, QuicPacketNumber packet_number, QuicByteCount bytes, HasRetransmittableData has_retransmittable_data) { QUICHE_DCHECK(sender_ != nullptr); QUIC_DVLOG(3) << "Packet " << packet_number << " with " << bytes << " bytes sent at " << sent_time << ". bytes_in_flight: " << bytes_in_flight; sender_->OnPacketSent(sent_time, bytes_in_flight, packet_number, bytes, has_retransmittable_data); if (has_retransmittable_data != HAS_RETRANSMITTABLE_DATA) { return; } if (remove_non_initial_burst_) { QUIC_RELOADABLE_FLAG_COUNT_N(quic_pacing_remove_non_initial_burst, 1, 2); } else { if (bytes_in_flight == 0 && !sender_->InRecovery()) { burst_tokens_ = std::min(initial_burst_size_, static_cast<uint32_t>(sender_->GetCongestionWindow() / kDefaultTCPMSS)); } } if (burst_tokens_ > 0) { --burst_tokens_; ideal_next_packet_send_time_ = QuicTime::Zero(); pacing_limited_ = false; return; } QuicTime::Delta delay = PacingRate(bytes_in_flight + bytes).TransferTime(bytes); if (!pacing_limited_ || lumpy_tokens_ == 0) { lumpy_tokens_ = std::max( 1u, std::min(static_cast<uint32_t>(GetQuicFlag(quic_lumpy_pacing_size)), static_cast<uint32_t>( (sender_->GetCongestionWindow() * GetQuicFlag(quic_lumpy_pacing_cwnd_fraction)) / kDefaultTCPMSS))); if (sender_->BandwidthEstimate() < QuicBandwidth::FromKBitsPerSecond( GetQuicFlag(quic_lumpy_pacing_min_bandwidth_kbps))) { lumpy_tokens_ = 1u; } if ((bytes_in_flight + bytes) >= sender_->GetCongestionWindow()) { lumpy_tokens_ = 1u; } } --lumpy_tokens_; if (pacing_limited_) { ideal_next_packet_send_time_ = ideal_next_packet_send_time_ + delay; } else { ideal_next_packet_send_time_ = std::max(ideal_next_packet_send_time_ + delay, sent_time + delay); } pacing_limited_ = sender_->CanSend(bytes_in_flight + bytes); } void PacingSender::OnApplicationLimited() { pacing_limited_ = false; } void PacingSender::SetBurstTokens(uint32_t burst_tokens) { initial_burst_size_ = burst_tokens; burst_tokens_ = std::min( initial_burst_size_, static_cast<uint32_t>(sender_->GetCongestionWindow() / kDefaultTCPMSS)); } QuicTime::Delta PacingSender::TimeUntilSend( QuicTime now, QuicByteCount bytes_in_flight) const { QUICHE_DCHECK(sender_ != nullptr); if (!sender_->CanSend(bytes_in_flight)) { return QuicTime::Delta::Infinite(); } if (remove_non_initial_burst_) { QUIC_RELOADABLE_FLAG_COUNT_N(quic_pacing_remove_non_initial_burst, 2, 2); if (burst_tokens_ > 0 || lumpy_tokens_ > 0) { QUIC_DVLOG(1) << "Can send packet now. burst_tokens:" << burst_tokens_ << ", lumpy_tokens:" << lumpy_tokens_; return QuicTime::Delta::Zero(); } } else { if (burst_tokens_ > 0 || bytes_in_flight == 0 || lumpy_tokens_ > 0) { QUIC_DVLOG(1) << "Sending packet now. burst_tokens:" << burst_tokens_ << ", bytes_in_flight:" << bytes_in_flight << ", lumpy_tokens:" << lumpy_tokens_; return QuicTime::Delta::Zero(); } } if (ideal_next_packet_send_time_ > now + kAlarmGranularity) { QUIC_DVLOG(1) << "Delaying packet: " << (ideal_next_packet_send_time_ - now).ToMicroseconds(); return ideal_next_packet_send_time_ - now; } QUIC_DVLOG(1) << "Can send packet now. ideal_next_packet_send_time: " << ideal_next_packet_send_time_ << ", now: " << now; return QuicTime::Delta::Zero(); } QuicBandwidth PacingSender::PacingRate(QuicByteCount bytes_in_flight) const { QUICHE_DCHECK(sender_ != nullptr); if (!max_pacing_rate_.IsZero()) { return QuicBandwidth::FromBitsPerSecond( std::min(max_pacing_rate_.ToBitsPerSecond(), sender_->PacingRate(bytes_in_flight).ToBitsPerSecond())); } return sender_->PacingRate(bytes_in_flight); } }
#include "quiche/quic/core/congestion_control/pacing_sender.h" #include <memory> #include <utility> #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_clock.h" #include "quiche/quic/test_tools/quic_test_utils.h" using testing::_; using testing::AtMost; using testing::Return; using testing::StrictMock; namespace quic { namespace test { const QuicByteCount kBytesInFlight = 1024; const int kInitialBurstPackets = 10; class TestPacingSender : public PacingSender { public: using PacingSender::lumpy_tokens; using PacingSender::PacingSender; QuicTime ideal_next_packet_send_time() const { return GetNextReleaseTime().release_time; } }; class PacingSenderTest : public QuicTest { protected: PacingSenderTest() : zero_time_(QuicTime::Delta::Zero()), infinite_time_(QuicTime::Delta::Infinite()), packet_number_(1), mock_sender_(new StrictMock<MockSendAlgorithm>()), pacing_sender_(new TestPacingSender) { pacing_sender_->set_sender(mock_sender_.get()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(9)); } ~PacingSenderTest() override {} void InitPacingRate(QuicPacketCount burst_size, QuicBandwidth bandwidth) { mock_sender_ = std::make_unique<StrictMock<MockSendAlgorithm>>(); pacing_sender_ = std::make_unique<TestPacingSender>(); pacing_sender_->set_sender(mock_sender_.get()); EXPECT_CALL(*mock_sender_, PacingRate(_)).WillRepeatedly(Return(bandwidth)); EXPECT_CALL(*mock_sender_, BandwidthEstimate()) .WillRepeatedly(Return(bandwidth)); if (burst_size == 0) { EXPECT_CALL(*mock_sender_, OnCongestionEvent(_, _, _, _, _, _, _)); LostPacketVector lost_packets; lost_packets.push_back( LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize)); AckedPacketVector empty; pacing_sender_->OnCongestionEvent(true, 1234, clock_.Now(), empty, lost_packets, 0, 0); } else if (burst_size != kInitialBurstPackets) { QUIC_LOG(FATAL) << "Unsupported burst_size " << burst_size << " specificied, only 0 and " << kInitialBurstPackets << " are supported."; } } void CheckPacketIsSentImmediately(HasRetransmittableData retransmittable_data, QuicByteCount prior_in_flight, bool in_recovery, QuicPacketCount cwnd) { for (int i = 0; i < 2; ++i) { EXPECT_CALL(*mock_sender_, CanSend(prior_in_flight)) .WillOnce(Return(true)); EXPECT_EQ(zero_time_, pacing_sender_->TimeUntilSend(clock_.Now(), prior_in_flight)) << "Next packet to send is " << packet_number_; } if (prior_in_flight == 0 && !GetQuicReloadableFlag(quic_pacing_remove_non_initial_burst)) { EXPECT_CALL(*mock_sender_, InRecovery()).WillOnce(Return(in_recovery)); } EXPECT_CALL(*mock_sender_, OnPacketSent(clock_.Now(), prior_in_flight, packet_number_, kMaxOutgoingPacketSize, retransmittable_data)); EXPECT_CALL(*mock_sender_, GetCongestionWindow()) .WillRepeatedly(Return(cwnd * kDefaultTCPMSS)); EXPECT_CALL(*mock_sender_, CanSend(prior_in_flight + kMaxOutgoingPacketSize)) .Times(AtMost(1)) .WillRepeatedly(Return((prior_in_flight + kMaxOutgoingPacketSize) < (cwnd * kDefaultTCPMSS))); pacing_sender_->OnPacketSent(clock_.Now(), prior_in_flight, packet_number_++, kMaxOutgoingPacketSize, retransmittable_data); } void CheckPacketIsSentImmediately() { CheckPacketIsSentImmediately(HAS_RETRANSMITTABLE_DATA, kBytesInFlight, false, 10); } void CheckPacketIsDelayed(QuicTime::Delta delay) { for (int i = 0; i < 2; ++i) { EXPECT_CALL(*mock_sender_, CanSend(kBytesInFlight)) .WillOnce(Return(true)); EXPECT_EQ(delay.ToMicroseconds(), pacing_sender_->TimeUntilSend(clock_.Now(), kBytesInFlight) .ToMicroseconds()); } } void UpdateRtt() { EXPECT_CALL(*mock_sender_, OnCongestionEvent(true, kBytesInFlight, _, _, _, _, _)); AckedPacketVector empty_acked; LostPacketVector empty_lost; pacing_sender_->OnCongestionEvent(true, kBytesInFlight, clock_.Now(), empty_acked, empty_lost, 0, 0); } void OnApplicationLimited() { pacing_sender_->OnApplicationLimited(); } const QuicTime::Delta zero_time_; const QuicTime::Delta infinite_time_; MockClock clock_; QuicPacketNumber packet_number_; std::unique_ptr<StrictMock<MockSendAlgorithm>> mock_sender_; std::unique_ptr<TestPacingSender> pacing_sender_; }; TEST_F(PacingSenderTest, NoSend) { for (int i = 0; i < 2; ++i) { EXPECT_CALL(*mock_sender_, CanSend(kBytesInFlight)).WillOnce(Return(false)); EXPECT_EQ(infinite_time_, pacing_sender_->TimeUntilSend(clock_.Now(), kBytesInFlight)); } } TEST_F(PacingSenderTest, SendNow) { for (int i = 0; i < 2; ++i) { EXPECT_CALL(*mock_sender_, CanSend(kBytesInFlight)).WillOnce(Return(true)); EXPECT_EQ(zero_time_, pacing_sender_->TimeUntilSend(clock_.Now(), kBytesInFlight)); } } TEST_F(PacingSenderTest, VariousSending) { InitPacingRate( 0, QuicBandwidth::FromBytesAndTimeDelta( kMaxOutgoingPacketSize, QuicTime::Delta::FromMilliseconds(1))); UpdateRtt(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(2)); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(4)); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(8)); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(8)); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); OnApplicationLimited(); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100)); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); CheckPacketIsSentImmediately(); } TEST_F(PacingSenderTest, InitialBurst) { InitPacingRate( 10, QuicBandwidth::FromBytesAndTimeDelta( kMaxOutgoingPacketSize, QuicTime::Delta::FromMilliseconds(1))); UpdateRtt(); for (int i = 0; i < kInitialBurstPackets; ++i) { CheckPacketIsSentImmediately(); } CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); if (GetQuicReloadableFlag(quic_pacing_remove_non_initial_burst)) { for (int i = 0; i < 6; ++i) { CheckPacketIsSentImmediately(); } CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(3)); return; } CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(HAS_RETRANSMITTABLE_DATA, 0, false, 10); for (int i = 0; i < kInitialBurstPackets - 1; ++i) { CheckPacketIsSentImmediately(); } CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); } TEST_F(PacingSenderTest, InitialBurstNoRttMeasurement) { InitPacingRate( 10, QuicBandwidth::FromBytesAndTimeDelta( kMaxOutgoingPacketSize, QuicTime::Delta::FromMilliseconds(1))); for (int i = 0; i < kInitialBurstPackets; ++i) { CheckPacketIsSentImmediately(); } CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); if (GetQuicReloadableFlag(quic_pacing_remove_non_initial_burst)) { for (int i = 0; i < 6; ++i) { CheckPacketIsSentImmediately(); } CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(3)); return; } CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(HAS_RETRANSMITTABLE_DATA, 0, false, 10); for (int i = 0; i < kInitialBurstPackets - 1; ++i) { CheckPacketIsSentImmediately(); } CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); } TEST_F(PacingSenderTest, FastSending) { InitPacingRate(10, QuicBandwidth::FromBytesAndTimeDelta( 2 * kMaxOutgoingPacketSize, QuicTime::Delta::FromMilliseconds(1))); UpdateRtt(); for (int i = 0; i < kInitialBurstPackets; ++i) { CheckPacketIsSentImmediately(); } CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMicroseconds(2000)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); if (GetQuicReloadableFlag(quic_pacing_remove_non_initial_burst)) { for (int i = 0; i < 10; ++i) { CheckPacketIsSentImmediately(); } CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); return; } CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(HAS_RETRANSMITTABLE_DATA, 0, false, 10); for (int i = 0; i < kInitialBurstPackets - 1; ++i) { CheckPacketIsSentImmediately(); } CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMicroseconds(2000)); } TEST_F(PacingSenderTest, NoBurstEnteringRecovery) { InitPacingRate( 0, QuicBandwidth::FromBytesAndTimeDelta( kMaxOutgoingPacketSize, QuicTime::Delta::FromMilliseconds(1))); CheckPacketIsSentImmediately(); LostPacketVector lost_packets; lost_packets.push_back( LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize)); AckedPacketVector empty_acked; EXPECT_CALL(*mock_sender_, OnCongestionEvent(true, kMaxOutgoingPacketSize, _, testing::IsEmpty(), _, _, _)); pacing_sender_->OnCongestionEvent(true, kMaxOutgoingPacketSize, clock_.Now(), empty_acked, lost_packets, 0, 0); CheckPacketIsSentImmediately(); EXPECT_CALL(*mock_sender_, CanSend(kMaxOutgoingPacketSize)) .WillOnce(Return(true)); EXPECT_EQ( QuicTime::Delta::FromMilliseconds(2), pacing_sender_->TimeUntilSend(clock_.Now(), kMaxOutgoingPacketSize)); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); } TEST_F(PacingSenderTest, NoBurstInRecovery) { InitPacingRate( 0, QuicBandwidth::FromBytesAndTimeDelta( kMaxOutgoingPacketSize, QuicTime::Delta::FromMilliseconds(1))); UpdateRtt(); CheckPacketIsSentImmediately(HAS_RETRANSMITTABLE_DATA, 0, true, 10); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); } TEST_F(PacingSenderTest, CwndLimited) { InitPacingRate( 0, QuicBandwidth::FromBytesAndTimeDelta( kMaxOutgoingPacketSize, QuicTime::Delta::FromMilliseconds(1))); UpdateRtt(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(2)); CheckPacketIsSentImmediately(HAS_RETRANSMITTABLE_DATA, 2 * kMaxOutgoingPacketSize, false, 2); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100)); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); } TEST_F(PacingSenderTest, LumpyPacingWithInitialBurstToken) { SetQuicFlag(quic_lumpy_pacing_size, 3); SetQuicFlag(quic_lumpy_pacing_cwnd_fraction, 0.5f); InitPacingRate( 10, QuicBandwidth::FromBytesAndTimeDelta( kMaxOutgoingPacketSize, QuicTime::Delta::FromMilliseconds(1))); UpdateRtt(); for (int i = 0; i < kInitialBurstPackets; ++i) { CheckPacketIsSentImmediately(); } CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(3)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3)); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(3)); OnApplicationLimited(); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100)); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(3)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3)); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(HAS_RETRANSMITTABLE_DATA, 20 * kMaxOutgoingPacketSize, false, 20); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100)); CheckPacketIsSentImmediately(HAS_RETRANSMITTABLE_DATA, kBytesInFlight, false, 5); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); } TEST_F(PacingSenderTest, NoLumpyPacingForLowBandwidthFlows) { SetQuicFlag(quic_lumpy_pacing_size, 3); SetQuicFlag(quic_lumpy_pacing_cwnd_fraction, 0.5f); QuicTime::Delta inter_packet_delay = QuicTime::Delta::FromMilliseconds(100); InitPacingRate(kInitialBurstPackets, QuicBandwidth::FromBytesAndTimeDelta(kMaxOutgoingPacketSize, inter_packet_delay)); UpdateRtt(); for (int i = 0; i < kInitialBurstPackets; ++i) { CheckPacketIsSentImmediately(); } CheckPacketIsSentImmediately(); for (int i = 0; i < 200; ++i) { CheckPacketIsDelayed(inter_packet_delay); } } TEST_F(PacingSenderTest, NoBurstsForLumpyPacingWithAckAggregation) { QuicTime::Delta inter_packet_delay = QuicTime::Delta::FromMilliseconds(1); InitPacingRate(kInitialBurstPackets, QuicBandwidth::FromBytesAndTimeDelta(kMaxOutgoingPacketSize, inter_packet_delay)); UpdateRtt(); for (int i = 0; i < kInitialBurstPackets; ++i) { CheckPacketIsSentImmediately(); } CheckPacketIsSentImmediately(HAS_RETRANSMITTABLE_DATA, 10 * kMaxOutgoingPacketSize, false, 10); EXPECT_EQ(0u, pacing_sender_->lumpy_tokens()); CheckPacketIsSentImmediately(HAS_RETRANSMITTABLE_DATA, 10 * kMaxOutgoingPacketSize, false, 10); EXPECT_EQ(0u, pacing_sender_->lumpy_tokens()); CheckPacketIsDelayed(2 * inter_packet_delay); } TEST_F(PacingSenderTest, IdealNextPacketSendTimeWithLumpyPacing) { SetQuicFlag(quic_lumpy_pacing_size, 3); SetQuicFlag(quic_lumpy_pacing_cwnd_fraction, 0.5f); QuicTime::Delta inter_packet_delay = QuicTime::Delta::FromMilliseconds(1); InitPacingRate(kInitialBurstPackets, QuicBandwidth::FromBytesAndTimeDelta(kMaxOutgoingPacketSize, inter_packet_delay)); for (int i = 0; i < kInitialBurstPackets; ++i) { CheckPacketIsSentImmediately(); } CheckPacketIsSentImmediately(); EXPECT_EQ(pacing_sender_->ideal_next_packet_send_time(), clock_.Now() + inter_packet_delay); EXPECT_EQ(pacing_sender_->lumpy_tokens(), 2u); CheckPacketIsSentImmediately(); EXPECT_EQ(pacing_sender_->ideal_next_packet_send_time(), clock_.Now() + 2 * inter_packet_delay); EXPECT_EQ(pacing_sender_->lumpy_tokens(), 1u); CheckPacketIsSentImmediately(); EXPECT_EQ(pacing_sender_->ideal_next_packet_send_time(), clock_.Now() + 3 * inter_packet_delay); EXPECT_EQ(pacing_sender_->lumpy_tokens(), 0u); CheckPacketIsDelayed(3 * inter_packet_delay); clock_.AdvanceTime(3 * inter_packet_delay); CheckPacketIsSentImmediately(); EXPECT_EQ(pacing_sender_->ideal_next_packet_send_time(), clock_.Now() + inter_packet_delay); EXPECT_EQ(pacing_sender_->lumpy_tokens(), 2u); CheckPacketIsSentImmediately(); EXPECT_EQ(pacing_sender_->ideal_next_packet_send_time(), clock_.Now() + 2 * inter_packet_delay); EXPECT_EQ(pacing_sender_->lumpy_tokens(), 1u); CheckPacketIsSentImmediately(); EXPECT_EQ(pacing_sender_->ideal_next_packet_send_time(), clock_.Now() + 3 * inter_packet_delay); EXPECT_EQ(pacing_sender_->lumpy_tokens(), 0u); CheckPacketIsDelayed(3 * inter_packet_delay); clock_.AdvanceTime(4.5 * inter_packet_delay); CheckPacketIsSentImmediately(); EXPECT_EQ(pacing_sender_->ideal_next_packet_send_time(), clock_.Now() - 0.5 * inter_packet_delay); EXPECT_EQ(pacing_sender_->lumpy_tokens(), 2u); CheckPacketIsSentImmediately(); EXPECT_EQ(pacing_sender_->ideal_next_packet_send_time(), clock_.Now() + 0.5 * inter_packet_delay); EXPECT_EQ(pacing_sender_->lumpy_tokens(), 1u); CheckPacketIsSentImmediately(); EXPECT_EQ(pacing_sender_->ideal_next_packet_send_time(), clock_.Now() + 1.5 * inter_packet_delay); EXPECT_EQ(pacing_sender_->lumpy_tokens(), 0u); CheckPacketIsDelayed(1.5 * inter_packet_delay); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/congestion_control/pacing_sender.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/congestion_control/pacing_sender_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
44971ec1-3e87-4c7a-9137-ad2e8869f3ef
cpp
google/quiche
hybrid_slow_start
quiche/quic/core/congestion_control/hybrid_slow_start.cc
quiche/quic/core/congestion_control/hybrid_slow_start_test.cc
#include "quiche/quic/core/congestion_control/hybrid_slow_start.h" #include <algorithm> #include "quiche/quic/platform/api/quic_logging.h" namespace quic { const int64_t kHybridStartLowWindow = 16; const uint32_t kHybridStartMinSamples = 8; const int kHybridStartDelayFactorExp = 3; const int64_t kHybridStartDelayMinThresholdUs = 4000; const int64_t kHybridStartDelayMaxThresholdUs = 16000; HybridSlowStart::HybridSlowStart() : started_(false), hystart_found_(NOT_FOUND), rtt_sample_count_(0), current_min_rtt_(QuicTime::Delta::Zero()) {} void HybridSlowStart::OnPacketAcked(QuicPacketNumber acked_packet_number) { if (IsEndOfRound(acked_packet_number)) { started_ = false; } } void HybridSlowStart::OnPacketSent(QuicPacketNumber packet_number) { last_sent_packet_number_ = packet_number; } void HybridSlowStart::Restart() { started_ = false; hystart_found_ = NOT_FOUND; } void HybridSlowStart::StartReceiveRound(QuicPacketNumber last_sent) { QUIC_DVLOG(1) << "Reset hybrid slow start @" << last_sent; end_packet_number_ = last_sent; current_min_rtt_ = QuicTime::Delta::Zero(); rtt_sample_count_ = 0; started_ = true; } bool HybridSlowStart::IsEndOfRound(QuicPacketNumber ack) const { return !end_packet_number_.IsInitialized() || end_packet_number_ <= ack; } bool HybridSlowStart::ShouldExitSlowStart(QuicTime::Delta latest_rtt, QuicTime::Delta min_rtt, QuicPacketCount congestion_window) { if (!started_) { StartReceiveRound(last_sent_packet_number_); } if (hystart_found_ != NOT_FOUND) { return true; } rtt_sample_count_++; if (rtt_sample_count_ <= kHybridStartMinSamples) { if (current_min_rtt_.IsZero() || current_min_rtt_ > latest_rtt) { current_min_rtt_ = latest_rtt; } } if (rtt_sample_count_ == kHybridStartMinSamples) { int64_t min_rtt_increase_threshold_us = min_rtt.ToMicroseconds() >> kHybridStartDelayFactorExp; min_rtt_increase_threshold_us = std::min(min_rtt_increase_threshold_us, kHybridStartDelayMaxThresholdUs); QuicTime::Delta min_rtt_increase_threshold = QuicTime::Delta::FromMicroseconds(std::max( min_rtt_increase_threshold_us, kHybridStartDelayMinThresholdUs)); if (current_min_rtt_ > min_rtt + min_rtt_increase_threshold) { hystart_found_ = DELAY; } } return congestion_window >= kHybridStartLowWindow && hystart_found_ != NOT_FOUND; } }
#include "quiche/quic/core/congestion_control/hybrid_slow_start.h" #include <memory> #include <utility> #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { class HybridSlowStartTest : public QuicTest { protected: HybridSlowStartTest() : one_ms_(QuicTime::Delta::FromMilliseconds(1)), rtt_(QuicTime::Delta::FromMilliseconds(60)) {} void SetUp() override { slow_start_ = std::make_unique<HybridSlowStart>(); } const QuicTime::Delta one_ms_; const QuicTime::Delta rtt_; std::unique_ptr<HybridSlowStart> slow_start_; }; TEST_F(HybridSlowStartTest, Simple) { QuicPacketNumber packet_number(1); QuicPacketNumber end_packet_number(3); slow_start_->StartReceiveRound(end_packet_number); EXPECT_FALSE(slow_start_->IsEndOfRound(packet_number++)); EXPECT_FALSE(slow_start_->IsEndOfRound(packet_number)); EXPECT_FALSE(slow_start_->IsEndOfRound(packet_number++)); EXPECT_TRUE(slow_start_->IsEndOfRound(packet_number++)); EXPECT_TRUE(slow_start_->IsEndOfRound(packet_number++)); end_packet_number = QuicPacketNumber(20); slow_start_->StartReceiveRound(end_packet_number); while (packet_number < end_packet_number) { EXPECT_FALSE(slow_start_->IsEndOfRound(packet_number++)); } EXPECT_TRUE(slow_start_->IsEndOfRound(packet_number++)); } TEST_F(HybridSlowStartTest, Delay) { const int kHybridStartMinSamples = 8; QuicPacketNumber end_packet_number(1); slow_start_->StartReceiveRound(end_packet_number++); for (int n = 0; n < kHybridStartMinSamples; ++n) { EXPECT_FALSE(slow_start_->ShouldExitSlowStart( rtt_ + QuicTime::Delta::FromMilliseconds(n), rtt_, 100)); } slow_start_->StartReceiveRound(end_packet_number++); for (int n = 1; n < kHybridStartMinSamples; ++n) { EXPECT_FALSE(slow_start_->ShouldExitSlowStart( rtt_ + QuicTime::Delta::FromMilliseconds(n + 10), rtt_, 100)); } EXPECT_TRUE(slow_start_->ShouldExitSlowStart( rtt_ + QuicTime::Delta::FromMilliseconds(10), rtt_, 100)); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/congestion_control/hybrid_slow_start.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/congestion_control/hybrid_slow_start_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
754d61e9-b5a1-4cad-8b5d-16211dc1d4ce
cpp
google/quiche
prague_sender
quiche/quic/core/congestion_control/prague_sender.cc
quiche/quic/core/congestion_control/prague_sender_test.cc
#include "quiche/quic/core/congestion_control/prague_sender.h" #include <algorithm> #include "quiche/quic/core/congestion_control/rtt_stats.h" #include "quiche/quic/core/congestion_control/tcp_cubic_sender_bytes.h" #include "quiche/quic/core/quic_clock.h" #include "quiche/quic/core/quic_connection_stats.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" namespace quic { PragueSender::PragueSender(const QuicClock* clock, const RttStats* rtt_stats, QuicPacketCount initial_tcp_congestion_window, QuicPacketCount max_congestion_window, QuicConnectionStats* stats) : TcpCubicSenderBytes(clock, rtt_stats, false, initial_tcp_congestion_window, max_congestion_window, stats), connection_start_time_(clock->Now()), last_alpha_update_(connection_start_time_) {} void PragueSender::OnCongestionEvent(bool rtt_updated, QuicByteCount prior_in_flight, QuicTime event_time, const AckedPacketVector& acked_packets, const LostPacketVector& lost_packets, QuicPacketCount num_ect, QuicPacketCount num_ce) { if (!ect1_enabled_) { TcpCubicSenderBytes::OnCongestionEvent(rtt_updated, prior_in_flight, event_time, acked_packets, lost_packets, num_ect, num_ce); return; } if (rtt_updated) { rtt_virt_ = std::max(rtt_stats()->smoothed_rtt(), kPragueRttVirtMin); } if (prague_alpha_.has_value()) { ect_count_ += num_ect; ce_count_ += num_ce; if (event_time - last_alpha_update_ > rtt_virt_) { float frac = static_cast<float>(ce_count_) / static_cast<float>(ect_count_ + ce_count_); prague_alpha_ = (1 - kPragueEwmaGain) * *prague_alpha_ + kPragueEwmaGain * frac; last_alpha_update_ = event_time; ect_count_ = 0; ce_count_ = 0; } } else if (num_ce > 0) { last_alpha_update_ = event_time; prague_alpha_ = 1.0; ect_count_ = num_ect; ce_count_ = num_ce; } if (!lost_packets.empty() && last_congestion_response_time_.has_value() && (event_time - *last_congestion_response_time_ < rtt_virt_)) { QuicByteCount previous_reduction = last_congestion_response_size_; last_congestion_response_time_.reset(); set_congestion_window(GetCongestionWindow() + previous_reduction); } if (!reduce_rtt_dependence_) { reduce_rtt_dependence_ = !InSlowStart() && lost_packets.empty() && (event_time - connection_start_time_) > kRoundsBeforeReducedRttDependence * rtt_stats()->smoothed_rtt(); } float congestion_avoidance_deflator; if (reduce_rtt_dependence_) { congestion_avoidance_deflator = static_cast<float>(rtt_stats()->smoothed_rtt().ToMicroseconds()) / static_cast<float>(rtt_virt_.ToMicroseconds()); congestion_avoidance_deflator *= congestion_avoidance_deflator; } else { congestion_avoidance_deflator = 1.0f; } QuicByteCount original_cwnd = GetCongestionWindow(); if (num_ce == 0 || !lost_packets.empty()) { TcpCubicSenderBytes::OnCongestionEvent(rtt_updated, prior_in_flight, event_time, acked_packets, lost_packets, num_ect, num_ce); if (lost_packets.empty() && reduce_rtt_dependence_ && original_cwnd < GetCongestionWindow()) { QuicByteCount cwnd_increase = GetCongestionWindow() - original_cwnd; set_congestion_window(original_cwnd + cwnd_increase * congestion_avoidance_deflator); } return; } if (InSlowStart()) { ExitSlowstart(); } QuicByteCount bytes_acked = 0; for (auto packet : acked_packets) { bytes_acked += packet.bytes_acked; } float ce_fraction = static_cast<float>(num_ce) / static_cast<float>(num_ect + num_ce); QuicByteCount bytes_ce = bytes_acked * ce_fraction; QuicPacketCount ce_packets_remaining = num_ce; bytes_acked -= bytes_ce; if (!last_congestion_response_time_.has_value() || event_time - *last_congestion_response_time_ > rtt_virt_) { last_congestion_response_time_ = event_time; while (ce_packets_remaining > 0) { OnPacketLost(acked_packets.back().packet_number, bytes_ce, prior_in_flight); bytes_ce = 0; ce_packets_remaining--; } QuicByteCount cwnd_reduction = original_cwnd - GetCongestionWindow(); last_congestion_response_size_ = cwnd_reduction * *prague_alpha_; set_congestion_window(original_cwnd - last_congestion_response_size_); set_slowstart_threshold(GetCongestionWindow()); ExitRecovery(); } if (num_ect == 0) { return; } for (const AckedPacket& acked : acked_packets) { OnPacketAcked( acked.packet_number, acked.bytes_acked * (1 - ce_fraction) * congestion_avoidance_deflator, prior_in_flight, event_time); } } CongestionControlType PragueSender::GetCongestionControlType() const { return kPragueCubic; } bool PragueSender::EnableECT1() { ect1_enabled_ = true; return true; } }
#include "quiche/quic/core/congestion_control/prague_sender.h" #include <cstdint> #include <optional> #include "quiche/quic/core/congestion_control/cubic_bytes.h" #include "quiche/quic/core/congestion_control/rtt_stats.h" #include "quiche/quic/core/congestion_control/send_algorithm_interface.h" #include "quiche/quic/core/quic_clock.h" #include "quiche/quic/core/quic_connection_stats.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_packet_number.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_clock.h" namespace quic::test { const uint32_t kInitialCongestionWindowPackets = 10; const uint32_t kMaxCongestionWindowPackets = 200; const QuicTime::Delta kRtt = QuicTime::Delta::FromMilliseconds(10); class PragueSenderPeer : public PragueSender { public: explicit PragueSenderPeer(const QuicClock* clock) : PragueSender(clock, &rtt_stats_, kInitialCongestionWindowPackets, kMaxCongestionWindowPackets, &stats_) {} QuicTimeDelta rtt_virt() const { return rtt_virt_; } bool InReducedRttDependenceMode() const { return reduce_rtt_dependence_; } float alpha() const { return *prague_alpha_; } RttStats rtt_stats_; QuicConnectionStats stats_; }; class PragueSenderTest : public QuicTest { protected: PragueSenderTest() : one_ms_(QuicTime::Delta::FromMilliseconds(1)), sender_(&clock_), packet_number_(1), acked_packet_number_(0), bytes_in_flight_(0), cubic_(&clock_) { EXPECT_TRUE(sender_.EnableECT1()); } int SendAvailableSendWindow() { return SendAvailableSendWindow(kDefaultTCPMSS); } int SendAvailableSendWindow(QuicPacketLength ) { int packets_sent = 0; bool can_send = sender_.CanSend(bytes_in_flight_); while (can_send) { sender_.OnPacketSent(clock_.Now(), bytes_in_flight_, QuicPacketNumber(packet_number_++), kDefaultTCPMSS, HAS_RETRANSMITTABLE_DATA); ++packets_sent; bytes_in_flight_ += kDefaultTCPMSS; can_send = sender_.CanSend(bytes_in_flight_); } return packets_sent; } void AckNPackets(int n, int ce) { EXPECT_LE(ce, n); sender_.rtt_stats_.UpdateRtt(kRtt, QuicTime::Delta::Zero(), clock_.Now()); AckedPacketVector acked_packets; LostPacketVector lost_packets; for (int i = 0; i < n; ++i) { ++acked_packet_number_; acked_packets.push_back( AckedPacket(QuicPacketNumber(acked_packet_number_), kDefaultTCPMSS, QuicTime::Zero())); } sender_.OnCongestionEvent(true, bytes_in_flight_, clock_.Now(), acked_packets, lost_packets, n - ce, ce); bytes_in_flight_ -= n * kDefaultTCPMSS; clock_.AdvanceTime(one_ms_); } void LoseNPackets(int n) { LoseNPackets(n, kDefaultTCPMSS); } void LoseNPackets(int n, QuicPacketLength packet_length) { AckedPacketVector acked_packets; LostPacketVector lost_packets; for (int i = 0; i < n; ++i) { ++acked_packet_number_; lost_packets.push_back( LostPacket(QuicPacketNumber(acked_packet_number_), packet_length)); } sender_.OnCongestionEvent(false, bytes_in_flight_, clock_.Now(), acked_packets, lost_packets, 0, 0); bytes_in_flight_ -= n * packet_length; } void LosePacket(uint64_t packet_number) { AckedPacketVector acked_packets; LostPacketVector lost_packets; lost_packets.push_back( LostPacket(QuicPacketNumber(packet_number), kDefaultTCPMSS)); sender_.OnCongestionEvent(false, bytes_in_flight_, clock_.Now(), acked_packets, lost_packets, 0, 0); bytes_in_flight_ -= kDefaultTCPMSS; } void MaybeUpdateAlpha(float& alpha, QuicTime& last_update, uint64_t& ect, uint64_t& ce) { if (clock_.Now() - last_update > kPragueRttVirtMin) { float frac = static_cast<float>(ce) / static_cast<float>(ect + ce); alpha = (1 - kPragueEwmaGain) * alpha + kPragueEwmaGain * frac; last_update = clock_.Now(); ect = 0; ce = 0; } } const QuicTime::Delta one_ms_; MockClock clock_; PragueSenderPeer sender_; uint64_t packet_number_; uint64_t acked_packet_number_; QuicByteCount bytes_in_flight_; CubicBytes cubic_; }; TEST_F(PragueSenderTest, EcnResponseInCongestionAvoidance) { int num_sent = SendAvailableSendWindow(); QuicByteCount expected_cwnd = sender_.GetCongestionWindow(); LoseNPackets(1); expected_cwnd = cubic_.CongestionWindowAfterPacketLoss(expected_cwnd); EXPECT_EQ(expected_cwnd, sender_.GetCongestionWindow()); for (int i = 1; i < num_sent; ++i) { AckNPackets(1, 0); } EXPECT_EQ(expected_cwnd, sender_.GetCongestionWindow()); EXPECT_EQ(0u, bytes_in_flight_); num_sent = SendAvailableSendWindow(); QuicByteCount original_cwnd = sender_.GetCongestionWindow(); while (sender_.GetCongestionWindow() == original_cwnd) { AckNPackets(1, 0); expected_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS, expected_cwnd, kRtt, clock_.Now()); EXPECT_EQ(expected_cwnd, sender_.GetCongestionWindow()); SendAvailableSendWindow(); } EXPECT_GE(bytes_in_flight_, sender_.GetCongestionWindow()); clock_.AdvanceTime(kRtt); original_cwnd = sender_.GetCongestionWindow(); AckNPackets(2, 1); expected_cwnd = cubic_.CongestionWindowAfterPacketLoss(expected_cwnd); QuicByteCount expected_ssthresh = expected_cwnd; QuicByteCount loss_reduction = original_cwnd - expected_cwnd; expected_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS / 2, expected_cwnd, kRtt, clock_.Now()); expected_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS / 2, expected_cwnd, kRtt, clock_.Now()); EXPECT_EQ(expected_cwnd, sender_.GetCongestionWindow()); EXPECT_EQ(expected_ssthresh, sender_.GetSlowStartThreshold()); AckNPackets(1, 1); EXPECT_EQ(expected_cwnd, sender_.GetCongestionWindow()); LoseNPackets(1); expected_cwnd = cubic_.CongestionWindowAfterPacketLoss(expected_cwnd + loss_reduction); EXPECT_EQ(expected_cwnd, sender_.GetCongestionWindow()); EXPECT_EQ(expected_cwnd, sender_.GetSlowStartThreshold()); EXPECT_EQ(sender_.rtt_virt().ToMilliseconds(), 25); } TEST_F(PragueSenderTest, EcnResponseInSlowStart) { SendAvailableSendWindow(); AckNPackets(1, 1); EXPECT_FALSE(sender_.InSlowStart()); } TEST_F(PragueSenderTest, ReducedRttDependence) { float expected_alpha; uint64_t num_ect = 0; uint64_t num_ce = 0; std::optional<QuicTime> last_alpha_update; std::optional<QuicTime> last_decrease; while (!sender_.InReducedRttDependenceMode()) { int num_sent = SendAvailableSendWindow(); clock_.AdvanceTime(kRtt); for (int i = 0; (i < num_sent - 1); ++i) { if (last_alpha_update.has_value()) { ++num_ect; MaybeUpdateAlpha(expected_alpha, last_alpha_update.value(), num_ect, num_ce); } AckNPackets(1, 0); } QuicByteCount cwnd = sender_.GetCongestionWindow(); num_ce++; if (last_alpha_update.has_value()) { MaybeUpdateAlpha(expected_alpha, last_alpha_update.value(), num_ect, num_ce); } else { expected_alpha = 1.0; last_alpha_update = clock_.Now(); } AckNPackets(1, 1); bool simulated_loss = false; if (!last_decrease.has_value() || (clock_.Now() - last_decrease.value() > sender_.rtt_virt())) { QuicByteCount new_cwnd = cubic_.CongestionWindowAfterPacketLoss(cwnd); QuicByteCount reduction = (cwnd - new_cwnd) * expected_alpha; cwnd -= reduction; last_decrease = clock_.Now(); simulated_loss = true; } EXPECT_EQ(expected_alpha, sender_.alpha()); EXPECT_EQ(cwnd, sender_.GetCongestionWindow()); if (simulated_loss) { EXPECT_EQ(cwnd, sender_.GetSlowStartThreshold()); } } SendAvailableSendWindow(); QuicByteCount expected_cwnd = sender_.GetCongestionWindow(); QuicByteCount expected_increase = cubic_.CongestionWindowAfterAck(kDefaultTCPMSS, expected_cwnd, kRtt, clock_.Now()) - expected_cwnd; expected_increase = static_cast<float>(expected_increase) / (2.5 * 2.5); AckNPackets(1, 0); EXPECT_EQ(expected_cwnd + expected_increase, sender_.GetCongestionWindow()); } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/congestion_control/prague_sender.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/congestion_control/prague_sender_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
0db15f84-b317-42b6-b4e2-ea434fdcf309
cpp
google/quiche
uber_loss_algorithm
quiche/quic/core/congestion_control/uber_loss_algorithm.cc
quiche/quic/core/congestion_control/uber_loss_algorithm_test.cc
#include "quiche/quic/core/congestion_control/uber_loss_algorithm.h" #include <algorithm> #include <memory> #include <utility> #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" namespace quic { UberLossAlgorithm::UberLossAlgorithm() { for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) { general_loss_algorithms_[i].Initialize(static_cast<PacketNumberSpace>(i), this); } } void UberLossAlgorithm::SetFromConfig(const QuicConfig& config, Perspective perspective) { if (config.HasClientRequestedIndependentOption(kELDT, perspective) && tuner_ != nullptr) { tuning_configured_ = true; MaybeStartTuning(); } } LossDetectionInterface::DetectionStats UberLossAlgorithm::DetectLosses( const QuicUnackedPacketMap& unacked_packets, QuicTime time, const RttStats& rtt_stats, QuicPacketNumber , const AckedPacketVector& packets_acked, LostPacketVector* packets_lost) { DetectionStats overall_stats; for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) { const QuicPacketNumber largest_acked = unacked_packets.GetLargestAckedOfPacketNumberSpace( static_cast<PacketNumberSpace>(i)); if (!largest_acked.IsInitialized() || unacked_packets.GetLeastUnacked() > largest_acked) { continue; } DetectionStats stats = general_loss_algorithms_[i].DetectLosses( unacked_packets, time, rtt_stats, largest_acked, packets_acked, packets_lost); overall_stats.sent_packets_max_sequence_reordering = std::max(overall_stats.sent_packets_max_sequence_reordering, stats.sent_packets_max_sequence_reordering); overall_stats.sent_packets_num_borderline_time_reorderings += stats.sent_packets_num_borderline_time_reorderings; overall_stats.total_loss_detection_response_time += stats.total_loss_detection_response_time; } return overall_stats; } QuicTime UberLossAlgorithm::GetLossTimeout() const { QuicTime loss_timeout = QuicTime::Zero(); for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) { const QuicTime timeout = general_loss_algorithms_[i].GetLossTimeout(); if (!loss_timeout.IsInitialized()) { loss_timeout = timeout; continue; } if (timeout.IsInitialized()) { loss_timeout = std::min(loss_timeout, timeout); } } return loss_timeout; } void UberLossAlgorithm::SpuriousLossDetected( const QuicUnackedPacketMap& unacked_packets, const RttStats& rtt_stats, QuicTime ack_receive_time, QuicPacketNumber packet_number, QuicPacketNumber previous_largest_acked) { general_loss_algorithms_[unacked_packets.GetPacketNumberSpace(packet_number)] .SpuriousLossDetected(unacked_packets, rtt_stats, ack_receive_time, packet_number, previous_largest_acked); } void UberLossAlgorithm::SetLossDetectionTuner( std::unique_ptr<LossDetectionTunerInterface> tuner) { if (tuner_ != nullptr) { QUIC_BUG(quic_bug_10469_1) << "LossDetectionTuner can only be set once when session begins."; return; } tuner_ = std::move(tuner); } void UberLossAlgorithm::MaybeStartTuning() { if (tuner_started_ || !tuning_configured_ || !min_rtt_available_ || !user_agent_known_ || !reorder_happened_) { return; } tuner_started_ = tuner_->Start(&tuned_parameters_); if (!tuner_started_) { return; } if (tuned_parameters_.reordering_shift.has_value() && tuned_parameters_.reordering_threshold.has_value()) { QUIC_DLOG(INFO) << "Setting reordering shift to " << *tuned_parameters_.reordering_shift << ", and reordering threshold to " << *tuned_parameters_.reordering_threshold; SetReorderingShift(*tuned_parameters_.reordering_shift); SetReorderingThreshold(*tuned_parameters_.reordering_threshold); } else { QUIC_BUG(quic_bug_10469_2) << "Tuner started but some parameters are missing"; } } void UberLossAlgorithm::OnConfigNegotiated() {} void UberLossAlgorithm::OnMinRttAvailable() { min_rtt_available_ = true; MaybeStartTuning(); } void UberLossAlgorithm::OnUserAgentIdKnown() { user_agent_known_ = true; MaybeStartTuning(); } void UberLossAlgorithm::OnConnectionClosed() { if (tuner_ != nullptr && tuner_started_) { tuner_->Finish(tuned_parameters_); } } void UberLossAlgorithm::OnReorderingDetected() { const bool tuner_started_before = tuner_started_; const bool reorder_happened_before = reorder_happened_; reorder_happened_ = true; MaybeStartTuning(); if (!tuner_started_before && tuner_started_) { if (reorder_happened_before) { QUIC_CODE_COUNT(quic_loss_tuner_started_after_first_reorder); } else { QUIC_CODE_COUNT(quic_loss_tuner_started_on_first_reorder); } } } void UberLossAlgorithm::SetReorderingShift(int reordering_shift) { for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) { general_loss_algorithms_[i].set_reordering_shift(reordering_shift); } } void UberLossAlgorithm::SetReorderingThreshold( QuicPacketCount reordering_threshold) { for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) { general_loss_algorithms_[i].set_reordering_threshold(reordering_threshold); } } void UberLossAlgorithm::EnableAdaptiveReorderingThreshold() { for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) { general_loss_algorithms_[i].set_use_adaptive_reordering_threshold(true); } } void UberLossAlgorithm::DisableAdaptiveReorderingThreshold() { for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) { general_loss_algorithms_[i].set_use_adaptive_reordering_threshold(false); } } void UberLossAlgorithm::EnableAdaptiveTimeThreshold() { for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) { general_loss_algorithms_[i].enable_adaptive_time_threshold(); } } QuicPacketCount UberLossAlgorithm::GetPacketReorderingThreshold() const { return general_loss_algorithms_[APPLICATION_DATA].reordering_threshold(); } int UberLossAlgorithm::GetPacketReorderingShift() const { return general_loss_algorithms_[APPLICATION_DATA].reordering_shift(); } void UberLossAlgorithm::DisablePacketThresholdForRuntPackets() { for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) { general_loss_algorithms_[i].disable_packet_threshold_for_runt_packets(); } } void UberLossAlgorithm::ResetLossDetection(PacketNumberSpace space) { if (space >= NUM_PACKET_NUMBER_SPACES) { QUIC_BUG(quic_bug_10469_3) << "Invalid packet number space: " << space; return; } general_loss_algorithms_[space].Reset(); } }
#include "quiche/quic/core/congestion_control/uber_loss_algorithm.h" #include <memory> #include <optional> #include <utility> #include <vector> #include "quiche/quic/core/congestion_control/rtt_stats.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_clock.h" #include "quiche/quic/test_tools/quic_unacked_packet_map_peer.h" namespace quic { namespace test { namespace { const uint32_t kDefaultLength = 1000; class UberLossAlgorithmTest : public QuicTest { protected: UberLossAlgorithmTest() { unacked_packets_ = std::make_unique<QuicUnackedPacketMap>(Perspective::IS_CLIENT); rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(100), QuicTime::Delta::Zero(), clock_.Now()); EXPECT_LT(0, rtt_stats_.smoothed_rtt().ToMicroseconds()); } void SendPacket(uint64_t packet_number, EncryptionLevel encryption_level) { QuicStreamFrame frame; QuicTransportVersion version = CurrentSupportedVersions()[0].transport_version; frame.stream_id = QuicUtils::GetFirstBidirectionalStreamId( version, Perspective::IS_CLIENT); if (encryption_level == ENCRYPTION_INITIAL) { if (QuicVersionUsesCryptoFrames(version)) { frame.stream_id = QuicUtils::GetFirstBidirectionalStreamId( version, Perspective::IS_CLIENT); } else { frame.stream_id = QuicUtils::GetCryptoStreamId(version); } } SerializedPacket packet(QuicPacketNumber(packet_number), PACKET_1BYTE_PACKET_NUMBER, nullptr, kDefaultLength, false, false); packet.encryption_level = encryption_level; packet.retransmittable_frames.push_back(QuicFrame(frame)); unacked_packets_->AddSentPacket(&packet, NOT_RETRANSMISSION, clock_.Now(), true, true, ECN_NOT_ECT); } void AckPackets(const std::vector<uint64_t>& packets_acked) { packets_acked_.clear(); for (uint64_t acked : packets_acked) { unacked_packets_->RemoveFromInFlight(QuicPacketNumber(acked)); packets_acked_.push_back(AckedPacket( QuicPacketNumber(acked), kMaxOutgoingPacketSize, QuicTime::Zero())); } } void VerifyLosses(uint64_t largest_newly_acked, const AckedPacketVector& packets_acked, const std::vector<uint64_t>& losses_expected) { return VerifyLosses(largest_newly_acked, packets_acked, losses_expected, std::nullopt); } void VerifyLosses( uint64_t largest_newly_acked, const AckedPacketVector& packets_acked, const std::vector<uint64_t>& losses_expected, std::optional<QuicPacketCount> max_sequence_reordering_expected) { LostPacketVector lost_packets; LossDetectionInterface::DetectionStats stats = loss_algorithm_.DetectLosses( *unacked_packets_, clock_.Now(), rtt_stats_, QuicPacketNumber(largest_newly_acked), packets_acked, &lost_packets); if (max_sequence_reordering_expected.has_value()) { EXPECT_EQ(stats.sent_packets_max_sequence_reordering, max_sequence_reordering_expected.value()); } ASSERT_EQ(losses_expected.size(), lost_packets.size()); for (size_t i = 0; i < losses_expected.size(); ++i) { EXPECT_EQ(lost_packets[i].packet_number, QuicPacketNumber(losses_expected[i])); } } MockClock clock_; std::unique_ptr<QuicUnackedPacketMap> unacked_packets_; RttStats rtt_stats_; UberLossAlgorithm loss_algorithm_; AckedPacketVector packets_acked_; }; TEST_F(UberLossAlgorithmTest, ScenarioA) { SendPacket(1, ENCRYPTION_INITIAL); SendPacket(2, ENCRYPTION_ZERO_RTT); SendPacket(3, ENCRYPTION_ZERO_RTT); unacked_packets_->RemoveFromInFlight(QuicPacketNumber(1)); SendPacket(4, ENCRYPTION_INITIAL); AckPackets({1, 4}); unacked_packets_->MaybeUpdateLargestAckedOfPacketNumberSpace( HANDSHAKE_DATA, QuicPacketNumber(4)); VerifyLosses(4, packets_acked_, std::vector<uint64_t>{}, 0); EXPECT_EQ(QuicTime::Zero(), loss_algorithm_.GetLossTimeout()); } TEST_F(UberLossAlgorithmTest, ScenarioB) { SendPacket(3, ENCRYPTION_ZERO_RTT); SendPacket(4, ENCRYPTION_ZERO_RTT); SendPacket(5, ENCRYPTION_FORWARD_SECURE); SendPacket(6, ENCRYPTION_FORWARD_SECURE); AckPackets({4}); unacked_packets_->MaybeUpdateLargestAckedOfPacketNumberSpace( APPLICATION_DATA, QuicPacketNumber(4)); VerifyLosses(4, packets_acked_, std::vector<uint64_t>{}, 1); EXPECT_EQ(clock_.Now() + 1.25 * rtt_stats_.smoothed_rtt(), loss_algorithm_.GetLossTimeout()); AckPackets({6}); unacked_packets_->MaybeUpdateLargestAckedOfPacketNumberSpace( APPLICATION_DATA, QuicPacketNumber(6)); VerifyLosses(6, packets_acked_, std::vector<uint64_t>{3}, 3); EXPECT_EQ(clock_.Now() + 1.25 * rtt_stats_.smoothed_rtt(), loss_algorithm_.GetLossTimeout()); packets_acked_.clear(); clock_.AdvanceTime(1.25 * rtt_stats_.latest_rtt()); VerifyLosses(6, packets_acked_, {5}, 1); } TEST_F(UberLossAlgorithmTest, ScenarioC) { QuicUnackedPacketMapPeer::SetPerspective(unacked_packets_.get(), Perspective::IS_SERVER); SendPacket(1, ENCRYPTION_ZERO_RTT); SendPacket(2, ENCRYPTION_FORWARD_SECURE); SendPacket(3, ENCRYPTION_FORWARD_SECURE); SendPacket(4, ENCRYPTION_FORWARD_SECURE); unacked_packets_->RemoveFromInFlight(QuicPacketNumber(1)); SendPacket(5, ENCRYPTION_ZERO_RTT); AckPackets({4, 5}); unacked_packets_->MaybeUpdateLargestAckedOfPacketNumberSpace( APPLICATION_DATA, QuicPacketNumber(4)); unacked_packets_->MaybeUpdateLargestAckedOfPacketNumberSpace( HANDSHAKE_DATA, QuicPacketNumber(5)); VerifyLosses(5, packets_acked_, std::vector<uint64_t>{}, 2); EXPECT_EQ(clock_.Now() + 1.25 * rtt_stats_.smoothed_rtt(), loss_algorithm_.GetLossTimeout()); packets_acked_.clear(); clock_.AdvanceTime(1.25 * rtt_stats_.latest_rtt()); VerifyLosses(5, packets_acked_, std::vector<uint64_t>{2, 3}, 2); } TEST_F(UberLossAlgorithmTest, PacketInLimbo) { QuicUnackedPacketMapPeer::SetPerspective(unacked_packets_.get(), Perspective::IS_SERVER); SendPacket(1, ENCRYPTION_ZERO_RTT); SendPacket(2, ENCRYPTION_FORWARD_SECURE); SendPacket(3, ENCRYPTION_FORWARD_SECURE); SendPacket(4, ENCRYPTION_ZERO_RTT); SendPacket(5, ENCRYPTION_FORWARD_SECURE); AckPackets({1, 3, 4}); unacked_packets_->MaybeUpdateLargestAckedOfPacketNumberSpace( APPLICATION_DATA, QuicPacketNumber(3)); unacked_packets_->MaybeUpdateLargestAckedOfPacketNumberSpace( HANDSHAKE_DATA, QuicPacketNumber(4)); VerifyLosses(4, packets_acked_, std::vector<uint64_t>{}); SendPacket(6, ENCRYPTION_FORWARD_SECURE); AckPackets({5, 6}); unacked_packets_->MaybeUpdateLargestAckedOfPacketNumberSpace( APPLICATION_DATA, QuicPacketNumber(6)); VerifyLosses(6, packets_acked_, std::vector<uint64_t>{2}); } class TestLossTuner : public LossDetectionTunerInterface { public: TestLossTuner(bool forced_start_result, LossDetectionParameters forced_parameters) : forced_start_result_(forced_start_result), forced_parameters_(std::move(forced_parameters)) {} ~TestLossTuner() override = default; bool Start(LossDetectionParameters* params) override { start_called_ = true; *params = forced_parameters_; return forced_start_result_; } void Finish(const LossDetectionParameters& ) override {} bool start_called() const { return start_called_; } private: bool forced_start_result_; LossDetectionParameters forced_parameters_; bool start_called_ = false; }; TEST_F(UberLossAlgorithmTest, LossDetectionTuning_SetFromConfigFirst) { const int old_reordering_shift = loss_algorithm_.GetPacketReorderingShift(); const QuicPacketCount old_reordering_threshold = loss_algorithm_.GetPacketReorderingThreshold(); loss_algorithm_.OnUserAgentIdKnown(); TestLossTuner* test_tuner = new TestLossTuner( true, LossDetectionParameters{ old_reordering_shift + 1, old_reordering_threshold * 2}); loss_algorithm_.SetLossDetectionTuner( std::unique_ptr<LossDetectionTunerInterface>(test_tuner)); QuicConfig config; QuicTagVector connection_options; connection_options.push_back(kELDT); config.SetInitialReceivedConnectionOptions(connection_options); loss_algorithm_.SetFromConfig(config, Perspective::IS_SERVER); EXPECT_FALSE(test_tuner->start_called()); EXPECT_EQ(old_reordering_shift, loss_algorithm_.GetPacketReorderingShift()); EXPECT_EQ(old_reordering_threshold, loss_algorithm_.GetPacketReorderingThreshold()); loss_algorithm_.OnMinRttAvailable(); EXPECT_FALSE(test_tuner->start_called()); loss_algorithm_.OnReorderingDetected(); EXPECT_TRUE(test_tuner->start_called()); EXPECT_NE(old_reordering_shift, loss_algorithm_.GetPacketReorderingShift()); EXPECT_NE(old_reordering_threshold, loss_algorithm_.GetPacketReorderingThreshold()); } TEST_F(UberLossAlgorithmTest, LossDetectionTuning_OnMinRttAvailableFirst) { const int old_reordering_shift = loss_algorithm_.GetPacketReorderingShift(); const QuicPacketCount old_reordering_threshold = loss_algorithm_.GetPacketReorderingThreshold(); loss_algorithm_.OnUserAgentIdKnown(); TestLossTuner* test_tuner = new TestLossTuner( true, LossDetectionParameters{ old_reordering_shift + 1, old_reordering_threshold * 2}); loss_algorithm_.SetLossDetectionTuner( std::unique_ptr<LossDetectionTunerInterface>(test_tuner)); loss_algorithm_.OnMinRttAvailable(); EXPECT_FALSE(test_tuner->start_called()); EXPECT_EQ(old_reordering_shift, loss_algorithm_.GetPacketReorderingShift()); EXPECT_EQ(old_reordering_threshold, loss_algorithm_.GetPacketReorderingThreshold()); loss_algorithm_.OnReorderingDetected(); EXPECT_FALSE(test_tuner->start_called()); QuicConfig config; QuicTagVector connection_options; connection_options.push_back(kELDT); config.SetInitialReceivedConnectionOptions(connection_options); loss_algorithm_.SetFromConfig(config, Perspective::IS_SERVER); EXPECT_TRUE(test_tuner->start_called()); EXPECT_NE(old_reordering_shift, loss_algorithm_.GetPacketReorderingShift()); EXPECT_NE(old_reordering_threshold, loss_algorithm_.GetPacketReorderingThreshold()); } TEST_F(UberLossAlgorithmTest, LossDetectionTuning_StartFailed) { const int old_reordering_shift = loss_algorithm_.GetPacketReorderingShift(); const QuicPacketCount old_reordering_threshold = loss_algorithm_.GetPacketReorderingThreshold(); loss_algorithm_.OnUserAgentIdKnown(); TestLossTuner* test_tuner = new TestLossTuner( false, LossDetectionParameters{ old_reordering_shift + 1, old_reordering_threshold * 2}); loss_algorithm_.SetLossDetectionTuner( std::unique_ptr<LossDetectionTunerInterface>(test_tuner)); QuicConfig config; QuicTagVector connection_options; connection_options.push_back(kELDT); config.SetInitialReceivedConnectionOptions(connection_options); loss_algorithm_.SetFromConfig(config, Perspective::IS_SERVER); EXPECT_FALSE(test_tuner->start_called()); EXPECT_EQ(old_reordering_shift, loss_algorithm_.GetPacketReorderingShift()); EXPECT_EQ(old_reordering_threshold, loss_algorithm_.GetPacketReorderingThreshold()); loss_algorithm_.OnReorderingDetected(); EXPECT_FALSE(test_tuner->start_called()); loss_algorithm_.OnMinRttAvailable(); EXPECT_TRUE(test_tuner->start_called()); EXPECT_EQ(old_reordering_shift, loss_algorithm_.GetPacketReorderingShift()); EXPECT_EQ(old_reordering_threshold, loss_algorithm_.GetPacketReorderingThreshold()); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/congestion_control/uber_loss_algorithm.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/congestion_control/uber_loss_algorithm_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
9336a6ec-7fe8-48a5-a72c-958db037a159
cpp
google/quiche
simple_session_notifier
quiche/quic/test_tools/simple_session_notifier.cc
quiche/quic/test_tools/simple_session_notifier_test.cc
#include "quiche/quic/test_tools/simple_session_notifier.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { namespace test { SimpleSessionNotifier::SimpleSessionNotifier(QuicConnection* connection) : last_control_frame_id_(kInvalidControlFrameId), least_unacked_(1), least_unsent_(1), connection_(connection) {} SimpleSessionNotifier::~SimpleSessionNotifier() { while (!control_frames_.empty()) { DeleteFrame(&control_frames_.front()); control_frames_.pop_front(); } } SimpleSessionNotifier::StreamState::StreamState() : bytes_total(0), bytes_sent(0), fin_buffered(false), fin_sent(false), fin_outstanding(false), fin_lost(false) {} SimpleSessionNotifier::StreamState::~StreamState() {} QuicConsumedData SimpleSessionNotifier::WriteOrBufferData( QuicStreamId id, QuicByteCount data_length, StreamSendingState state) { return WriteOrBufferData(id, data_length, state, NOT_RETRANSMISSION); } QuicConsumedData SimpleSessionNotifier::WriteOrBufferData( QuicStreamId id, QuicByteCount data_length, StreamSendingState state, TransmissionType transmission_type) { if (!stream_map_.contains(id)) { stream_map_[id] = StreamState(); } StreamState& stream_state = stream_map_.find(id)->second; const bool had_buffered_data = HasBufferedStreamData() || HasBufferedControlFrames(); QuicStreamOffset offset = stream_state.bytes_sent; QUIC_DVLOG(1) << "WriteOrBuffer stream_id: " << id << " [" << offset << ", " << offset + data_length << "), fin: " << (state != NO_FIN); stream_state.bytes_total += data_length; stream_state.fin_buffered = state != NO_FIN; if (had_buffered_data) { QUIC_DLOG(WARNING) << "Connection is write blocked"; return {0, false}; } const size_t length = stream_state.bytes_total - stream_state.bytes_sent; connection_->SetTransmissionType(transmission_type); QuicConsumedData consumed = connection_->SendStreamData(id, length, stream_state.bytes_sent, state); QUIC_DVLOG(1) << "consumed: " << consumed; OnStreamDataConsumed(id, stream_state.bytes_sent, consumed.bytes_consumed, consumed.fin_consumed); return consumed; } void SimpleSessionNotifier::OnStreamDataConsumed(QuicStreamId id, QuicStreamOffset offset, QuicByteCount data_length, bool fin) { StreamState& state = stream_map_.find(id)->second; if (QuicUtils::IsCryptoStreamId(connection_->transport_version(), id) && data_length > 0) { crypto_bytes_transferred_[connection_->encryption_level()].Add( offset, offset + data_length); } state.bytes_sent += data_length; state.fin_sent = fin; state.fin_outstanding = fin; } size_t SimpleSessionNotifier::WriteCryptoData(EncryptionLevel level, QuicByteCount data_length, QuicStreamOffset offset) { crypto_state_[level].bytes_total += data_length; size_t bytes_written = connection_->SendCryptoData(level, data_length, offset); crypto_state_[level].bytes_sent += bytes_written; crypto_bytes_transferred_[level].Add(offset, offset + bytes_written); return bytes_written; } void SimpleSessionNotifier::WriteOrBufferRstStream( QuicStreamId id, QuicRstStreamErrorCode error, QuicStreamOffset bytes_written) { QUIC_DVLOG(1) << "Writing RST_STREAM_FRAME"; const bool had_buffered_data = HasBufferedStreamData() || HasBufferedControlFrames(); control_frames_.emplace_back((QuicFrame(new QuicRstStreamFrame( ++last_control_frame_id_, id, error, bytes_written)))); if (error != QUIC_STREAM_NO_ERROR) { stream_map_.erase(id); } if (had_buffered_data) { QUIC_DLOG(WARNING) << "Connection is write blocked"; return; } WriteBufferedControlFrames(); } void SimpleSessionNotifier::WriteOrBufferWindowUpate( QuicStreamId id, QuicStreamOffset byte_offset) { QUIC_DVLOG(1) << "Writing WINDOW_UPDATE"; const bool had_buffered_data = HasBufferedStreamData() || HasBufferedControlFrames(); QuicControlFrameId control_frame_id = ++last_control_frame_id_; control_frames_.emplace_back( (QuicFrame(QuicWindowUpdateFrame(control_frame_id, id, byte_offset)))); if (had_buffered_data) { QUIC_DLOG(WARNING) << "Connection is write blocked"; return; } WriteBufferedControlFrames(); } void SimpleSessionNotifier::WriteOrBufferPing() { QUIC_DVLOG(1) << "Writing PING_FRAME"; const bool had_buffered_data = HasBufferedStreamData() || HasBufferedControlFrames(); control_frames_.emplace_back( (QuicFrame(QuicPingFrame(++last_control_frame_id_)))); if (had_buffered_data) { QUIC_DLOG(WARNING) << "Connection is write blocked"; return; } WriteBufferedControlFrames(); } void SimpleSessionNotifier::WriteOrBufferAckFrequency( const QuicAckFrequencyFrame& ack_frequency_frame) { QUIC_DVLOG(1) << "Writing ACK_FREQUENCY"; const bool had_buffered_data = HasBufferedStreamData() || HasBufferedControlFrames(); QuicControlFrameId control_frame_id = ++last_control_frame_id_; control_frames_.emplace_back(( QuicFrame(new QuicAckFrequencyFrame(control_frame_id, control_frame_id, ack_frequency_frame.packet_tolerance, ack_frequency_frame.max_ack_delay)))); if (had_buffered_data) { QUIC_DLOG(WARNING) << "Connection is write blocked"; return; } WriteBufferedControlFrames(); } void SimpleSessionNotifier::NeuterUnencryptedData() { if (QuicVersionUsesCryptoFrames(connection_->transport_version())) { for (const auto& interval : crypto_bytes_transferred_[ENCRYPTION_INITIAL]) { QuicCryptoFrame crypto_frame(ENCRYPTION_INITIAL, interval.min(), interval.max() - interval.min()); OnFrameAcked(QuicFrame(&crypto_frame), QuicTime::Delta::Zero(), QuicTime::Zero()); } return; } for (const auto& interval : crypto_bytes_transferred_[ENCRYPTION_INITIAL]) { QuicStreamFrame stream_frame( QuicUtils::GetCryptoStreamId(connection_->transport_version()), false, interval.min(), interval.max() - interval.min()); OnFrameAcked(QuicFrame(stream_frame), QuicTime::Delta::Zero(), QuicTime::Zero()); } } void SimpleSessionNotifier::OnCanWrite() { if (connection_->framer().is_processing_packet()) { QUIC_BUG(simple_notifier_write_mid_packet_processing) << "Try to write mid packet processing."; return; } if (!RetransmitLostCryptoData() || !RetransmitLostControlFrames() || !RetransmitLostStreamData()) { return; } if (!WriteBufferedCryptoData() || !WriteBufferedControlFrames()) { return; } for (const auto& pair : stream_map_) { const auto& state = pair.second; if (!StreamHasBufferedData(pair.first)) { continue; } const size_t length = state.bytes_total - state.bytes_sent; const bool can_bundle_fin = state.fin_buffered && (state.bytes_sent + length == state.bytes_total); connection_->SetTransmissionType(NOT_RETRANSMISSION); QuicConnection::ScopedEncryptionLevelContext context( connection_, connection_->framer().GetEncryptionLevelToSendApplicationData()); QuicConsumedData consumed = connection_->SendStreamData( pair.first, length, state.bytes_sent, can_bundle_fin ? FIN : NO_FIN); QUIC_DVLOG(1) << "Tries to write stream_id: " << pair.first << " [" << state.bytes_sent << ", " << state.bytes_sent + length << "), fin: " << can_bundle_fin << ", and consumed: " << consumed; OnStreamDataConsumed(pair.first, state.bytes_sent, consumed.bytes_consumed, consumed.fin_consumed); if (length != consumed.bytes_consumed || (can_bundle_fin && !consumed.fin_consumed)) { break; } } } void SimpleSessionNotifier::OnStreamReset(QuicStreamId id, QuicRstStreamErrorCode error) { if (error != QUIC_STREAM_NO_ERROR) { stream_map_.erase(id); } } bool SimpleSessionNotifier::WillingToWrite() const { QUIC_DVLOG(1) << "has_buffered_control_frames: " << HasBufferedControlFrames() << " as_lost_control_frames: " << !lost_control_frames_.empty() << " has_buffered_stream_data: " << HasBufferedStreamData() << " has_lost_stream_data: " << HasLostStreamData(); return HasBufferedControlFrames() || !lost_control_frames_.empty() || HasBufferedStreamData() || HasLostStreamData(); } QuicByteCount SimpleSessionNotifier::StreamBytesSent() const { QuicByteCount bytes_sent = 0; for (const auto& pair : stream_map_) { const auto& state = pair.second; bytes_sent += state.bytes_sent; } return bytes_sent; } QuicByteCount SimpleSessionNotifier::StreamBytesToSend() const { QuicByteCount bytes_to_send = 0; for (const auto& pair : stream_map_) { const auto& state = pair.second; bytes_to_send += (state.bytes_total - state.bytes_sent); } return bytes_to_send; } bool SimpleSessionNotifier::OnFrameAcked(const QuicFrame& frame, QuicTime::Delta , QuicTime ) { QUIC_DVLOG(1) << "Acking " << frame; if (frame.type == CRYPTO_FRAME) { StreamState* state = &crypto_state_[frame.crypto_frame->level]; QuicStreamOffset offset = frame.crypto_frame->offset; QuicByteCount data_length = frame.crypto_frame->data_length; QuicIntervalSet<QuicStreamOffset> newly_acked(offset, offset + data_length); newly_acked.Difference(state->bytes_acked); if (newly_acked.Empty()) { return false; } state->bytes_acked.Add(offset, offset + data_length); state->pending_retransmissions.Difference(offset, offset + data_length); return true; } if (frame.type != STREAM_FRAME) { return OnControlFrameAcked(frame); } if (!stream_map_.contains(frame.stream_frame.stream_id)) { return false; } auto* state = &stream_map_.find(frame.stream_frame.stream_id)->second; QuicStreamOffset offset = frame.stream_frame.offset; QuicByteCount data_length = frame.stream_frame.data_length; QuicIntervalSet<QuicStreamOffset> newly_acked(offset, offset + data_length); newly_acked.Difference(state->bytes_acked); const bool fin_newly_acked = frame.stream_frame.fin && state->fin_outstanding; if (newly_acked.Empty() && !fin_newly_acked) { return false; } state->bytes_acked.Add(offset, offset + data_length); if (fin_newly_acked) { state->fin_outstanding = false; state->fin_lost = false; } state->pending_retransmissions.Difference(offset, offset + data_length); return true; } void SimpleSessionNotifier::OnFrameLost(const QuicFrame& frame) { QUIC_DVLOG(1) << "Losting " << frame; if (frame.type == CRYPTO_FRAME) { StreamState* state = &crypto_state_[frame.crypto_frame->level]; QuicStreamOffset offset = frame.crypto_frame->offset; QuicByteCount data_length = frame.crypto_frame->data_length; QuicIntervalSet<QuicStreamOffset> bytes_lost(offset, offset + data_length); bytes_lost.Difference(state->bytes_acked); if (bytes_lost.Empty()) { return; } for (const auto& lost : bytes_lost) { state->pending_retransmissions.Add(lost.min(), lost.max()); } return; } if (frame.type != STREAM_FRAME) { OnControlFrameLost(frame); return; } if (!stream_map_.contains(frame.stream_frame.stream_id)) { return; } auto* state = &stream_map_.find(frame.stream_frame.stream_id)->second; QuicStreamOffset offset = frame.stream_frame.offset; QuicByteCount data_length = frame.stream_frame.data_length; QuicIntervalSet<QuicStreamOffset> bytes_lost(offset, offset + data_length); bytes_lost.Difference(state->bytes_acked); const bool fin_lost = state->fin_outstanding && frame.stream_frame.fin; if (bytes_lost.Empty() && !fin_lost) { return; } for (const auto& lost : bytes_lost) { state->pending_retransmissions.Add(lost.min(), lost.max()); } state->fin_lost = fin_lost; } bool SimpleSessionNotifier::RetransmitFrames(const QuicFrames& frames, TransmissionType type) { QuicConnection::ScopedPacketFlusher retransmission_flusher(connection_); connection_->SetTransmissionType(type); for (const QuicFrame& frame : frames) { if (frame.type == CRYPTO_FRAME) { const StreamState& state = crypto_state_[frame.crypto_frame->level]; const EncryptionLevel current_encryption_level = connection_->encryption_level(); QuicIntervalSet<QuicStreamOffset> retransmission( frame.crypto_frame->offset, frame.crypto_frame->offset + frame.crypto_frame->data_length); retransmission.Difference(state.bytes_acked); for (const auto& interval : retransmission) { QuicStreamOffset offset = interval.min(); QuicByteCount length = interval.max() - interval.min(); connection_->SetDefaultEncryptionLevel(frame.crypto_frame->level); size_t consumed = connection_->SendCryptoData(frame.crypto_frame->level, length, offset); if (consumed < length) { return false; } } connection_->SetDefaultEncryptionLevel(current_encryption_level); } if (frame.type != STREAM_FRAME) { if (GetControlFrameId(frame) == kInvalidControlFrameId) { continue; } QuicFrame copy = CopyRetransmittableControlFrame(frame); if (!connection_->SendControlFrame(copy)) { DeleteFrame(&copy); return false; } continue; } if (!stream_map_.contains(frame.stream_frame.stream_id)) { continue; } const auto& state = stream_map_.find(frame.stream_frame.stream_id)->second; QuicIntervalSet<QuicStreamOffset> retransmission( frame.stream_frame.offset, frame.stream_frame.offset + frame.stream_frame.data_length); EncryptionLevel retransmission_encryption_level = connection_->encryption_level(); if (QuicUtils::IsCryptoStreamId(connection_->transport_version(), frame.stream_frame.stream_id)) { for (size_t i = 0; i < NUM_ENCRYPTION_LEVELS; ++i) { if (retransmission.Intersects(crypto_bytes_transferred_[i])) { retransmission_encryption_level = static_cast<EncryptionLevel>(i); retransmission.Intersection(crypto_bytes_transferred_[i]); break; } } } retransmission.Difference(state.bytes_acked); bool retransmit_fin = frame.stream_frame.fin && state.fin_outstanding; QuicConsumedData consumed(0, false); for (const auto& interval : retransmission) { QuicStreamOffset retransmission_offset = interval.min(); QuicByteCount retransmission_length = interval.max() - interval.min(); const bool can_bundle_fin = retransmit_fin && (retransmission_offset + retransmission_length == state.bytes_sent); QuicConnection::ScopedEncryptionLevelContext context( connection_, QuicUtils::IsCryptoStreamId(connection_->transport_version(), frame.stream_frame.stream_id) ? retransmission_encryption_level : connection_->framer() .GetEncryptionLevelToSendApplicationData()); consumed = connection_->SendStreamData( frame.stream_frame.stream_id, retransmission_length, retransmission_offset, can_bundle_fin ? FIN : NO_FIN); QUIC_DVLOG(1) << "stream " << frame.stream_frame.stream_id << " is forced to retransmit stream data [" << retransmission_offset << ", " << retransmission_offset + retransmission_length << ") and fin: " << can_bundle_fin << ", consumed: " << consumed; if (can_bundle_fin) { retransmit_fin = !consumed.fin_consumed; } if (consumed.bytes_consumed < retransmission_length || (can_bundle_fin && !consumed.fin_consumed)) { return false; } } if (retransmit_fin) { QUIC_DVLOG(1) << "stream " << frame.stream_frame.stream_id << " retransmits fin only frame."; consumed = connection_->SendStreamData(frame.stream_frame.stream_id, 0, state.bytes_sent, FIN); if (!consumed.fin_consumed) { return false; } } } return true; } bool SimpleSessionNotifier::IsFrameOutstanding(const QuicFrame& frame) const { if (frame.type == CRYPTO_FRAME) { QuicStreamOffset offset = frame.crypto_frame->offset; QuicByteCount data_length = frame.crypto_frame->data_length; bool ret = data_length > 0 && !crypto_state_[frame.crypto_frame->level].bytes_acked.Contains( offset, offset + data_length); return ret; } if (frame.type != STREAM_FRAME) { return IsControlFrameOutstanding(frame); } if (!stream_map_.contains(frame.stream_frame.stream_id)) { return false; } const auto& state = stream_map_.find(frame.stream_frame.stream_id)->second; QuicStreamOffset offset = frame.stream_frame.offset; QuicByteCount data_length = frame.stream_frame.data_length; return (data_length > 0 && !state.bytes_acked.Contains(offset, offset + data_length)) || (frame.stream_frame.fin && state.fin_outstanding); } bool SimpleSessionNotifier::HasUnackedCryptoData() const { if (QuicVersionUsesCryptoFrames(connection_->transport_version())) { for (size_t i = 0; i < NUM_ENCRYPTION_LEVELS; ++i) { const StreamState& state = crypto_state_[i]; if (state.bytes_total > state.bytes_sent) { return true; } QuicIntervalSet<QuicStreamOffset> bytes_to_ack(0, state.bytes_total); bytes_to_ack.Difference(state.bytes_acked); if (!bytes_to_ack.Empty()) { return true; } } return false; } if (!stream_map_.contains( QuicUtils::GetCryptoStreamId(connection_->transport_version()))) { return false; } const auto& state = stream_map_ .find(QuicUtils::GetCryptoStreamId(connection_->transport_version())) ->second; if (state.bytes_total > state.bytes_sent) { return true; } QuicIntervalSet<QuicStreamOffset> bytes_to_ack(0, state.bytes_total); bytes_to_ack.Difference(state.bytes_acked); return !bytes_to_ack.Empty(); } bool SimpleSessionNotifier::HasUnackedStreamData() const { for (const auto& it : stream_map_) { if (StreamIsWaitingForAcks(it.first)) return true; } return false; } bool SimpleSessionNotifier::OnControlFrameAcked(const QuicFrame& frame) { QuicControlFrameId id = GetControlFrameId(frame); if (id == kInvalidControlFrameId) { return false; } QUICHE_DCHECK(id < least_unacked_ + control_frames_.size()); if (id < least_unacked_ || GetControlFrameId(control_frames_.at(id - least_unacked_)) == kInvalidControlFrameId) { return false; } SetControlFrameId(kInvalidControlFrameId, &control_frames_.at(id - least_unacked_)); lost_control_frames_.erase(id); while (!control_frames_.empty() && GetControlFrameId(control_frames_.front()) == kInvalidControlFrameId) { DeleteFrame(&control_frames_.front()); control_frames_.pop_front(); ++least_unacked_; } return true; } void SimpleSessionNotifier::OnControlFrameLost(const QuicFrame& frame) { QuicControlFrameId id = GetControlFrameId(frame); if (id == kInvalidControlFrameId) { return; } QUICHE_DCHECK(id < least_unacked_ + control_frames_.size()); if (id < least_unacked_ || GetControlFrameId(control_frames_.at(id - least_unacked_)) == kInvalidControlFrameId) { return; } if (!lost_control_frames_.contains(id)) { lost_control_frames_[id] = true; } } bool SimpleSessionNotifier::IsControlFrameOutstanding( const QuicFrame& frame) const { QuicControlFrameId id = GetControlFrameId(frame); if (id == kInvalidControlFrameId) { return false; } return id < least_unacked_ + control_frames_.size() && id >= least_unacked_ && GetControlFrameId(control_frames_.at(id - least_unacked_)) != kInvalidControlFrameId; } bool SimpleSessionNotifier::RetransmitLostControlFrames() { while (!lost_control_frames_.empty()) { QuicFrame pending = control_frames_.at(lost_control_frames_.begin()->first - least_unacked_); QuicFrame copy = CopyRetransmittableControlFrame(pending); connection_->SetTransmissionType(LOSS_RETRANSMISSION); if (!connection_->SendControlFrame(copy)) { DeleteFrame(&copy); break; } lost_control_frames_.pop_front(); } return lost_control_frames_.empty(); } bool SimpleSessionNotifier::RetransmitLostCryptoData() { if (QuicVersionUsesCryptoFrames(connection_->transport_version())) { for (EncryptionLevel level : {ENCRYPTION_INITIAL, ENCRYPTION_HANDSHAKE, ENCRYPTION_ZERO_RTT, ENCRYPTION_FORWARD_SECURE}) { auto& state = crypto_state_[level]; while (!state.pending_retransmissions.Empty()) { connection_->SetTransmissionType(HANDSHAKE_RETRANSMISSION); EncryptionLevel current_encryption_level = connection_->encryption_level(); connection_->SetDefaultEncryptionLevel(level); QuicIntervalSet<QuicStreamOffset> retransmission( state.pending_retransmissions.begin()->min(), state.pending_retransmissions.begin()->max()); retransmission.Intersection(crypto_bytes_transferred_[level]); QuicStreamOffset retransmission_offset = retransmission.begin()->min(); QuicByteCount retransmission_length = retransmission.begin()->max() - retransmission.begin()->min(); size_t bytes_consumed = connection_->SendCryptoData( level, retransmission_length, retransmission_offset); connection_->SetDefaultEncryptionLevel(current_encryption_level); state.pending_retransmissions.Difference( retransmission_offset, retransmission_offset + bytes_consumed); if (bytes_consumed < retransmission_length) { return false; } } } return true; } if (!stream_map_.contains( QuicUtils::GetCryptoStreamId(connection_->transport_version()))) { return true; } auto& state = stream_map_ .find(QuicUtils::GetCryptoStreamId(connection_->transport_version())) ->second; while (!state.pending_retransmissions.Empty()) { connection_->SetTransmissionType(HANDSHAKE_RETRANSMISSION); QuicIntervalSet<QuicStreamOffset> retransmission( state.pending_retransmissions.begin()->min(), state.pending_retransmissions.begin()->max()); EncryptionLevel retransmission_encryption_level = ENCRYPTION_INITIAL; for (size_t i = 0; i < NUM_ENCRYPTION_LEVELS; ++i) { if (retransmission.Intersects(crypto_bytes_transferred_[i])) { retransmission_encryption_level = static_cast<EncryptionLevel>(i); retransmission.Intersection(crypto_bytes_transferred_[i]); break; } } QuicStreamOffset retransmission_offset = retransmission.begin()->min(); QuicByteCount retransmission_length = retransmission.begin()->max() - retransmission.begin()->min(); EncryptionLevel current_encryption_level = connection_->encryption_level(); connection_->SetDefaultEncryptionLevel(retransmission_encryption_level); QuicConsumedData consumed = connection_->SendStreamData( QuicUtils::GetCryptoStreamId(connection_->transport_version()), retransmission_length, retransmission_offset, NO_FIN); connection_->SetDefaultEncryptionLevel(current_encryption_level); state.pending_retransmissions.Difference( retransmission_offset, retransmission_offset + consumed.bytes_consumed); if (consumed.bytes_consumed < retransmission_length) { break; } } return state.pending_retransmissions.Empty(); } bool SimpleSessionNotifier::RetransmitLostStreamData() { for (auto& pair : stream_map_) { StreamState& state = pair.second; QuicConsumedData consumed(0, false); while (!state.pending_retransmissions.Empty() || state.fin_lost) { connection_->SetTransmissionType(LOSS_RETRANSMISSION); if (state.pending_retransmissions.Empty()) { QUIC_DVLOG(1) << "stream " << pair.first << " retransmits fin only frame."; consumed = connection_->SendStreamData(pair.first, 0, state.bytes_sent, FIN); state.fin_lost = !consumed.fin_consumed; if (state.fin_lost) { QUIC_DLOG(INFO) << "Connection is write blocked"; return false; } } else { QuicStreamOffset offset = state.pending_retransmissions.begin()->min(); QuicByteCount length = state.pending_retransmissions.begin()->max() - state.pending_retransmissions.begin()->min(); const bool can_bundle_fin = state.fin_lost && (offset + length == state.bytes_sent); consumed = connection_->SendStreamData(pair.first, length, offset, can_bundle_fin ? FIN : NO_FIN); QUIC_DVLOG(1) << "stream " << pair.first << " tries to retransmit stream data [" << offset << ", " << offset + length << ") and fin: " << can_bundle_fin << ", consumed: " << consumed; state.pending_retransmissions.Difference( offset, offset + consumed.bytes_consumed); if (consumed.fin_consumed) { state.fin_lost = false; } if (length > consumed.bytes_consumed || (can_bundle_fin && !consumed.fin_consumed)) { QUIC_DVLOG(1) << "Connection is write blocked"; break; } } } } return !HasLostStreamData(); } bool SimpleSessionNotifier::WriteBufferedCryptoData() { for (size_t i = 0; i < NUM_ENCRYPTION_LEVELS; ++i) { const StreamState& state = crypto_state_[i]; QuicIntervalSet<QuicStreamOffset> buffered_crypto_data(0, state.bytes_total); buffered_crypto_data.Difference(crypto_bytes_transferred_[i]); for (const auto& interval : buffered_crypto_data) { size_t bytes_written = connection_->SendCryptoData( static_cast<EncryptionLevel>(i), interval.Length(), interval.min()); crypto_state_[i].bytes_sent += bytes_written; crypto_bytes_transferred_[i].Add(interval.min(), interval.min() + bytes_written); if (bytes_written < interval.Length()) { return false; } } } return true; } bool SimpleSessionNotifier::WriteBufferedControlFrames() { while (HasBufferedControlFrames()) { QuicFrame frame_to_send = control_frames_.at(least_unsent_ - least_unacked_); QuicFrame copy = CopyRetransmittableControlFrame(frame_to_send); connection_->SetTransmissionType(NOT_RETRANSMISSION); if (!connection_->SendControlFrame(copy)) { DeleteFrame(&copy); break; } ++least_unsent_; } return !HasBufferedControlFrames(); } bool SimpleSessionNotifier::HasBufferedControlFrames() const { return least_unsent_ < least_unacked_ + control_frames_.size(); } bool SimpleSessionNotifier::HasBufferedStreamData() const { for (const auto& pair : stream_map_) { const auto& state = pair.second; if (state.bytes_total > state.bytes_sent || (state.fin_buffered && !state.fin_sent)) { return true; } } return false; } bool SimpleSessionNotifier::StreamIsWaitingForAcks(QuicStreamId id) const { if (!stream_map_.contains(id)) { return false; } const StreamState& state = stream_map_.find(id)->second; return !state.bytes_acked.Contains(0, state.bytes_sent) || state.fin_outstanding; } bool SimpleSessionNotifier::StreamHasBufferedData(QuicStreamId id) const { if (!stream_map_.contains(id)) { return false; } const StreamState& state = stream_map_.find(id)->second; return state.bytes_total > state.bytes_sent || (state.fin_buffered && !state.fin_sent); } bool SimpleSessionNotifier::HasLostStreamData() const { for (const auto& pair : stream_map_) { const auto& state = pair.second; if (!state.pending_retransmissions.Empty() || state.fin_lost) { return true; } } return false; } } }
#include "quiche/quic/test_tools/simple_session_notifier.h" #include <memory> #include <string> #include <utility> #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_connection_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/simple_data_producer.h" using testing::_; using testing::InSequence; using testing::Return; using testing::StrictMock; namespace quic { namespace test { namespace { class MockQuicConnectionWithSendStreamData : public MockQuicConnection { public: MockQuicConnectionWithSendStreamData(MockQuicConnectionHelper* helper, MockAlarmFactory* alarm_factory, Perspective perspective) : MockQuicConnection(helper, alarm_factory, perspective) {} MOCK_METHOD(QuicConsumedData, SendStreamData, (QuicStreamId id, size_t write_length, QuicStreamOffset offset, StreamSendingState state), (override)); }; class SimpleSessionNotifierTest : public QuicTest { public: SimpleSessionNotifierTest() : connection_(&helper_, &alarm_factory_, Perspective::IS_CLIENT), notifier_(&connection_) { connection_.set_visitor(&visitor_); connection_.SetSessionNotifier(&notifier_); EXPECT_FALSE(notifier_.WillingToWrite()); EXPECT_EQ(0u, notifier_.StreamBytesSent()); EXPECT_FALSE(notifier_.HasBufferedStreamData()); } bool ControlFrameConsumed(const QuicFrame& frame) { DeleteFrame(&const_cast<QuicFrame&>(frame)); return true; } MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; MockQuicConnectionVisitor visitor_; StrictMock<MockQuicConnectionWithSendStreamData> connection_; SimpleSessionNotifier notifier_; }; TEST_F(SimpleSessionNotifierTest, WriteOrBufferData) { InSequence s; EXPECT_CALL(connection_, SendStreamData(3, 1024, 0, NO_FIN)) .WillOnce(Return(QuicConsumedData(1024, false))); notifier_.WriteOrBufferData(3, 1024, NO_FIN); EXPECT_EQ(0u, notifier_.StreamBytesToSend()); EXPECT_CALL(connection_, SendStreamData(5, 512, 0, NO_FIN)) .WillOnce(Return(QuicConsumedData(512, false))); notifier_.WriteOrBufferData(5, 512, NO_FIN); EXPECT_FALSE(notifier_.WillingToWrite()); EXPECT_CALL(connection_, SendStreamData(5, 512, 512, FIN)) .WillOnce(Return(QuicConsumedData(256, false))); notifier_.WriteOrBufferData(5, 512, FIN); EXPECT_TRUE(notifier_.WillingToWrite()); EXPECT_EQ(1792u, notifier_.StreamBytesSent()); EXPECT_EQ(256u, notifier_.StreamBytesToSend()); EXPECT_TRUE(notifier_.HasBufferedStreamData()); EXPECT_CALL(connection_, SendStreamData(7, 1024, 0, FIN)).Times(0); notifier_.WriteOrBufferData(7, 1024, FIN); EXPECT_EQ(1792u, notifier_.StreamBytesSent()); } TEST_F(SimpleSessionNotifierTest, WriteOrBufferRstStream) { InSequence s; EXPECT_CALL(connection_, SendStreamData(5, 1024, 0, FIN)) .WillOnce(Return(QuicConsumedData(1024, true))); notifier_.WriteOrBufferData(5, 1024, FIN); EXPECT_TRUE(notifier_.StreamIsWaitingForAcks(5)); EXPECT_TRUE(notifier_.HasUnackedStreamData()); EXPECT_CALL(connection_, SendControlFrame(_)) .WillRepeatedly( Invoke(this, &SimpleSessionNotifierTest::ControlFrameConsumed)); notifier_.WriteOrBufferRstStream(5, QUIC_STREAM_NO_ERROR, 1024); EXPECT_TRUE(notifier_.StreamIsWaitingForAcks(5)); EXPECT_TRUE(notifier_.HasUnackedStreamData()); notifier_.WriteOrBufferRstStream(5, QUIC_ERROR_PROCESSING_STREAM, 1024); EXPECT_FALSE(notifier_.StreamIsWaitingForAcks(5)); EXPECT_FALSE(notifier_.HasUnackedStreamData()); } TEST_F(SimpleSessionNotifierTest, WriteOrBufferPing) { InSequence s; EXPECT_CALL(connection_, SendControlFrame(_)) .WillRepeatedly( Invoke(this, &SimpleSessionNotifierTest::ControlFrameConsumed)); notifier_.WriteOrBufferPing(); EXPECT_EQ(0u, notifier_.StreamBytesToSend()); EXPECT_FALSE(notifier_.WillingToWrite()); EXPECT_CALL(connection_, SendStreamData(3, 1024, 0, NO_FIN)) .WillOnce(Return(QuicConsumedData(1024, false))); notifier_.WriteOrBufferData(3, 1024, NO_FIN); EXPECT_EQ(0u, notifier_.StreamBytesToSend()); EXPECT_CALL(connection_, SendStreamData(5, 512, 0, NO_FIN)) .WillOnce(Return(QuicConsumedData(256, false))); notifier_.WriteOrBufferData(5, 512, NO_FIN); EXPECT_TRUE(notifier_.WillingToWrite()); EXPECT_CALL(connection_, SendControlFrame(_)).Times(0); notifier_.WriteOrBufferPing(); } TEST_F(SimpleSessionNotifierTest, NeuterUnencryptedData) { if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { return; } InSequence s; connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); EXPECT_CALL(connection_, SendStreamData(QuicUtils::GetCryptoStreamId( connection_.transport_version()), 1024, 0, NO_FIN)) .WillOnce(Return(QuicConsumedData(1024, false))); notifier_.WriteOrBufferData( QuicUtils::GetCryptoStreamId(connection_.transport_version()), 1024, NO_FIN); connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); EXPECT_CALL(connection_, SendStreamData(QuicUtils::GetCryptoStreamId( connection_.transport_version()), 1024, 1024, NO_FIN)) .WillOnce(Return(QuicConsumedData(1024, false))); notifier_.WriteOrBufferData( QuicUtils::GetCryptoStreamId(connection_.transport_version()), 1024, NO_FIN); QuicStreamFrame stream_frame( QuicUtils::GetCryptoStreamId(connection_.transport_version()), false, 1024, 1024); notifier_.OnFrameAcked(QuicFrame(stream_frame), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_TRUE(notifier_.StreamIsWaitingForAcks( QuicUtils::GetCryptoStreamId(connection_.transport_version()))); EXPECT_TRUE(notifier_.HasUnackedStreamData()); notifier_.NeuterUnencryptedData(); EXPECT_FALSE(notifier_.StreamIsWaitingForAcks( QuicUtils::GetCryptoStreamId(connection_.transport_version()))); EXPECT_FALSE(notifier_.HasUnackedStreamData()); } TEST_F(SimpleSessionNotifierTest, OnCanWrite) { if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { return; } InSequence s; connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); EXPECT_CALL(connection_, SendStreamData(QuicUtils::GetCryptoStreamId( connection_.transport_version()), 1024, 0, NO_FIN)) .WillOnce(Return(QuicConsumedData(1024, false))); notifier_.WriteOrBufferData( QuicUtils::GetCryptoStreamId(connection_.transport_version()), 1024, NO_FIN); connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); EXPECT_CALL(connection_, SendStreamData(QuicUtils::GetCryptoStreamId( connection_.transport_version()), 1024, 1024, NO_FIN)) .WillOnce(Return(QuicConsumedData(1024, false))); notifier_.WriteOrBufferData( QuicUtils::GetCryptoStreamId(connection_.transport_version()), 1024, NO_FIN); EXPECT_CALL(connection_, SendStreamData(3, 1024, 0, FIN)) .WillOnce(Return(QuicConsumedData(512, false))); notifier_.WriteOrBufferData(3, 1024, FIN); EXPECT_CALL(connection_, SendStreamData(5, _, _, _)).Times(0); notifier_.WriteOrBufferData(5, 1024, NO_FIN); EXPECT_CALL(connection_, SendControlFrame(_)).Times(0); notifier_.WriteOrBufferRstStream(5, QUIC_ERROR_PROCESSING_STREAM, 1024); QuicStreamFrame frame1( QuicUtils::GetCryptoStreamId(connection_.transport_version()), false, 500, 1000); QuicStreamFrame frame2(3, false, 0, 512); notifier_.OnFrameLost(QuicFrame(frame1)); notifier_.OnFrameLost(QuicFrame(frame2)); EXPECT_CALL(connection_, SendStreamData(QuicUtils::GetCryptoStreamId( connection_.transport_version()), 524, 500, NO_FIN)) .WillOnce(Return(QuicConsumedData(524, false))); EXPECT_CALL(connection_, SendStreamData(QuicUtils::GetCryptoStreamId( connection_.transport_version()), 476, 1024, NO_FIN)) .WillOnce(Return(QuicConsumedData(476, false))); EXPECT_CALL(connection_, SendStreamData(3, 512, 0, NO_FIN)) .WillOnce(Return(QuicConsumedData(512, false))); EXPECT_CALL(connection_, SendControlFrame(_)) .WillOnce(Invoke(this, &SimpleSessionNotifierTest::ControlFrameConsumed)); EXPECT_CALL(connection_, SendStreamData(3, 512, 512, FIN)) .WillOnce(Return(QuicConsumedData(512, true))); notifier_.OnCanWrite(); EXPECT_FALSE(notifier_.WillingToWrite()); } TEST_F(SimpleSessionNotifierTest, OnCanWriteCryptoFrames) { if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) { return; } SimpleDataProducer producer; connection_.SetDataProducer(&producer); InSequence s; connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); EXPECT_CALL(connection_, SendCryptoData(ENCRYPTION_INITIAL, 1024, 0)) .WillOnce(Invoke(&connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); EXPECT_CALL(connection_, CloseConnection(QUIC_PACKET_WRITE_ERROR, _, _)); std::string crypto_data1(1024, 'a'); producer.SaveCryptoData(ENCRYPTION_INITIAL, 0, crypto_data1); std::string crypto_data2(524, 'a'); producer.SaveCryptoData(ENCRYPTION_INITIAL, 500, crypto_data2); notifier_.WriteCryptoData(ENCRYPTION_INITIAL, 1024, 0); connection_.SetEncrypter(ENCRYPTION_ZERO_RTT, std::make_unique<NullEncrypter>( Perspective::IS_CLIENT)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); EXPECT_CALL(connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 1024, 0)) .WillOnce(Invoke(&connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); std::string crypto_data3(1024, 'a'); producer.SaveCryptoData(ENCRYPTION_ZERO_RTT, 0, crypto_data3); notifier_.WriteCryptoData(ENCRYPTION_ZERO_RTT, 1024, 0); EXPECT_CALL(connection_, SendStreamData(3, 1024, 0, FIN)) .WillOnce(Return(QuicConsumedData(512, false))); notifier_.WriteOrBufferData(3, 1024, FIN); EXPECT_CALL(connection_, SendStreamData(5, _, _, _)).Times(0); notifier_.WriteOrBufferData(5, 1024, NO_FIN); EXPECT_CALL(connection_, SendControlFrame(_)).Times(0); notifier_.WriteOrBufferRstStream(5, QUIC_ERROR_PROCESSING_STREAM, 1024); QuicCryptoFrame crypto_frame1(ENCRYPTION_INITIAL, 500, 524); QuicCryptoFrame crypto_frame2(ENCRYPTION_ZERO_RTT, 0, 476); QuicStreamFrame stream3_frame(3, false, 0, 512); notifier_.OnFrameLost(QuicFrame(&crypto_frame1)); notifier_.OnFrameLost(QuicFrame(&crypto_frame2)); notifier_.OnFrameLost(QuicFrame(stream3_frame)); EXPECT_CALL(connection_, SendCryptoData(ENCRYPTION_INITIAL, 524, 500)) .WillOnce(Invoke(&connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); EXPECT_CALL(connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 476, 0)) .WillOnce(Invoke(&connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); EXPECT_CALL(connection_, SendStreamData(3, 512, 0, NO_FIN)) .WillOnce(Return(QuicConsumedData(512, false))); EXPECT_CALL(connection_, SendControlFrame(_)) .WillOnce(Invoke(this, &SimpleSessionNotifierTest::ControlFrameConsumed)); EXPECT_CALL(connection_, SendStreamData(3, 512, 512, FIN)) .WillOnce(Return(QuicConsumedData(512, true))); notifier_.OnCanWrite(); EXPECT_FALSE(notifier_.WillingToWrite()); } TEST_F(SimpleSessionNotifierTest, RetransmitFrames) { InSequence s; connection_.SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(Perspective::IS_CLIENT)); EXPECT_CALL(connection_, SendStreamData(3, 10, 0, FIN)) .WillOnce(Return(QuicConsumedData(10, true))); notifier_.WriteOrBufferData(3, 10, FIN); QuicStreamFrame frame1(3, true, 0, 10); EXPECT_CALL(connection_, SendStreamData(5, 10, 0, FIN)) .WillOnce(Return(QuicConsumedData(10, true))); notifier_.WriteOrBufferData(5, 10, FIN); QuicStreamFrame frame2(5, true, 0, 10); EXPECT_CALL(connection_, SendControlFrame(_)) .WillOnce(Invoke(this, &SimpleSessionNotifierTest::ControlFrameConsumed)); notifier_.WriteOrBufferRstStream(5, QUIC_STREAM_NO_ERROR, 10); QuicStreamFrame ack_frame1(3, false, 3, 4); QuicStreamFrame ack_frame2(5, false, 8, 2); notifier_.OnFrameAcked(QuicFrame(ack_frame1), QuicTime::Delta::Zero(), QuicTime::Zero()); notifier_.OnFrameAcked(QuicFrame(ack_frame2), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_FALSE(notifier_.WillingToWrite()); QuicRstStreamFrame rst_stream(1, 5, QUIC_STREAM_NO_ERROR, 10); QuicFrames frames; frames.push_back(QuicFrame(frame2)); frames.push_back(QuicFrame(&rst_stream)); frames.push_back(QuicFrame(frame1)); EXPECT_CALL(connection_, SendStreamData(5, 8, 0, NO_FIN)) .WillOnce(Return(QuicConsumedData(8, false))); EXPECT_CALL(connection_, SendStreamData(5, 0, 10, FIN)) .WillOnce(Return(QuicConsumedData(0, true))); EXPECT_CALL(connection_, SendControlFrame(_)) .WillOnce(Invoke(this, &SimpleSessionNotifierTest::ControlFrameConsumed)); EXPECT_CALL(connection_, SendStreamData(3, 3, 0, NO_FIN)) .WillOnce(Return(QuicConsumedData(2, false))); notifier_.RetransmitFrames(frames, PTO_RETRANSMISSION); EXPECT_FALSE(notifier_.WillingToWrite()); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/test_tools/simple_session_notifier.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/test_tools/simple_session_notifier_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
6884867c-9dbe-412d-b6e1-d8bbf28fb1e0
cpp
google/quiche
test_ip_packets
quiche/quic/test_tools/test_ip_packets.cc
quiche/quic/test_tools/test_ip_packets_test.cc
#include "quiche/quic/test_tools/test_ip_packets.h" #include <cstdint> #include <limits> #include <string> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/internet_checksum.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_data_writer.h" #include "quiche/common/quiche_endian.h" #include "quiche/common/quiche_ip_address.h" #include "quiche/common/quiche_ip_address_family.h" #if defined(__linux__) #include <netinet/in.h> #include <netinet/ip.h> #include <netinet/ip6.h> #include <netinet/udp.h> #endif namespace quic::test { namespace { constexpr uint16_t kIpv4HeaderSize = 20; constexpr uint16_t kIpv6HeaderSize = 40; constexpr uint16_t kUdpHeaderSize = 8; constexpr uint8_t kUdpProtocol = 0x11; #if defined(__linux__) static_assert(kIpv4HeaderSize == sizeof(iphdr)); static_assert(kIpv6HeaderSize == sizeof(ip6_hdr)); static_assert(kUdpHeaderSize == sizeof(udphdr)); static_assert(kUdpProtocol == IPPROTO_UDP); #endif std::string CreateIpv4Header(int payload_length, quiche::QuicheIpAddress source_address, quiche::QuicheIpAddress destination_address, uint8_t protocol) { QUICHE_CHECK_GT(payload_length, 0); QUICHE_CHECK_LE(payload_length, std::numeric_limits<uint16_t>::max() - kIpv4HeaderSize); QUICHE_CHECK(source_address.address_family() == quiche::IpAddressFamily::IP_V4); QUICHE_CHECK(destination_address.address_family() == quiche::IpAddressFamily::IP_V4); std::string header(kIpv4HeaderSize, '\0'); quiche::QuicheDataWriter header_writer(header.size(), header.data()); header_writer.WriteUInt8(0x45); header_writer.WriteUInt8(0x00); header_writer.WriteUInt16(kIpv4HeaderSize + payload_length); header_writer.WriteUInt16(0x0000); header_writer.WriteUInt16(0x0000); header_writer.WriteUInt8(64); header_writer.WriteUInt8(protocol); header_writer.WriteUInt16(0x0000); header_writer.WriteStringPiece(source_address.ToPackedString()); header_writer.WriteStringPiece(destination_address.ToPackedString()); QUICHE_CHECK_EQ(header_writer.remaining(), 0u); return header; } std::string CreateIpv6Header(int payload_length, quiche::QuicheIpAddress source_address, quiche::QuicheIpAddress destination_address, uint8_t next_header) { QUICHE_CHECK_GT(payload_length, 0); QUICHE_CHECK_LE(payload_length, std::numeric_limits<uint16_t>::max()); QUICHE_CHECK(source_address.address_family() == quiche::IpAddressFamily::IP_V6); QUICHE_CHECK(destination_address.address_family() == quiche::IpAddressFamily::IP_V6); std::string header(kIpv6HeaderSize, '\0'); quiche::QuicheDataWriter header_writer(header.size(), header.data()); header_writer.WriteUInt32(0x60000000); header_writer.WriteUInt16(payload_length); header_writer.WriteUInt8(next_header); header_writer.WriteUInt8(64); header_writer.WriteStringPiece(source_address.ToPackedString()); header_writer.WriteStringPiece(destination_address.ToPackedString()); QUICHE_CHECK_EQ(header_writer.remaining(), 0u); return header; } } std::string CreateIpPacket(const quiche::QuicheIpAddress& source_address, const quiche::QuicheIpAddress& destination_address, absl::string_view payload, IpPacketPayloadType payload_type) { QUICHE_CHECK(source_address.address_family() == destination_address.address_family()); uint8_t payload_protocol; switch (payload_type) { case IpPacketPayloadType::kUdp: payload_protocol = kUdpProtocol; break; default: QUICHE_NOTREACHED(); return ""; } std::string header; switch (source_address.address_family()) { case quiche::IpAddressFamily::IP_V4: header = CreateIpv4Header(payload.size(), source_address, destination_address, payload_protocol); break; case quiche::IpAddressFamily::IP_V6: header = CreateIpv6Header(payload.size(), source_address, destination_address, payload_protocol); break; default: QUICHE_NOTREACHED(); return ""; } return absl::StrCat(header, payload); } std::string CreateUdpPacket(const QuicSocketAddress& source_address, const QuicSocketAddress& destination_address, absl::string_view payload) { QUICHE_CHECK(source_address.host().address_family() == destination_address.host().address_family()); QUICHE_CHECK(!payload.empty()); QUICHE_CHECK_LE(payload.size(), static_cast<uint16_t>(std::numeric_limits<uint16_t>::max() - kUdpHeaderSize)); std::string header(kUdpHeaderSize, '\0'); quiche::QuicheDataWriter header_writer(header.size(), header.data()); header_writer.WriteUInt16(source_address.port()); header_writer.WriteUInt16(destination_address.port()); header_writer.WriteUInt16(kUdpHeaderSize + payload.size()); InternetChecksum checksum; switch (source_address.host().address_family()) { case quiche::IpAddressFamily::IP_V4: { checksum.Update(source_address.host().ToPackedString()); checksum.Update(destination_address.host().ToPackedString()); uint8_t protocol[] = {0x00, kUdpProtocol}; checksum.Update(protocol, sizeof(protocol)); uint16_t udp_length = quiche::QuicheEndian::HostToNet16(kUdpHeaderSize + payload.size()); checksum.Update(reinterpret_cast<uint8_t*>(&udp_length), sizeof(udp_length)); break; } case quiche::IpAddressFamily::IP_V6: { checksum.Update(source_address.host().ToPackedString()); checksum.Update(destination_address.host().ToPackedString()); uint32_t udp_length = quiche::QuicheEndian::HostToNet32(kUdpHeaderSize + payload.size()); checksum.Update(reinterpret_cast<uint8_t*>(&udp_length), sizeof(udp_length)); uint8_t protocol[] = {0x00, 0x00, 0x00, kUdpProtocol}; checksum.Update(protocol, sizeof(protocol)); break; } default: QUICHE_NOTREACHED(); return ""; } checksum.Update(header.data(), header.size()); checksum.Update(payload.data(), payload.size()); uint16_t checksum_val = checksum.Value(); header_writer.WriteBytes(&checksum_val, sizeof(checksum_val)); QUICHE_CHECK_EQ(header_writer.remaining(), 0u); return absl::StrCat(header, payload); } }
#include "quiche/quic/test_tools/test_ip_packets.h" #include <string> #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/quiche_ip_address.h" namespace quic::test { namespace { TEST(TestIpPacketsTest, CreateIpv4Packet) { quiche::QuicheIpAddress source_ip; ASSERT_TRUE(source_ip.FromString("192.0.2.45")); ASSERT_TRUE(source_ip.IsIPv4()); QuicSocketAddress source_address{source_ip, 54131}; quiche::QuicheIpAddress destination_ip; ASSERT_TRUE(destination_ip.FromString("192.0.2.67")); ASSERT_TRUE(destination_ip.IsIPv4()); QuicSocketAddress destination_address(destination_ip, 57542); std::string packet = CreateIpPacket(source_ip, destination_ip, CreateUdpPacket(source_address, destination_address, "foo"), IpPacketPayloadType::kUdp); constexpr static char kExpected[] = "\x45" "\x00" "\x00\x1F" "\x00\x00" "\x00\x00" "\x40" "\x11" "\x00\x00" "\xC0\x00\x02\x2D" "\xC0\x00\x02\x43" "\xD3\x73" "\xE0\xC6" "\x00\x0B" "\xF1\xBC" "foo"; EXPECT_EQ(absl::string_view(packet), absl::string_view(kExpected, sizeof(kExpected) - 1)); } TEST(TestIpPacketsTest, CreateIpv6Packet) { quiche::QuicheIpAddress source_ip; ASSERT_TRUE(source_ip.FromString("2001:db8::45")); ASSERT_TRUE(source_ip.IsIPv6()); QuicSocketAddress source_address{source_ip, 51941}; quiche::QuicheIpAddress destination_ip; ASSERT_TRUE(destination_ip.FromString("2001:db8::67")); ASSERT_TRUE(destination_ip.IsIPv6()); QuicSocketAddress destination_address(destination_ip, 55341); std::string packet = CreateIpPacket(source_ip, destination_ip, CreateUdpPacket(source_address, destination_address, "foo"), IpPacketPayloadType::kUdp); constexpr static char kExpected[] = "\x60\x00\x00\x00" "\x00\x0b" "\x11" "\x40" "\x20\x01\x0D\xB8\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x45" "\x20\x01\x0D\xB8\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x67" "\xCA\xE5" "\xD8\x2D" "\x00\x0B" "\x2B\x37" "foo"; EXPECT_EQ(absl::string_view(packet), absl::string_view(kExpected, sizeof(kExpected) - 1)); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/test_tools/test_ip_packets.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/test_tools/test_ip_packets_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
0c554337-25b8-4cac-b532-75ba9b73bfbf
cpp
google/quiche
crypto_test_utils
quiche/quic/test_tools/crypto_test_utils.cc
quiche/quic/test_tools/crypto_test_utils_test.cc
#include "quiche/quic/test_tools/crypto_test_utils.h" #include <algorithm> #include <cstddef> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/core/crypto/certificate_view.h" #include "quiche/quic/core/crypto/crypto_handshake.h" #include "quiche/quic/core/crypto/crypto_utils.h" #include "quiche/quic/core/crypto/proof_source_x509.h" #include "quiche/quic/core/crypto/quic_crypto_server_config.h" #include "quiche/quic/core/crypto/quic_decrypter.h" #include "quiche/quic/core/crypto/quic_encrypter.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/proto/crypto_server_config_proto.h" #include "quiche/quic/core/quic_clock.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_crypto_client_stream.h" #include "quiche/quic/core/quic_crypto_server_stream_base.h" #include "quiche/quic/core/quic_crypto_stream.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_server_id.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_hostname_utils.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_connection_peer.h" #include "quiche/quic/test_tools/quic_framer_peer.h" #include "quiche/quic/test_tools/quic_stream_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/simple_quic_framer.h" #include "quiche/quic/test_tools/test_certificates.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_callbacks.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace quic { namespace test { namespace crypto_test_utils { namespace { using testing::_; class CryptoFramerVisitor : public CryptoFramerVisitorInterface { public: CryptoFramerVisitor() : error_(false) {} void OnError(CryptoFramer* ) override { error_ = true; } void OnHandshakeMessage(const CryptoHandshakeMessage& message) override { messages_.push_back(message); } bool error() const { return error_; } const std::vector<CryptoHandshakeMessage>& messages() const { return messages_; } private: bool error_; std::vector<CryptoHandshakeMessage> messages_; }; bool HexChar(char c, uint8_t* value) { if (c >= '0' && c <= '9') { *value = c - '0'; return true; } if (c >= 'a' && c <= 'f') { *value = c - 'a' + 10; return true; } if (c >= 'A' && c <= 'F') { *value = c - 'A' + 10; return true; } return false; } void MovePackets(const QuicConnection& source_conn, absl::Span<const QuicEncryptedPacket* const> packets, QuicCryptoStream& dest_stream, QuicConnection& dest_conn, Perspective dest_perspective, bool process_stream_data) { QUICHE_CHECK(!packets.empty()); SimpleQuicFramer framer(source_conn.supported_versions(), dest_perspective); QuicFramerPeer::SetLastSerializedServerConnectionId(framer.framer(), TestConnectionId()); SimpleQuicFramer null_encryption_framer(source_conn.supported_versions(), dest_perspective); QuicFramerPeer::SetLastSerializedServerConnectionId( null_encryption_framer.framer(), TestConnectionId()); for (const QuicEncryptedPacket* const packet : packets) { if (!dest_conn.connected()) { QUIC_LOG(INFO) << "Destination connection disconnected. Skipping packet."; continue; } QuicConnectionPeer::SwapCrypters(&dest_conn, framer.framer()); QuicConnectionPeer::AddBytesReceived(&dest_conn, packet->length()); if (!framer.ProcessPacket(*packet)) { QuicConnectionPeer::SwapCrypters(&dest_conn, framer.framer()); continue; } QuicConnectionPeer::SwapCrypters(&dest_conn, framer.framer()); QuicConnection::ScopedPacketFlusher flusher(&dest_conn); dest_conn.OnDecryptedPacket(packet->length(), framer.last_decrypted_level()); if (dest_stream.handshake_protocol() == PROTOCOL_TLS1_3) { QUIC_LOG(INFO) << "Attempting to decrypt with NullDecrypter: " "expect a decryption failure on the next log line."; ASSERT_FALSE(null_encryption_framer.ProcessPacket(*packet)) << "No TLS packets should be encrypted with the NullEncrypter"; } dest_conn.OnDecryptedPacket(packet->length(), framer.last_decrypted_level()); QuicConnectionPeer::SetCurrentPacket(&dest_conn, packet->AsStringPiece()); for (const auto& stream_frame : framer.stream_frames()) { if (process_stream_data && dest_stream.handshake_protocol() == PROTOCOL_TLS1_3) { dest_conn.OnStreamFrame(*stream_frame); } else { if (stream_frame->stream_id == dest_stream.id()) { dest_stream.OnStreamFrame(*stream_frame); } } } for (const auto& crypto_frame : framer.crypto_frames()) { dest_stream.OnCryptoFrame(*crypto_frame); } if (!framer.connection_close_frames().empty() && dest_conn.connected()) { dest_conn.OnConnectionCloseFrame(framer.connection_close_frames()[0]); } } QuicConnectionPeer::SetCurrentPacket(&dest_conn, absl::string_view(nullptr, 0)); } } FakeClientOptions::FakeClientOptions() {} FakeClientOptions::~FakeClientOptions() {} namespace { class FullChloGenerator { public: FullChloGenerator( QuicCryptoServerConfig* crypto_config, QuicSocketAddress server_addr, QuicSocketAddress client_addr, const QuicClock* clock, ParsedQuicVersion version, quiche::QuicheReferenceCountedPointer<QuicSignedServerConfig> signed_config, QuicCompressedCertsCache* compressed_certs_cache, CryptoHandshakeMessage* out) : crypto_config_(crypto_config), server_addr_(server_addr), client_addr_(client_addr), clock_(clock), version_(version), signed_config_(signed_config), compressed_certs_cache_(compressed_certs_cache), out_(out), params_(new QuicCryptoNegotiatedParameters) {} class ValidateClientHelloCallback : public ValidateClientHelloResultCallback { public: explicit ValidateClientHelloCallback(FullChloGenerator* generator) : generator_(generator) {} void Run(quiche::QuicheReferenceCountedPointer< ValidateClientHelloResultCallback::Result> result, std::unique_ptr<ProofSource::Details> ) override { generator_->ValidateClientHelloDone(std::move(result)); } private: FullChloGenerator* generator_; }; std::unique_ptr<ValidateClientHelloCallback> GetValidateClientHelloCallback() { return std::make_unique<ValidateClientHelloCallback>(this); } private: void ValidateClientHelloDone(quiche::QuicheReferenceCountedPointer< ValidateClientHelloResultCallback::Result> result) { result_ = result; crypto_config_->ProcessClientHello( result_, false, TestConnectionId(1), server_addr_, client_addr_, version_, {version_}, clock_, QuicRandom::GetInstance(), compressed_certs_cache_, params_, signed_config_, 50, kDefaultMaxPacketSize, GetProcessClientHelloCallback()); } class ProcessClientHelloCallback : public ProcessClientHelloResultCallback { public: explicit ProcessClientHelloCallback(FullChloGenerator* generator) : generator_(generator) {} void Run(QuicErrorCode error, const std::string& error_details, std::unique_ptr<CryptoHandshakeMessage> message, std::unique_ptr<DiversificationNonce> , std::unique_ptr<ProofSource::Details> ) override { ASSERT_TRUE(message) << QuicErrorCodeToString(error) << " " << error_details; generator_->ProcessClientHelloDone(std::move(message)); } private: FullChloGenerator* generator_; }; std::unique_ptr<ProcessClientHelloCallback> GetProcessClientHelloCallback() { return std::make_unique<ProcessClientHelloCallback>(this); } void ProcessClientHelloDone(std::unique_ptr<CryptoHandshakeMessage> rej) { EXPECT_THAT(rej->tag(), testing::Eq(kREJ)); QUIC_VLOG(1) << "Extract valid STK and SCID from\n" << rej->DebugString(); absl::string_view srct; ASSERT_TRUE(rej->GetStringPiece(kSourceAddressTokenTag, &srct)); absl::string_view scfg; ASSERT_TRUE(rej->GetStringPiece(kSCFG, &scfg)); std::unique_ptr<CryptoHandshakeMessage> server_config( CryptoFramer::ParseMessage(scfg)); absl::string_view scid; ASSERT_TRUE(server_config->GetStringPiece(kSCID, &scid)); *out_ = result_->client_hello; out_->SetStringPiece(kSCID, scid); out_->SetStringPiece(kSourceAddressTokenTag, srct); uint64_t xlct = LeafCertHashForTesting(); out_->SetValue(kXLCT, xlct); } protected: QuicCryptoServerConfig* crypto_config_; QuicSocketAddress server_addr_; QuicSocketAddress client_addr_; const QuicClock* clock_; ParsedQuicVersion version_; quiche::QuicheReferenceCountedPointer<QuicSignedServerConfig> signed_config_; QuicCompressedCertsCache* compressed_certs_cache_; CryptoHandshakeMessage* out_; quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> params_; quiche::QuicheReferenceCountedPointer< ValidateClientHelloResultCallback::Result> result_; }; } std::unique_ptr<QuicCryptoServerConfig> CryptoServerConfigForTesting() { return std::make_unique<QuicCryptoServerConfig>( QuicCryptoServerConfig::TESTING, QuicRandom::GetInstance(), ProofSourceForTesting(), KeyExchangeSource::Default()); } int HandshakeWithFakeServer(QuicConfig* server_quic_config, QuicCryptoServerConfig* crypto_config, MockQuicConnectionHelper* helper, MockAlarmFactory* alarm_factory, PacketSavingConnection* client_conn, QuicCryptoClientStreamBase* client, std::string alpn) { auto* server_conn = new testing::NiceMock<PacketSavingConnection>( helper, alarm_factory, Perspective::IS_SERVER, ParsedVersionOfIndex(client_conn->supported_versions(), 0)); QuicCompressedCertsCache compressed_certs_cache( QuicCompressedCertsCache::kQuicCompressedCertsCacheSize); SetupCryptoServerConfigForTest( server_conn->clock(), server_conn->random_generator(), crypto_config); TestQuicSpdyServerSession server_session( server_conn, *server_quic_config, client_conn->supported_versions(), crypto_config, &compressed_certs_cache); server_session.Initialize(); server_session.GetMutableCryptoStream() ->SetServerApplicationStateForResumption( std::make_unique<ApplicationState>()); EXPECT_CALL(*server_session.helper(), CanAcceptClientHello(testing::_, testing::_, testing::_, testing::_, testing::_)) .Times(testing::AnyNumber()); EXPECT_CALL(*server_conn, OnCanWrite()).Times(testing::AnyNumber()); EXPECT_CALL(*client_conn, OnCanWrite()).Times(testing::AnyNumber()); EXPECT_CALL(*server_conn, SendCryptoData(_, _, _)) .Times(testing::AnyNumber()); EXPECT_CALL(server_session, SelectAlpn(_)) .WillRepeatedly([alpn](const std::vector<absl::string_view>& alpns) { return std::find(alpns.cbegin(), alpns.cend(), alpn); }); QUICHE_CHECK_NE(0u, client_conn->encrypted_packets_.size()); CommunicateHandshakeMessages(client_conn, client, server_conn, server_session.GetMutableCryptoStream()); if (client_conn->connected() && server_conn->connected()) { CompareClientAndServerKeys(client, server_session.GetMutableCryptoStream()); } return client->num_sent_client_hellos(); } int HandshakeWithFakeClient(MockQuicConnectionHelper* helper, MockAlarmFactory* alarm_factory, PacketSavingConnection* server_conn, QuicCryptoServerStreamBase* server, const QuicServerId& server_id, const FakeClientOptions& options, std::string alpn) { ParsedQuicVersionVector supported_versions = server_conn->supported_versions(); if (options.only_tls_versions) { supported_versions.erase( std::remove_if(supported_versions.begin(), supported_versions.end(), [](const ParsedQuicVersion& version) { return version.handshake_protocol != PROTOCOL_TLS1_3; }), supported_versions.end()); QUICHE_CHECK(!options.only_quic_crypto_versions); } else if (options.only_quic_crypto_versions) { supported_versions.erase( std::remove_if(supported_versions.begin(), supported_versions.end(), [](const ParsedQuicVersion& version) { return version.handshake_protocol != PROTOCOL_QUIC_CRYPTO; }), supported_versions.end()); } PacketSavingConnection* client_conn = new PacketSavingConnection( helper, alarm_factory, Perspective::IS_CLIENT, supported_versions); client_conn->AdvanceTime(QuicTime::Delta::FromSeconds(1)); QuicCryptoClientConfig crypto_config(ProofVerifierForTesting()); TestQuicSpdyClientSession client_session(client_conn, DefaultQuicConfig(), supported_versions, server_id, &crypto_config); EXPECT_CALL(client_session, OnProofValid(testing::_)) .Times(testing::AnyNumber()); EXPECT_CALL(client_session, OnProofVerifyDetailsAvailable(testing::_)) .Times(testing::AnyNumber()); EXPECT_CALL(*client_conn, OnCanWrite()).Times(testing::AnyNumber()); if (!alpn.empty()) { EXPECT_CALL(client_session, GetAlpnsToOffer()) .WillRepeatedly(testing::Return(std::vector<std::string>({alpn}))); } else { EXPECT_CALL(client_session, GetAlpnsToOffer()) .WillRepeatedly(testing::Return(std::vector<std::string>( {AlpnForVersion(client_conn->version())}))); } client_session.GetMutableCryptoStream()->CryptoConnect(); QUICHE_CHECK_EQ(1u, client_conn->encrypted_packets_.size()); CommunicateHandshakeMessages(client_conn, client_session.GetMutableCryptoStream(), server_conn, server); if (server->one_rtt_keys_available() && server->encryption_established()) { CompareClientAndServerKeys(client_session.GetMutableCryptoStream(), server); } return client_session.GetCryptoStream()->num_sent_client_hellos(); } void SetupCryptoServerConfigForTest(const QuicClock* clock, QuicRandom* rand, QuicCryptoServerConfig* crypto_config) { QuicCryptoServerConfig::ConfigOptions options; options.channel_id_enabled = true; std::unique_ptr<CryptoHandshakeMessage> scfg = crypto_config->AddDefaultConfig(rand, clock, options); } void SendHandshakeMessageToStream(QuicCryptoStream* stream, const CryptoHandshakeMessage& message, Perspective ) { const QuicData& data = message.GetSerialized(); QuicSession* session = QuicStreamPeer::session(stream); if (!QuicVersionUsesCryptoFrames(session->transport_version())) { QuicStreamFrame frame( QuicUtils::GetCryptoStreamId(session->transport_version()), false, stream->crypto_bytes_read(), data.AsStringPiece()); stream->OnStreamFrame(frame); } else { EncryptionLevel level = session->connection()->last_decrypted_level(); QuicCryptoFrame frame(level, stream->BytesReadOnLevel(level), data.AsStringPiece()); stream->OnCryptoFrame(frame); } } void CommunicateHandshakeMessages(PacketSavingConnection* client_conn, QuicCryptoStream* client, PacketSavingConnection* server_conn, QuicCryptoStream* server) { CommunicateHandshakeMessages(*client_conn, *client, *server_conn, *server, *client_conn, *server_conn); } void CommunicateHandshakeMessages(QuicConnection& client_conn, QuicCryptoStream& client, QuicConnection& server_conn, QuicCryptoStream& server, PacketProvider& packets_from_client, PacketProvider& packets_from_server) { while ( client_conn.connected() && server_conn.connected() && (!client.one_rtt_keys_available() || !server.one_rtt_keys_available())) { QUICHE_CHECK(!packets_from_client.GetPackets().empty()); QUIC_LOG(INFO) << "Processing " << packets_from_client.GetPackets().size() << " packets client->server"; MovePackets(client_conn, packets_from_client.GetPackets(), server, server_conn, Perspective::IS_SERVER, false); packets_from_client.ClearPackets(); if (client.one_rtt_keys_available() && server.one_rtt_keys_available() && packets_from_server.GetPackets().empty()) { break; } QUIC_LOG(INFO) << "Processing " << packets_from_server.GetPackets().size() << " packets server->client"; MovePackets(server_conn, packets_from_server.GetPackets(), client, client_conn, Perspective::IS_CLIENT, false); packets_from_server.ClearPackets(); } } bool CommunicateHandshakeMessagesUntil( PacketSavingConnection* client_conn, QuicCryptoStream* client, quiche::UnretainedCallback<bool()> client_condition, PacketSavingConnection* server_conn, QuicCryptoStream* server, quiche::UnretainedCallback<bool()> server_condition, bool process_stream_data) { return CommunicateHandshakeMessagesUntil( *client_conn, *client, client_condition, *server_conn, *server, server_condition, process_stream_data, *client_conn, *server_conn); } bool CommunicateHandshakeMessagesUntil( QuicConnection& client_conn, QuicCryptoStream& client, quiche::UnretainedCallback<bool()> client_condition, QuicConnection& server_conn, QuicCryptoStream& server, quiche::UnretainedCallback<bool()> server_condition, bool process_stream_data, PacketProvider& packets_from_client, PacketProvider& packets_from_server) { while (client_conn.connected() && server_conn.connected() && (!client_condition() || !server_condition()) && (!packets_from_client.GetPackets().empty() || !packets_from_server.GetPackets().empty())) { if (!server_condition() && !packets_from_client.GetPackets().empty()) { QUIC_LOG(INFO) << "Processing " << packets_from_client.GetPackets().size() << " packets client->server"; MovePackets(client_conn, packets_from_client.GetPackets(), server, server_conn, Perspective::IS_SERVER, process_stream_data); packets_from_client.ClearPackets(); } if (!client_condition() && !packets_from_server.GetPackets().empty()) { QUIC_LOG(INFO) << "Processing " << packets_from_server.GetPackets().size() << " packets server->client"; MovePackets(server_conn, packets_from_server.GetPackets(), client, client_conn, Perspective::IS_CLIENT, process_stream_data); packets_from_server.ClearPackets(); } } bool result = client_condition() && server_condition(); if (!result) { QUIC_LOG(INFO) << "CommunicateHandshakeMessagesUnti failed with state: " "client connected? " << client_conn.connected() << " server connected? " << server_conn.connected() << " client condition met? " << client_condition() << " server condition met? " << server_condition(); } return result; } std::pair<size_t, size_t> AdvanceHandshake(PacketSavingConnection* client_conn, QuicCryptoStream* client, size_t client_i, PacketSavingConnection* server_conn, QuicCryptoStream* server, size_t server_i) { std::vector<QuicEncryptedPacket*> client_packets; for (; client_i < client_conn->encrypted_packets_.size(); ++client_i) { client_packets.push_back(client_conn->encrypted_packets_[client_i].get()); } AdvanceHandshake(client_packets, *client_conn, *client, {}, *server_conn, *server); std::vector<QuicEncryptedPacket*> server_packets; for (; server_i < server_conn->encrypted_packets_.size(); ++server_i) { server_packets.push_back(server_conn->encrypted_packets_[server_i].get()); } AdvanceHandshake({}, *client_conn, *client, server_packets, *server_conn, *server); return std::make_pair(client_i, server_i); } void AdvanceHandshake( absl::Span<const QuicEncryptedPacket* const> packets_from_client, QuicConnection& client_conn, QuicCryptoStream& client, absl::Span<const QuicEncryptedPacket* const> packets_from_server, QuicConnection& server_conn, QuicCryptoStream& server) { if (!packets_from_client.empty()) { QUIC_LOG(INFO) << "Processing " << packets_from_client.size() << " packets client->server"; MovePackets(client_conn, packets_from_client, server, server_conn, Perspective::IS_SERVER, false); } if (!packets_from_server.empty()) { QUIC_LOG(INFO) << "Processing " << packets_from_server.size() << " packets server->client"; MovePackets(server_conn, packets_from_server, client, client_conn, Perspective::IS_CLIENT, false); } } std::string GetValueForTag(const CryptoHandshakeMessage& message, QuicTag tag) { auto it = message.tag_value_map().find(tag); if (it == message.tag_value_map().end()) { return std::string(); } return it->second; } uint64_t LeafCertHashForTesting() { quiche::QuicheReferenceCountedPointer<ProofSource::Chain> chain; QuicSocketAddress server_address(QuicIpAddress::Any4(), 42); QuicSocketAddress client_address(QuicIpAddress::Any4(), 43); QuicCryptoProof proof; std::unique_ptr<ProofSource> proof_source(ProofSourceForTesting()); class Callback : public ProofSource::Callback { public: Callback(bool* ok, quiche::QuicheReferenceCountedPointer<ProofSource::Chain>* chain) : ok_(ok), chain_(chain) {} void Run( bool ok, const quiche::QuicheReferenceCountedPointer<ProofSource::Chain>& chain, const QuicCryptoProof& , std::unique_ptr<ProofSource::Details> ) override { *ok_ = ok; *chain_ = chain; } private: bool* ok_; quiche::QuicheReferenceCountedPointer<ProofSource::Chain>* chain_; }; bool ok = false; proof_source->GetProof( server_address, client_address, "", "", AllSupportedVersionsWithQuicCrypto().front().transport_version, "", std::unique_ptr<ProofSource::Callback>(new Callback(&ok, &chain))); if (!ok || chain->certs.empty()) { QUICHE_DCHECK(false) << "Proof generation failed"; return 0; } return QuicUtils::FNV1a_64_Hash(chain->certs[0]); } void FillInDummyReject(CryptoHandshakeMessage* rej) { rej->set_tag(kREJ); unsigned char scfg[] = { 0x53, 0x43, 0x46, 0x47, 0x01, 0x00, 0x00, 0x00, 0x45, 0x58, 0x50, 0x59, 0x08, 0x00, 0x00, 0x00, '1', '2', '3', '4', '5', '6', '7', '8' }; rej->SetValue(kSCFG, scfg); rej->SetStringPiece(kServerNonceTag, "SERVER_NONCE"); int64_t ttl = 2 * 24 * 60 * 60; rej->SetValue(kSTTL, ttl); std::vector<QuicTag> reject_reasons; reject_reasons.push_back(CLIENT_NONCE_INVALID_FAILURE); rej->SetVector(kRREJ, reject_reasons); } namespace { #define RETURN_STRING_LITERAL(x) \ case x: \ return #x std::string EncryptionLevelString(EncryptionLevel level) { switch (level) { RETURN_STRING_LITERAL(ENCRYPTION_INITIAL); RETURN_STRING_LITERAL(ENCRYPTION_HANDSHAKE); RETURN_STRING_LITERAL(ENCRYPTION_ZERO_RTT); RETURN_STRING_LITERAL(ENCRYPTION_FORWARD_SECURE); default: return ""; } } void CompareCrypters(const QuicEncrypter* encrypter, const QuicDecrypter* decrypter, std::string label) { if (encrypter == nullptr || decrypter == nullptr) { ADD_FAILURE() << "Expected non-null crypters; have " << encrypter << " and " << decrypter << " for " << label; return; } absl::string_view encrypter_key = encrypter->GetKey(); absl::string_view encrypter_iv = encrypter->GetNoncePrefix(); absl::string_view decrypter_key = decrypter->GetKey(); absl::string_view decrypter_iv = decrypter->GetNoncePrefix(); quiche::test::CompareCharArraysWithHexError( label + " key", encrypter_key.data(), encrypter_key.length(), decrypter_key.data(), decrypter_key.length()); quiche::test::CompareCharArraysWithHexError( label + " iv", encrypter_iv.data(), encrypter_iv.length(), decrypter_iv.data(), decrypter_iv.length()); } } void CompareClientAndServerKeys(QuicCryptoClientStreamBase* client, QuicCryptoServerStreamBase* server) { QuicFramer* client_framer = QuicConnectionPeer::GetFramer( QuicStreamPeer::session(client)->connection()); QuicFramer* server_framer = QuicConnectionPeer::GetFramer( QuicStreamPeer::session(server)->connection()); for (EncryptionLevel level : {ENCRYPTION_HANDSHAKE, ENCRYPTION_ZERO_RTT, ENCRYPTION_FORWARD_SECURE}) { SCOPED_TRACE(EncryptionLevelString(level)); const QuicEncrypter* client_encrypter( QuicFramerPeer::GetEncrypter(client_framer, level)); const QuicDecrypter* server_decrypter( QuicFramerPeer::GetDecrypter(server_framer, level)); if (level == ENCRYPTION_FORWARD_SECURE || !((level == ENCRYPTION_HANDSHAKE || level == ENCRYPTION_ZERO_RTT || client_encrypter == nullptr) && (level == ENCRYPTION_ZERO_RTT || server_decrypter == nullptr))) { CompareCrypters(client_encrypter, server_decrypter, "client " + EncryptionLevelString(level) + " write"); } const QuicEncrypter* server_encrypter( QuicFramerPeer::GetEncrypter(server_framer, level)); const QuicDecrypter* client_decrypter( QuicFramerPeer::GetDecrypter(client_framer, level)); if (level == ENCRYPTION_FORWARD_SECURE || !(server_encrypter == nullptr && (level == ENCRYPTION_HANDSHAKE || level == ENCRYPTION_ZERO_RTT || client_decrypter == nullptr))) { CompareCrypters(server_encrypter, client_decrypter, "server " + EncryptionLevelString(level) + " write"); } } absl::string_view client_subkey_secret = client->crypto_negotiated_params().subkey_secret; absl::string_view server_subkey_secret = server->crypto_negotiated_params().subkey_secret; quiche::test::CompareCharArraysWithHexError( "subkey secret", client_subkey_secret.data(), client_subkey_secret.length(), server_subkey_secret.data(), server_subkey_secret.length()); } QuicTag ParseTag(const char* tagstr) { const size_t len = strlen(tagstr); QUICHE_CHECK_NE(0u, len); QuicTag tag = 0; if (tagstr[0] == '#') { QUICHE_CHECK_EQ(static_cast<size_t>(1 + 2 * 4), len); tagstr++; for (size_t i = 0; i < 8; i++) { tag <<= 4; uint8_t v = 0; QUICHE_CHECK(HexChar(tagstr[i], &v)); tag |= v; } return tag; } QUICHE_CHECK_LE(len, 4u); for (size_t i = 0; i < 4; i++) { tag >>= 8; if (i < len) { tag |= static_cast<uint32_t>(tagstr[i]) << 24; } } return tag; } CryptoHandshakeMessage CreateCHLO( std::vector<std::pair<std::string, std::string>> tags_and_values) { return CreateCHLO(tags_and_values, -1); } CryptoHandshakeMessage CreateCHLO( std::vector<std::pair<std::string, std::string>> tags_and_values, int minimum_size_bytes) { CryptoHandshakeMessage msg; msg.set_tag(MakeQuicTag('C', 'H', 'L', 'O')); if (minimum_size_bytes > 0) { msg.set_minimum_size(minimum_size_bytes); } for (const auto& tag_and_value : tags_and_values) { const std::string& tag = tag_and_value.first; const std::string& value = tag_and_value.second; const QuicTag quic_tag = ParseTag(tag.c_str()); size_t value_len = value.length(); if (value_len > 0 && value[0] == '#') { std::string hex_value = absl::HexStringToBytes(absl::string_view(&value[1])); msg.SetStringPiece(quic_tag, hex_value); continue; } msg.SetStringPiece(quic_tag, value); } std::unique_ptr<QuicData> bytes = CryptoFramer::ConstructHandshakeMessage(msg); std::unique_ptr<CryptoHandshakeMessage> parsed( CryptoFramer::ParseMessage(bytes->AsStringPiece())); QUICHE_CHECK(parsed); return *parsed; } CryptoHandshakeMessage GenerateDefaultInchoateCHLO( const QuicClock* clock, QuicTransportVersion version, QuicCryptoServerConfig* crypto_config) { return CreateCHLO( {{"PDMD", "X509"}, {"AEAD", "AESG"}, {"KEXS", "C255"}, {"PUBS", GenerateClientPublicValuesHex().c_str()}, {"NONC", GenerateClientNonceHex(clock, crypto_config).c_str()}, {"VER\0", QuicVersionLabelToString( CreateQuicVersionLabel( ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, version))).c_str()}}, kClientHelloMinimumSize); } std::string GenerateClientNonceHex(const QuicClock* clock, QuicCryptoServerConfig* crypto_config) { QuicCryptoServerConfig::ConfigOptions old_config_options; QuicCryptoServerConfig::ConfigOptions new_config_options; old_config_options.id = "old-config-id"; crypto_config->AddDefaultConfig(QuicRandom::GetInstance(), clock, old_config_options); QuicServerConfigProtobuf primary_config = crypto_config->GenerateConfig( QuicRandom::GetInstance(), clock, new_config_options); primary_config.set_primary_time(clock->WallNow().ToUNIXSeconds()); std::unique_ptr<CryptoHandshakeMessage> msg = crypto_config->AddConfig(primary_config, clock->WallNow()); absl::string_view orbit; QUICHE_CHECK(msg->GetStringPiece(kORBT, &orbit)); std::string nonce; CryptoUtils::GenerateNonce(clock->WallNow(), QuicRandom::GetInstance(), orbit, &nonce); return ("#" + absl::BytesToHexString(nonce)); } std::string GenerateClientPublicValuesHex() { char public_value[32]; memset(public_value, 42, sizeof(public_value)); return ("#" + absl::BytesToHexString( absl::string_view(public_value, sizeof(public_value)))); } void GenerateFullCHLO( const CryptoHandshakeMessage& inchoate_chlo, QuicCryptoServerConfig* crypto_config, QuicSocketAddress server_addr, QuicSocketAddress client_addr, QuicTransportVersion transport_version, const QuicClock* clock, quiche::QuicheReferenceCountedPointer<QuicSignedServerConfig> signed_config, QuicCompressedCertsCache* compressed_certs_cache, CryptoHandshakeMessage* out) { FullChloGenerator generator( crypto_config, server_addr, client_addr, clock, ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, transport_version), signed_config, compressed_certs_cache, out); crypto_config->ValidateClientHello( inchoate_chlo, client_addr, server_addr, transport_version, clock, signed_config, generator.GetValidateClientHelloCallback()); } namespace { constexpr char kTestProofHostname[] = "test.example.com"; class TestProofSource : public ProofSourceX509 { public: TestProofSource() : ProofSourceX509( quiche::QuicheReferenceCountedPointer<ProofSource::Chain>( new ProofSource::Chain( std::vector<std::string>{std::string(kTestCertificate)})), std::move(*CertificatePrivateKey::LoadFromDer( kTestCertificatePrivateKey))) { QUICHE_DCHECK(valid()); } protected: void MaybeAddSctsForHostname(absl::string_view , std::string& leaf_cert_scts) override { leaf_cert_scts = "Certificate Transparency is really nice"; } }; class TestProofVerifier : public ProofVerifier { public: TestProofVerifier() : certificate_(std::move( *CertificateView::ParseSingleCertificate(kTestCertificate))) {} class Details : public ProofVerifyDetails { public: ProofVerifyDetails* Clone() const override { return new Details(*this); } }; QuicAsyncStatus VerifyProof( const std::string& hostname, const uint16_t port, const std::string& server_config, QuicTransportVersion , absl::string_view chlo_hash, const std::vector<std::string>& certs, const std::string& cert_sct, const std::string& signature, const ProofVerifyContext* context, std::string* error_details, std::unique_ptr<ProofVerifyDetails>* details, std::unique_ptr<ProofVerifierCallback> callback) override { std::optional<std::string> payload = CryptoUtils::GenerateProofPayloadToBeSigned(chlo_hash, server_config); if (!payload.has_value()) { *error_details = "Failed to serialize signed payload"; return QUIC_FAILURE; } if (!certificate_.VerifySignature(*payload, signature, SSL_SIGN_RSA_PSS_RSAE_SHA256)) { *error_details = "Invalid signature"; return QUIC_FAILURE; } uint8_t out_alert; return VerifyCertChain(hostname, port, certs, "", cert_sct, context, error_details, details, &out_alert, std::move(callback)); } QuicAsyncStatus VerifyCertChain( const std::string& hostname, const uint16_t , const std::vector<std::string>& certs, const std::string& , const std::string& , const ProofVerifyContext* , std::string* error_details, std::unique_ptr<ProofVerifyDetails>* details, uint8_t* , std::unique_ptr<ProofVerifierCallback> ) override { std::string normalized_hostname = QuicHostnameUtils::NormalizeHostname(hostname); if (normalized_hostname != kTestProofHostname) { *error_details = absl::StrCat("Invalid hostname, expected ", kTestProofHostname, " got ", hostname); return QUIC_FAILURE; } if (certs.empty() || certs.front() != kTestCertificate) { *error_details = "Received certificate different from the expected"; return QUIC_FAILURE; } *details = std::make_unique<Details>(); return QUIC_SUCCESS; } std::unique_ptr<ProofVerifyContext> CreateDefaultContext() override { return nullptr; } private: CertificateView certificate_; }; } std::unique_ptr<ProofSource> ProofSourceForTesting() { return std::make_unique<TestProofSource>(); } std::unique_ptr<ProofVerifier> ProofVerifierForTesting() { return std::make_unique<TestProofVerifier>(); } std::string CertificateHostnameForTesting() { return kTestProofHostname; } std::unique_ptr<ProofVerifyContext> ProofVerifyContextForTesting() { return nullptr; } } } }
#include "quiche/quic/test_tools/crypto_test_utils.h" #include <memory> #include <string> #include <utility> #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/proto/crypto_server_config_proto.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_clock.h" namespace quic { namespace test { class ShloVerifier { public: ShloVerifier(QuicCryptoServerConfig* crypto_config, QuicSocketAddress server_addr, QuicSocketAddress client_addr, const QuicClock* clock, quiche::QuicheReferenceCountedPointer<QuicSignedServerConfig> signed_config, QuicCompressedCertsCache* compressed_certs_cache, ParsedQuicVersion version) : crypto_config_(crypto_config), server_addr_(server_addr), client_addr_(client_addr), clock_(clock), signed_config_(signed_config), compressed_certs_cache_(compressed_certs_cache), params_(new QuicCryptoNegotiatedParameters), version_(version) {} class ValidateClientHelloCallback : public ValidateClientHelloResultCallback { public: explicit ValidateClientHelloCallback(ShloVerifier* shlo_verifier) : shlo_verifier_(shlo_verifier) {} void Run(quiche::QuicheReferenceCountedPointer< ValidateClientHelloResultCallback::Result> result, std::unique_ptr<ProofSource::Details> ) override { shlo_verifier_->ValidateClientHelloDone(result); } private: ShloVerifier* shlo_verifier_; }; std::unique_ptr<ValidateClientHelloCallback> GetValidateClientHelloCallback() { return std::make_unique<ValidateClientHelloCallback>(this); } absl::string_view server_nonce() { return server_nonce_; } bool chlo_accepted() const { return chlo_accepted_; } private: void ValidateClientHelloDone( const quiche::QuicheReferenceCountedPointer< ValidateClientHelloResultCallback::Result>& result) { result_ = result; crypto_config_->ProcessClientHello( result_, false, TestConnectionId(1), server_addr_, client_addr_, version_, AllSupportedVersions(), clock_, QuicRandom::GetInstance(), compressed_certs_cache_, params_, signed_config_, 50, kDefaultMaxPacketSize, GetProcessClientHelloCallback()); } class ProcessClientHelloCallback : public ProcessClientHelloResultCallback { public: explicit ProcessClientHelloCallback(ShloVerifier* shlo_verifier) : shlo_verifier_(shlo_verifier) {} void Run(QuicErrorCode , const std::string& , std::unique_ptr<CryptoHandshakeMessage> message, std::unique_ptr<DiversificationNonce> , std::unique_ptr<ProofSource::Details> ) override { shlo_verifier_->ProcessClientHelloDone(std::move(message)); } private: ShloVerifier* shlo_verifier_; }; std::unique_ptr<ProcessClientHelloCallback> GetProcessClientHelloCallback() { return std::make_unique<ProcessClientHelloCallback>(this); } void ProcessClientHelloDone(std::unique_ptr<CryptoHandshakeMessage> message) { if (message->tag() == kSHLO) { chlo_accepted_ = true; } else { QUIC_LOG(INFO) << "Fail to pass validation. Get " << message->DebugString(); chlo_accepted_ = false; EXPECT_EQ(1u, result_->info.reject_reasons.size()); EXPECT_EQ(SERVER_NONCE_REQUIRED_FAILURE, result_->info.reject_reasons[0]); server_nonce_ = result_->info.server_nonce; } } QuicCryptoServerConfig* crypto_config_; QuicSocketAddress server_addr_; QuicSocketAddress client_addr_; const QuicClock* clock_; quiche::QuicheReferenceCountedPointer<QuicSignedServerConfig> signed_config_; QuicCompressedCertsCache* compressed_certs_cache_; quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> params_; quiche::QuicheReferenceCountedPointer< ValidateClientHelloResultCallback::Result> result_; const ParsedQuicVersion version_; bool chlo_accepted_ = false; absl::string_view server_nonce_; }; class CryptoTestUtilsTest : public QuicTest {}; TEST_F(CryptoTestUtilsTest, TestGenerateFullCHLO) { MockClock clock; QuicCryptoServerConfig crypto_config( QuicCryptoServerConfig::TESTING, QuicRandom::GetInstance(), crypto_test_utils::ProofSourceForTesting(), KeyExchangeSource::Default()); QuicSocketAddress server_addr(QuicIpAddress::Any4(), 5); QuicSocketAddress client_addr(QuicIpAddress::Loopback4(), 1); quiche::QuicheReferenceCountedPointer<QuicSignedServerConfig> signed_config( new QuicSignedServerConfig); QuicCompressedCertsCache compressed_certs_cache( QuicCompressedCertsCache::kQuicCompressedCertsCacheSize); CryptoHandshakeMessage full_chlo; QuicCryptoServerConfig::ConfigOptions old_config_options; old_config_options.id = "old-config-id"; crypto_config.AddDefaultConfig(QuicRandom::GetInstance(), &clock, old_config_options); QuicCryptoServerConfig::ConfigOptions new_config_options; QuicServerConfigProtobuf primary_config = crypto_config.GenerateConfig( QuicRandom::GetInstance(), &clock, new_config_options); primary_config.set_primary_time(clock.WallNow().ToUNIXSeconds()); std::unique_ptr<CryptoHandshakeMessage> msg = crypto_config.AddConfig(primary_config, clock.WallNow()); absl::string_view orbit; ASSERT_TRUE(msg->GetStringPiece(kORBT, &orbit)); std::string nonce; CryptoUtils::GenerateNonce(clock.WallNow(), QuicRandom::GetInstance(), orbit, &nonce); std::string nonce_hex = "#" + absl::BytesToHexString(nonce); char public_value[32]; memset(public_value, 42, sizeof(public_value)); std::string pub_hex = "#" + absl::BytesToHexString(absl::string_view( public_value, sizeof(public_value))); QuicTransportVersion transport_version = QUIC_VERSION_UNSUPPORTED; for (const ParsedQuicVersion& version : AllSupportedVersions()) { if (version.handshake_protocol == PROTOCOL_QUIC_CRYPTO) { transport_version = version.transport_version; break; } } ASSERT_NE(QUIC_VERSION_UNSUPPORTED, transport_version); CryptoHandshakeMessage inchoate_chlo = crypto_test_utils::CreateCHLO( {{"PDMD", "X509"}, {"AEAD", "AESG"}, {"KEXS", "C255"}, {"COPT", "SREJ"}, {"PUBS", pub_hex}, {"NONC", nonce_hex}, {"VER\0", QuicVersionLabelToString(CreateQuicVersionLabel( ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, transport_version)))}}, kClientHelloMinimumSize); crypto_test_utils::GenerateFullCHLO(inchoate_chlo, &crypto_config, server_addr, client_addr, transport_version, &clock, signed_config, &compressed_certs_cache, &full_chlo); ShloVerifier shlo_verifier( &crypto_config, server_addr, client_addr, &clock, signed_config, &compressed_certs_cache, ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, transport_version)); crypto_config.ValidateClientHello( full_chlo, client_addr, server_addr, transport_version, &clock, signed_config, shlo_verifier.GetValidateClientHelloCallback()); ASSERT_EQ(shlo_verifier.chlo_accepted(), !GetQuicReloadableFlag(quic_require_handshake_confirmation)); if (!shlo_verifier.chlo_accepted()) { ShloVerifier shlo_verifier2( &crypto_config, server_addr, client_addr, &clock, signed_config, &compressed_certs_cache, ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, transport_version)); full_chlo.SetStringPiece( kServerNonceTag, "#" + absl::BytesToHexString(shlo_verifier.server_nonce())); crypto_config.ValidateClientHello( full_chlo, client_addr, server_addr, transport_version, &clock, signed_config, shlo_verifier2.GetValidateClientHelloCallback()); EXPECT_TRUE(shlo_verifier2.chlo_accepted()) << full_chlo.DebugString(); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/test_tools/crypto_test_utils.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/test_tools/crypto_test_utils_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
cfd1497b-0282-4c8e-ba59-e0bbdda6328f
cpp
google/quiche
quic_test_utils
quiche/quic/test_tools/quic_test_utils.cc
quiche/quic/test_tools/quic_test_utils_test.cc
#include "quiche/quic/test_tools/quic_test_utils.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <limits> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/strings/string_view.h" #include "openssl/chacha.h" #include "openssl/sha.h" #include "quiche/quic/core/crypto/crypto_framer.h" #include "quiche/quic/core/crypto/crypto_handshake.h" #include "quiche/quic/core/crypto/crypto_utils.h" #include "quiche/quic/core/crypto/null_decrypter.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/crypto/quic_decrypter.h" #include "quiche/quic/core/crypto/quic_encrypter.h" #include "quiche/quic/core/http/quic_spdy_client_session.h" #include "quiche/quic/core/quic_config.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/core/quic_framer.h" #include "quiche/quic/core/quic_packet_creator.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/test_tools/crypto_test_utils.h" #include "quiche/quic/test_tools/quic_config_peer.h" #include "quiche/quic/test_tools/quic_connection_peer.h" #include "quiche/common/quiche_buffer_allocator.h" #include "quiche/common/quiche_endian.h" #include "quiche/common/simple_buffer_allocator.h" using testing::_; using testing::Invoke; using testing::Return; namespace quic { namespace test { QuicConnectionId TestConnectionId() { return TestConnectionId(42); } QuicConnectionId TestConnectionId(uint64_t connection_number) { const uint64_t connection_id64_net = quiche::QuicheEndian::HostToNet64(connection_number); return QuicConnectionId(reinterpret_cast<const char*>(&connection_id64_net), sizeof(connection_id64_net)); } QuicConnectionId TestConnectionIdNineBytesLong(uint64_t connection_number) { const uint64_t connection_number_net = quiche::QuicheEndian::HostToNet64(connection_number); char connection_id_bytes[9] = {}; static_assert( sizeof(connection_id_bytes) == 1 + sizeof(connection_number_net), "bad lengths"); memcpy(connection_id_bytes + 1, &connection_number_net, sizeof(connection_number_net)); return QuicConnectionId(connection_id_bytes, sizeof(connection_id_bytes)); } uint64_t TestConnectionIdToUInt64(QuicConnectionId connection_id) { QUICHE_DCHECK_EQ(connection_id.length(), kQuicDefaultConnectionIdLength); uint64_t connection_id64_net = 0; memcpy(&connection_id64_net, connection_id.data(), std::min<size_t>(static_cast<size_t>(connection_id.length()), sizeof(connection_id64_net))); return quiche::QuicheEndian::NetToHost64(connection_id64_net); } std::vector<uint8_t> CreateStatelessResetTokenForTest() { static constexpr uint8_t kStatelessResetTokenDataForTest[16] = { 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F}; return std::vector<uint8_t>(kStatelessResetTokenDataForTest, kStatelessResetTokenDataForTest + sizeof(kStatelessResetTokenDataForTest)); } std::string TestHostname() { return "test.example.com"; } QuicServerId TestServerId() { return QuicServerId(TestHostname(), kTestPort); } QuicAckFrame InitAckFrame(const std::vector<QuicAckBlock>& ack_blocks) { QUICHE_DCHECK_GT(ack_blocks.size(), 0u); QuicAckFrame ack; QuicPacketNumber end_of_previous_block(1); for (const QuicAckBlock& block : ack_blocks) { QUICHE_DCHECK_GE(block.start, end_of_previous_block); QUICHE_DCHECK_GT(block.limit, block.start); ack.packets.AddRange(block.start, block.limit); end_of_previous_block = block.limit; } ack.largest_acked = ack.packets.Max(); return ack; } QuicAckFrame InitAckFrame(uint64_t largest_acked) { return InitAckFrame(QuicPacketNumber(largest_acked)); } QuicAckFrame InitAckFrame(QuicPacketNumber largest_acked) { return InitAckFrame({{QuicPacketNumber(1), largest_acked + 1}}); } QuicAckFrame MakeAckFrameWithAckBlocks(size_t num_ack_blocks, uint64_t least_unacked) { QuicAckFrame ack; ack.largest_acked = QuicPacketNumber(2 * num_ack_blocks + least_unacked); for (QuicPacketNumber i = QuicPacketNumber(2); i < QuicPacketNumber(2 * num_ack_blocks + 1); i += 2) { ack.packets.Add(i + least_unacked); } return ack; } QuicAckFrame MakeAckFrameWithGaps(uint64_t gap_size, size_t max_num_gaps, uint64_t largest_acked) { QuicAckFrame ack; ack.largest_acked = QuicPacketNumber(largest_acked); ack.packets.Add(QuicPacketNumber(largest_acked)); for (size_t i = 0; i < max_num_gaps; ++i) { if (largest_acked <= gap_size) { break; } largest_acked -= gap_size; ack.packets.Add(QuicPacketNumber(largest_acked)); } return ack; } EncryptionLevel HeaderToEncryptionLevel(const QuicPacketHeader& header) { if (header.form == IETF_QUIC_SHORT_HEADER_PACKET) { return ENCRYPTION_FORWARD_SECURE; } else if (header.form == IETF_QUIC_LONG_HEADER_PACKET) { if (header.long_packet_type == HANDSHAKE) { return ENCRYPTION_HANDSHAKE; } else if (header.long_packet_type == ZERO_RTT_PROTECTED) { return ENCRYPTION_ZERO_RTT; } } return ENCRYPTION_INITIAL; } std::unique_ptr<QuicPacket> BuildUnsizedDataPacket( QuicFramer* framer, const QuicPacketHeader& header, const QuicFrames& frames) { const size_t max_plaintext_size = framer->GetMaxPlaintextSize(kMaxOutgoingPacketSize); size_t packet_size = GetPacketHeaderSize(framer->transport_version(), header); for (size_t i = 0; i < frames.size(); ++i) { QUICHE_DCHECK_LE(packet_size, max_plaintext_size); bool first_frame = i == 0; bool last_frame = i == frames.size() - 1; const size_t frame_size = framer->GetSerializedFrameLength( frames[i], max_plaintext_size - packet_size, first_frame, last_frame, header.packet_number_length); QUICHE_DCHECK(frame_size); packet_size += frame_size; } return BuildUnsizedDataPacket(framer, header, frames, packet_size); } std::unique_ptr<QuicPacket> BuildUnsizedDataPacket( QuicFramer* framer, const QuicPacketHeader& header, const QuicFrames& frames, size_t packet_size) { char* buffer = new char[packet_size]; EncryptionLevel level = HeaderToEncryptionLevel(header); size_t length = framer->BuildDataPacket(header, frames, buffer, packet_size, level); if (length == 0) { delete[] buffer; return nullptr; } return std::make_unique<QuicPacket>( buffer, length, true, GetIncludedDestinationConnectionIdLength(header), GetIncludedSourceConnectionIdLength(header), header.version_flag, header.nonce != nullptr, header.packet_number_length, header.retry_token_length_length, header.retry_token.length(), header.length_length); } std::string Sha1Hash(absl::string_view data) { char buffer[SHA_DIGEST_LENGTH]; SHA1(reinterpret_cast<const uint8_t*>(data.data()), data.size(), reinterpret_cast<uint8_t*>(buffer)); return std::string(buffer, ABSL_ARRAYSIZE(buffer)); } bool ClearControlFrame(const QuicFrame& frame) { DeleteFrame(&const_cast<QuicFrame&>(frame)); return true; } bool ClearControlFrameWithTransmissionType(const QuicFrame& frame, TransmissionType ) { return ClearControlFrame(frame); } uint64_t SimpleRandom::RandUint64() { uint64_t result; RandBytes(&result, sizeof(result)); return result; } void SimpleRandom::RandBytes(void* data, size_t len) { uint8_t* data_bytes = reinterpret_cast<uint8_t*>(data); while (len > 0) { const size_t buffer_left = sizeof(buffer_) - buffer_offset_; const size_t to_copy = std::min(buffer_left, len); memcpy(data_bytes, buffer_ + buffer_offset_, to_copy); data_bytes += to_copy; buffer_offset_ += to_copy; len -= to_copy; if (buffer_offset_ == sizeof(buffer_)) { FillBuffer(); } } } void SimpleRandom::InsecureRandBytes(void* data, size_t len) { RandBytes(data, len); } uint64_t SimpleRandom::InsecureRandUint64() { return RandUint64(); } void SimpleRandom::FillBuffer() { uint8_t nonce[12]; memcpy(nonce, buffer_, sizeof(nonce)); CRYPTO_chacha_20(buffer_, buffer_, sizeof(buffer_), key_, nonce, 0); buffer_offset_ = 0; } void SimpleRandom::set_seed(uint64_t seed) { static_assert(sizeof(key_) == SHA256_DIGEST_LENGTH, "Key has to be 256 bits"); SHA256(reinterpret_cast<const uint8_t*>(&seed), sizeof(seed), key_); memset(buffer_, 0, sizeof(buffer_)); FillBuffer(); } MockFramerVisitor::MockFramerVisitor() { ON_CALL(*this, OnProtocolVersionMismatch(_)) .WillByDefault(testing::Return(false)); ON_CALL(*this, OnUnauthenticatedHeader(_)) .WillByDefault(testing::Return(true)); ON_CALL(*this, OnUnauthenticatedPublicHeader(_)) .WillByDefault(testing::Return(true)); ON_CALL(*this, OnPacketHeader(_)).WillByDefault(testing::Return(true)); ON_CALL(*this, OnStreamFrame(_)).WillByDefault(testing::Return(true)); ON_CALL(*this, OnCryptoFrame(_)).WillByDefault(testing::Return(true)); ON_CALL(*this, OnStopWaitingFrame(_)).WillByDefault(testing::Return(true)); ON_CALL(*this, OnPaddingFrame(_)).WillByDefault(testing::Return(true)); ON_CALL(*this, OnPingFrame(_)).WillByDefault(testing::Return(true)); ON_CALL(*this, OnRstStreamFrame(_)).WillByDefault(testing::Return(true)); ON_CALL(*this, OnConnectionCloseFrame(_)) .WillByDefault(testing::Return(true)); ON_CALL(*this, OnStopSendingFrame(_)).WillByDefault(testing::Return(true)); ON_CALL(*this, OnPathChallengeFrame(_)).WillByDefault(testing::Return(true)); ON_CALL(*this, OnPathResponseFrame(_)).WillByDefault(testing::Return(true)); ON_CALL(*this, OnGoAwayFrame(_)).WillByDefault(testing::Return(true)); ON_CALL(*this, OnMaxStreamsFrame(_)).WillByDefault(testing::Return(true)); ON_CALL(*this, OnStreamsBlockedFrame(_)).WillByDefault(testing::Return(true)); } MockFramerVisitor::~MockFramerVisitor() {} bool NoOpFramerVisitor::OnProtocolVersionMismatch( ParsedQuicVersion ) { return false; } bool NoOpFramerVisitor::OnUnauthenticatedPublicHeader( const QuicPacketHeader& ) { return true; } bool NoOpFramerVisitor::OnUnauthenticatedHeader( const QuicPacketHeader& ) { return true; } bool NoOpFramerVisitor::OnPacketHeader(const QuicPacketHeader& ) { return true; } void NoOpFramerVisitor::OnCoalescedPacket( const QuicEncryptedPacket& ) {} void NoOpFramerVisitor::OnUndecryptablePacket( const QuicEncryptedPacket& , EncryptionLevel , bool ) {} bool NoOpFramerVisitor::OnStreamFrame(const QuicStreamFrame& ) { return true; } bool NoOpFramerVisitor::OnCryptoFrame(const QuicCryptoFrame& ) { return true; } bool NoOpFramerVisitor::OnAckFrameStart(QuicPacketNumber , QuicTime::Delta ) { return true; } bool NoOpFramerVisitor::OnAckRange(QuicPacketNumber , QuicPacketNumber ) { return true; } bool NoOpFramerVisitor::OnAckTimestamp(QuicPacketNumber , QuicTime ) { return true; } bool NoOpFramerVisitor::OnAckFrameEnd( QuicPacketNumber , const std::optional<QuicEcnCounts>& ) { return true; } bool NoOpFramerVisitor::OnStopWaitingFrame( const QuicStopWaitingFrame& ) { return true; } bool NoOpFramerVisitor::OnPaddingFrame(const QuicPaddingFrame& ) { return true; } bool NoOpFramerVisitor::OnPingFrame(const QuicPingFrame& ) { return true; } bool NoOpFramerVisitor::OnRstStreamFrame(const QuicRstStreamFrame& ) { return true; } bool NoOpFramerVisitor::OnConnectionCloseFrame( const QuicConnectionCloseFrame& ) { return true; } bool NoOpFramerVisitor::OnNewConnectionIdFrame( const QuicNewConnectionIdFrame& ) { return true; } bool NoOpFramerVisitor::OnRetireConnectionIdFrame( const QuicRetireConnectionIdFrame& ) { return true; } bool NoOpFramerVisitor::OnNewTokenFrame(const QuicNewTokenFrame& ) { return true; } bool NoOpFramerVisitor::OnStopSendingFrame( const QuicStopSendingFrame& ) { return true; } bool NoOpFramerVisitor::OnPathChallengeFrame( const QuicPathChallengeFrame& ) { return true; } bool NoOpFramerVisitor::OnPathResponseFrame( const QuicPathResponseFrame& ) { return true; } bool NoOpFramerVisitor::OnGoAwayFrame(const QuicGoAwayFrame& ) { return true; } bool NoOpFramerVisitor::OnMaxStreamsFrame( const QuicMaxStreamsFrame& ) { return true; } bool NoOpFramerVisitor::OnStreamsBlockedFrame( const QuicStreamsBlockedFrame& ) { return true; } bool NoOpFramerVisitor::OnWindowUpdateFrame( const QuicWindowUpdateFrame& ) { return true; } bool NoOpFramerVisitor::OnBlockedFrame(const QuicBlockedFrame& ) { return true; } bool NoOpFramerVisitor::OnMessageFrame(const QuicMessageFrame& ) { return true; } bool NoOpFramerVisitor::OnHandshakeDoneFrame( const QuicHandshakeDoneFrame& ) { return true; } bool NoOpFramerVisitor::OnAckFrequencyFrame( const QuicAckFrequencyFrame& ) { return true; } bool NoOpFramerVisitor::OnResetStreamAtFrame( const QuicResetStreamAtFrame& ) { return true; } bool NoOpFramerVisitor::IsValidStatelessResetToken( const StatelessResetToken& ) const { return false; } MockQuicConnectionVisitor::MockQuicConnectionVisitor() { ON_CALL(*this, GetFlowControlSendWindowSize(_)) .WillByDefault(Return(std::numeric_limits<QuicByteCount>::max())); } MockQuicConnectionVisitor::~MockQuicConnectionVisitor() {} MockQuicConnectionHelper::MockQuicConnectionHelper() {} MockQuicConnectionHelper::~MockQuicConnectionHelper() {} const MockClock* MockQuicConnectionHelper::GetClock() const { return &clock_; } MockClock* MockQuicConnectionHelper::GetClock() { return &clock_; } QuicRandom* MockQuicConnectionHelper::GetRandomGenerator() { return &random_generator_; } QuicAlarm* MockAlarmFactory::CreateAlarm(QuicAlarm::Delegate* delegate) { return new MockAlarmFactory::TestAlarm( QuicArenaScopedPtr<QuicAlarm::Delegate>(delegate)); } QuicArenaScopedPtr<QuicAlarm> MockAlarmFactory::CreateAlarm( QuicArenaScopedPtr<QuicAlarm::Delegate> delegate, QuicConnectionArena* arena) { if (arena != nullptr) { return arena->New<TestAlarm>(std::move(delegate)); } else { return QuicArenaScopedPtr<TestAlarm>(new TestAlarm(std::move(delegate))); } } quiche::QuicheBufferAllocator* MockQuicConnectionHelper::GetStreamSendBufferAllocator() { return &buffer_allocator_; } void MockQuicConnectionHelper::AdvanceTime(QuicTime::Delta delta) { clock_.AdvanceTime(delta); } MockQuicConnection::MockQuicConnection(QuicConnectionHelperInterface* helper, QuicAlarmFactory* alarm_factory, Perspective perspective) : MockQuicConnection(TestConnectionId(), QuicSocketAddress(TestPeerIPAddress(), kTestPort), helper, alarm_factory, perspective, ParsedVersionOfIndex(CurrentSupportedVersions(), 0)) {} MockQuicConnection::MockQuicConnection(QuicSocketAddress address, QuicConnectionHelperInterface* helper, QuicAlarmFactory* alarm_factory, Perspective perspective) : MockQuicConnection(TestConnectionId(), address, helper, alarm_factory, perspective, ParsedVersionOfIndex(CurrentSupportedVersions(), 0)) {} MockQuicConnection::MockQuicConnection(QuicConnectionId connection_id, QuicConnectionHelperInterface* helper, QuicAlarmFactory* alarm_factory, Perspective perspective) : MockQuicConnection(connection_id, QuicSocketAddress(TestPeerIPAddress(), kTestPort), helper, alarm_factory, perspective, ParsedVersionOfIndex(CurrentSupportedVersions(), 0)) {} MockQuicConnection::MockQuicConnection( QuicConnectionHelperInterface* helper, QuicAlarmFactory* alarm_factory, Perspective perspective, const ParsedQuicVersionVector& supported_versions) : MockQuicConnection( TestConnectionId(), QuicSocketAddress(TestPeerIPAddress(), kTestPort), helper, alarm_factory, perspective, supported_versions) {} MockQuicConnection::MockQuicConnection( QuicConnectionId connection_id, QuicSocketAddress initial_peer_address, QuicConnectionHelperInterface* helper, QuicAlarmFactory* alarm_factory, Perspective perspective, const ParsedQuicVersionVector& supported_versions) : QuicConnection( connection_id, QuicSocketAddress(QuicIpAddress::Any4(), 5), initial_peer_address, helper, alarm_factory, new testing::NiceMock<MockPacketWriter>(), true, perspective, supported_versions, connection_id_generator_) { ON_CALL(*this, OnError(_)) .WillByDefault( Invoke(this, &PacketSavingConnection::QuicConnection_OnError)); ON_CALL(*this, SendCryptoData(_, _, _)) .WillByDefault( Invoke(this, &MockQuicConnection::QuicConnection_SendCryptoData)); SetSelfAddress(QuicSocketAddress(QuicIpAddress::Any4(), 5)); } MockQuicConnection::~MockQuicConnection() {} void MockQuicConnection::AdvanceTime(QuicTime::Delta delta) { static_cast<MockQuicConnectionHelper*>(helper())->AdvanceTime(delta); } bool MockQuicConnection::OnProtocolVersionMismatch( ParsedQuicVersion ) { return false; } PacketSavingConnection::PacketSavingConnection(MockQuicConnectionHelper* helper, QuicAlarmFactory* alarm_factory, Perspective perspective) : MockQuicConnection(helper, alarm_factory, perspective), mock_helper_(helper) {} PacketSavingConnection::PacketSavingConnection( MockQuicConnectionHelper* helper, QuicAlarmFactory* alarm_factory, Perspective perspective, const ParsedQuicVersionVector& supported_versions) : MockQuicConnection(helper, alarm_factory, perspective, supported_versions), mock_helper_(helper) {} PacketSavingConnection::~PacketSavingConnection() {} SerializedPacketFate PacketSavingConnection::GetSerializedPacketFate( bool , EncryptionLevel ) { return SEND_TO_WRITER; } void PacketSavingConnection::SendOrQueuePacket(SerializedPacket packet) { encrypted_packets_.push_back(std::make_unique<QuicEncryptedPacket>( CopyBuffer(packet), packet.encrypted_length, true)); MockClock& clock = *mock_helper_->GetClock(); clock.AdvanceTime(QuicTime::Delta::FromMilliseconds(10)); OnPacketSent(packet.encryption_level, packet.transmission_type); QuicConnectionPeer::GetSentPacketManager(this)->OnPacketSent( &packet, clock.ApproximateNow(), NOT_RETRANSMISSION, HAS_RETRANSMITTABLE_DATA, true, ECN_NOT_ECT); } std::vector<const QuicEncryptedPacket*> PacketSavingConnection::GetPackets() const { std::vector<const QuicEncryptedPacket*> packets; for (size_t i = num_cleared_packets_; i < encrypted_packets_.size(); ++i) { packets.push_back(encrypted_packets_[i].get()); } return packets; } void PacketSavingConnection::ClearPackets() { num_cleared_packets_ = encrypted_packets_.size(); } MockQuicSession::MockQuicSession(QuicConnection* connection) : MockQuicSession(connection, true) {} MockQuicSession::MockQuicSession(QuicConnection* connection, bool create_mock_crypto_stream) : QuicSession(connection, nullptr, DefaultQuicConfig(), connection->supported_versions(), 0) { if (create_mock_crypto_stream) { crypto_stream_ = std::make_unique<testing::NiceMock<MockQuicCryptoStream>>(this); } ON_CALL(*this, WritevData(_, _, _, _, _, _)) .WillByDefault(testing::Return(QuicConsumedData(0, false))); } MockQuicSession::~MockQuicSession() { DeleteConnection(); } QuicCryptoStream* MockQuicSession::GetMutableCryptoStream() { return crypto_stream_.get(); } const QuicCryptoStream* MockQuicSession::GetCryptoStream() const { return crypto_stream_.get(); } void MockQuicSession::SetCryptoStream(QuicCryptoStream* crypto_stream) { crypto_stream_.reset(crypto_stream); } QuicConsumedData MockQuicSession::ConsumeData( QuicStreamId id, size_t write_length, QuicStreamOffset offset, StreamSendingState state, TransmissionType , std::optional<EncryptionLevel> ) { if (write_length > 0) { auto buf = std::make_unique<char[]>(write_length); QuicStream* stream = GetOrCreateStream(id); QUICHE_DCHECK(stream); QuicDataWriter writer(write_length, buf.get(), quiche::HOST_BYTE_ORDER); stream->WriteStreamData(offset, write_length, &writer); } else { QUICHE_DCHECK(state != NO_FIN); } return QuicConsumedData(write_length, state != NO_FIN); } MockQuicCryptoStream::MockQuicCryptoStream(QuicSession* session) : QuicCryptoStream(session), params_(new QuicCryptoNegotiatedParameters) {} MockQuicCryptoStream::~MockQuicCryptoStream() {} ssl_early_data_reason_t MockQuicCryptoStream::EarlyDataReason() const { return ssl_early_data_unknown; } bool MockQuicCryptoStream::one_rtt_keys_available() const { return false; } const QuicCryptoNegotiatedParameters& MockQuicCryptoStream::crypto_negotiated_params() const { return *params_; } CryptoMessageParser* MockQuicCryptoStream::crypto_message_parser() { return &crypto_framer_; } MockQuicSpdySession::MockQuicSpdySession(QuicConnection* connection) : MockQuicSpdySession(connection, true) {} MockQuicSpdySession::MockQuicSpdySession(QuicConnection* connection, bool create_mock_crypto_stream) : QuicSpdySession(connection, nullptr, DefaultQuicConfig(), connection->supported_versions()) { if (create_mock_crypto_stream) { crypto_stream_ = std::make_unique<MockQuicCryptoStream>(this); } ON_CALL(*this, WritevData(_, _, _, _, _, _)) .WillByDefault(testing::Return(QuicConsumedData(0, false))); ON_CALL(*this, SendWindowUpdate(_, _)) .WillByDefault([this](QuicStreamId id, QuicStreamOffset byte_offset) { return QuicSpdySession::SendWindowUpdate(id, byte_offset); }); ON_CALL(*this, SendBlocked(_, _)) .WillByDefault([this](QuicStreamId id, QuicStreamOffset byte_offset) { return QuicSpdySession::SendBlocked(id, byte_offset); }); ON_CALL(*this, OnCongestionWindowChange(_)).WillByDefault(testing::Return()); } MockQuicSpdySession::~MockQuicSpdySession() { DeleteConnection(); } QuicCryptoStream* MockQuicSpdySession::GetMutableCryptoStream() { return crypto_stream_.get(); } const QuicCryptoStream* MockQuicSpdySession::GetCryptoStream() const { return crypto_stream_.get(); } void MockQuicSpdySession::SetCryptoStream(QuicCryptoStream* crypto_stream) { crypto_stream_.reset(crypto_stream); } QuicConsumedData MockQuicSpdySession::ConsumeData( QuicStreamId id, size_t write_length, QuicStreamOffset offset, StreamSendingState state, TransmissionType , std::optional<EncryptionLevel> ) { if (write_length > 0) { auto buf = std::make_unique<char[]>(write_length); QuicStream* stream = GetOrCreateStream(id); QUICHE_DCHECK(stream); QuicDataWriter writer(write_length, buf.get(), quiche::HOST_BYTE_ORDER); stream->WriteStreamData(offset, write_length, &writer); } else { QUICHE_DCHECK(state != NO_FIN); } return QuicConsumedData(write_length, state != NO_FIN); } TestQuicSpdyServerSession::TestQuicSpdyServerSession( QuicConnection* connection, const QuicConfig& config, const ParsedQuicVersionVector& supported_versions, const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache) : QuicServerSessionBase(config, supported_versions, connection, &visitor_, &helper_, crypto_config, compressed_certs_cache) { ON_CALL(helper_, CanAcceptClientHello(_, _, _, _, _)) .WillByDefault(testing::Return(true)); } TestQuicSpdyServerSession::~TestQuicSpdyServerSession() { DeleteConnection(); } std::unique_ptr<QuicCryptoServerStreamBase> TestQuicSpdyServerSession::CreateQuicCryptoServerStream( const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache) { return CreateCryptoServerStream(crypto_config, compressed_certs_cache, this, &helper_); } QuicCryptoServerStreamBase* TestQuicSpdyServerSession::GetMutableCryptoStream() { return QuicServerSessionBase::GetMutableCryptoStream(); } const QuicCryptoServerStreamBase* TestQuicSpdyServerSession::GetCryptoStream() const { return QuicServerSessionBase::GetCryptoStream(); } TestQuicSpdyClientSession::TestQuicSpdyClientSession( QuicConnection* connection, const QuicConfig& config, const ParsedQuicVersionVector& supported_versions, const QuicServerId& server_id, QuicCryptoClientConfig* crypto_config, std::optional<QuicSSLConfig> ssl_config) : QuicSpdyClientSessionBase(connection, nullptr, config, supported_versions), ssl_config_(std::move(ssl_config)) { crypto_stream_ = std::make_unique<QuicCryptoClientStream>( server_id, this, crypto_test_utils::ProofVerifyContextForTesting(), crypto_config, this, false); Initialize(); ON_CALL(*this, OnConfigNegotiated()) .WillByDefault( Invoke(this, &TestQuicSpdyClientSession::RealOnConfigNegotiated)); } TestQuicSpdyClientSession::~TestQuicSpdyClientSession() {} QuicCryptoClientStream* TestQuicSpdyClientSession::GetMutableCryptoStream() { return crypto_stream_.get(); } const QuicCryptoClientStream* TestQuicSpdyClientSession::GetCryptoStream() const { return crypto_stream_.get(); } void TestQuicSpdyClientSession::RealOnConfigNegotiated() { QuicSpdyClientSessionBase::OnConfigNegotiated(); } MockPacketWriter::MockPacketWriter() { ON_CALL(*this, GetMaxPacketSize(_)) .WillByDefault(testing::Return(kMaxOutgoingPacketSize)); ON_CALL(*this, IsBatchMode()).WillByDefault(testing::Return(false)); ON_CALL(*this, GetNextWriteLocation(_, _)) .WillByDefault(testing::Return(QuicPacketBuffer())); ON_CALL(*this, Flush()) .WillByDefault(testing::Return(WriteResult(WRITE_STATUS_OK, 0))); ON_CALL(*this, SupportsReleaseTime()).WillByDefault(testing::Return(false)); } MockPacketWriter::~MockPacketWriter() {} MockSendAlgorithm::MockSendAlgorithm() { ON_CALL(*this, PacingRate(_)) .WillByDefault(testing::Return(QuicBandwidth::Zero())); ON_CALL(*this, BandwidthEstimate()) .WillByDefault(testing::Return(QuicBandwidth::Zero())); } MockSendAlgorithm::~MockSendAlgorithm() {} MockLossAlgorithm::MockLossAlgorithm() {} MockLossAlgorithm::~MockLossAlgorithm() {} MockAckListener::MockAckListener() {} MockAckListener::~MockAckListener() {} MockNetworkChangeVisitor::MockNetworkChangeVisitor() {} MockNetworkChangeVisitor::~MockNetworkChangeVisitor() {} QuicIpAddress TestPeerIPAddress() { return QuicIpAddress::Loopback4(); } ParsedQuicVersion QuicVersionMax() { return AllSupportedVersions().front(); } ParsedQuicVersion QuicVersionMin() { return AllSupportedVersions().back(); } void DisableQuicVersionsWithTls() { for (const ParsedQuicVersion& version : AllSupportedVersionsWithTls()) { QuicDisableVersion(version); } } QuicEncryptedPacket* ConstructEncryptedPacket( QuicConnectionId destination_connection_id, QuicConnectionId source_connection_id, bool version_flag, bool reset_flag, uint64_t packet_number, const std::string& data) { return ConstructEncryptedPacket( destination_connection_id, source_connection_id, version_flag, reset_flag, packet_number, data, CONNECTION_ID_PRESENT, CONNECTION_ID_ABSENT, PACKET_4BYTE_PACKET_NUMBER); } QuicEncryptedPacket* ConstructEncryptedPacket( QuicConnectionId destination_connection_id, QuicConnectionId source_connection_id, bool version_flag, bool reset_flag, uint64_t packet_number, const std::string& data, QuicConnectionIdIncluded destination_connection_id_included, QuicConnectionIdIncluded source_connection_id_included, QuicPacketNumberLength packet_number_length) { return ConstructEncryptedPacket( destination_connection_id, source_connection_id, version_flag, reset_flag, packet_number, data, destination_connection_id_included, source_connection_id_included, packet_number_length, nullptr); } QuicEncryptedPacket* ConstructEncryptedPacket( QuicConnectionId destination_connection_id, QuicConnectionId source_connection_id, bool version_flag, bool reset_flag, uint64_t packet_number, const std::string& data, QuicConnectionIdIncluded destination_connection_id_included, QuicConnectionIdIncluded source_connection_id_included, QuicPacketNumberLength packet_number_length, ParsedQuicVersionVector* versions) { return ConstructEncryptedPacket( destination_connection_id, source_connection_id, version_flag, reset_flag, packet_number, data, false, destination_connection_id_included, source_connection_id_included, packet_number_length, versions, Perspective::IS_CLIENT); } QuicEncryptedPacket* ConstructEncryptedPacket( QuicConnectionId destination_connection_id, QuicConnectionId source_connection_id, bool version_flag, bool reset_flag, uint64_t packet_number, const std::string& data, bool full_padding, QuicConnectionIdIncluded destination_connection_id_included, QuicConnectionIdIncluded source_connection_id_included, QuicPacketNumberLength packet_number_length, ParsedQuicVersionVector* versions) { return ConstructEncryptedPacket( destination_connection_id, source_connection_id, version_flag, reset_flag, packet_number, data, full_padding, destination_connection_id_included, source_connection_id_included, packet_number_length, versions, Perspective::IS_CLIENT); } QuicEncryptedPacket* ConstructEncryptedPacket( QuicConnectionId destination_connection_id, QuicConnectionId source_connection_id, bool version_flag, bool reset_flag, uint64_t packet_number, const std::string& data, bool full_padding, QuicConnectionIdIncluded destination_connection_id_included, QuicConnectionIdIncluded source_connection_id_included, QuicPacketNumberLength packet_number_length, ParsedQuicVersionVector* versions, Perspective perspective) { QuicPacketHeader header; header.destination_connection_id = destination_connection_id; header.destination_connection_id_included = destination_connection_id_included; header.source_connection_id = source_connection_id; header.source_connection_id_included = source_connection_id_included; header.version_flag = version_flag; header.reset_flag = reset_flag; header.packet_number_length = packet_number_length; header.packet_number = QuicPacketNumber(packet_number); ParsedQuicVersionVector supported_versions = CurrentSupportedVersions(); if (!versions) { versions = &supported_versions; } EXPECT_FALSE(versions->empty()); ParsedQuicVersion version = (*versions)[0]; if (QuicVersionHasLongHeaderLengths(version.transport_version) && version_flag) { header.retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1; header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2; } QuicFrames frames; QuicFramer framer(*versions, QuicTime::Zero(), perspective, kQuicDefaultConnectionIdLength); framer.SetInitialObfuscators(destination_connection_id); EncryptionLevel level = header.version_flag ? ENCRYPTION_INITIAL : ENCRYPTION_FORWARD_SECURE; if (level != ENCRYPTION_INITIAL) { framer.SetEncrypter(level, std::make_unique<TaggingEncrypter>(level)); } if (!QuicVersionUsesCryptoFrames(version.transport_version)) { QuicFrame frame( QuicStreamFrame(QuicUtils::GetCryptoStreamId(version.transport_version), false, 0, absl::string_view(data))); frames.push_back(frame); } else { QuicFrame frame(new QuicCryptoFrame(level, 0, data)); frames.push_back(frame); } if (full_padding) { frames.push_back(QuicFrame(QuicPaddingFrame(-1))); } else { size_t min_plaintext_size = QuicPacketCreator::MinPlaintextPacketSize( version, packet_number_length); if (data.length() < min_plaintext_size) { size_t padding_length = min_plaintext_size - data.length(); frames.push_back(QuicFrame(QuicPaddingFrame(padding_length))); } } std::unique_ptr<QuicPacket> packet( BuildUnsizedDataPacket(&framer, header, frames)); EXPECT_TRUE(packet != nullptr); char* buffer = new char[kMaxOutgoingPacketSize]; size_t encrypted_length = framer.EncryptPayload(level, QuicPacketNumber(packet_number), *packet, buffer, kMaxOutgoingPacketSize); EXPECT_NE(0u, encrypted_length); DeleteFrames(&frames); return new QuicEncryptedPacket(buffer, encrypted_length, true); } std::unique_ptr<QuicEncryptedPacket> GetUndecryptableEarlyPacket( const ParsedQuicVersion& version, const QuicConnectionId& server_connection_id) { QuicPacketHeader header; header.destination_connection_id = server_connection_id; header.destination_connection_id_included = CONNECTION_ID_PRESENT; header.source_connection_id = EmptyQuicConnectionId(); header.source_connection_id_included = CONNECTION_ID_PRESENT; if (!version.SupportsClientConnectionIds()) { header.source_connection_id_included = CONNECTION_ID_ABSENT; } header.version_flag = true; header.reset_flag = false; header.packet_number_length = PACKET_4BYTE_PACKET_NUMBER; header.packet_number = QuicPacketNumber(33); header.long_packet_type = ZERO_RTT_PROTECTED; if (version.HasLongHeaderLengths()) { header.retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1; header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2; } QuicFrames frames; frames.push_back(QuicFrame(QuicPingFrame())); frames.push_back(QuicFrame(QuicPaddingFrame(100))); QuicFramer framer({version}, QuicTime::Zero(), Perspective::IS_CLIENT, kQuicDefaultConnectionIdLength); framer.SetInitialObfuscators(server_connection_id); framer.SetEncrypter(ENCRYPTION_ZERO_RTT, std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT)); std::unique_ptr<QuicPacket> packet( BuildUnsizedDataPacket(&framer, header, frames)); EXPECT_TRUE(packet != nullptr); char* buffer = new char[kMaxOutgoingPacketSize]; size_t encrypted_length = framer.EncryptPayload(ENCRYPTION_ZERO_RTT, header.packet_number, *packet, buffer, kMaxOutgoingPacketSize); EXPECT_NE(0u, encrypted_length); DeleteFrames(&frames); return std::make_unique<QuicEncryptedPacket>(buffer, encrypted_length, true); } QuicReceivedPacket* ConstructReceivedPacket( const QuicEncryptedPacket& encrypted_packet, QuicTime receipt_time) { return ConstructReceivedPacket(encrypted_packet, receipt_time, ECN_NOT_ECT); } QuicReceivedPacket* ConstructReceivedPacket( const QuicEncryptedPacket& encrypted_packet, QuicTime receipt_time, QuicEcnCodepoint ecn) { char* buffer = new char[encrypted_packet.length()]; memcpy(buffer, encrypted_packet.data(), encrypted_packet.length()); return new QuicReceivedPacket(buffer, encrypted_packet.length(), receipt_time, true, 0, true, nullptr, 0, false, ecn); } QuicEncryptedPacket* ConstructMisFramedEncryptedPacket( QuicConnectionId destination_connection_id, QuicConnectionId source_connection_id, bool version_flag, bool reset_flag, uint64_t packet_number, const std::string& data, QuicConnectionIdIncluded destination_connection_id_included, QuicConnectionIdIncluded source_connection_id_included, QuicPacketNumberLength packet_number_length, ParsedQuicVersion version, Perspective perspective) { QuicPacketHeader header; header.destination_connection_id = destination_connection_id; header.destination_connection_id_included = destination_connection_id_included; header.source_connection_id = source_connection_id; header.source_connection_id_included = source_connection_id_included; header.version_flag = version_flag; header.reset_flag = reset_flag; header.packet_number_length = packet_number_length; header.packet_number = QuicPacketNumber(packet_number); if (QuicVersionHasLongHeaderLengths(version.transport_version) && version_flag) { header.retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1; header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2; } QuicFrame frame(QuicStreamFrame(1, false, 0, absl::string_view(data))); QuicFrames frames; frames.push_back(frame); QuicFramer framer({version}, QuicTime::Zero(), perspective, kQuicDefaultConnectionIdLength); framer.SetInitialObfuscators(destination_connection_id); EncryptionLevel level = version_flag ? ENCRYPTION_INITIAL : ENCRYPTION_FORWARD_SECURE; if (level != ENCRYPTION_INITIAL) { framer.SetEncrypter(level, std::make_unique<TaggingEncrypter>(level)); } if (data.length() < 7) { size_t padding_length = 7 - data.length(); frames.push_back(QuicFrame(QuicPaddingFrame(padding_length))); } std::unique_ptr<QuicPacket> packet( BuildUnsizedDataPacket(&framer, header, frames)); EXPECT_TRUE(packet != nullptr); reinterpret_cast<unsigned char*>( packet->mutable_data())[GetStartOfEncryptedData( framer.transport_version(), GetIncludedDestinationConnectionIdLength(header), GetIncludedSourceConnectionIdLength(header), version_flag, false , packet_number_length, header.retry_token_length_length, 0, header.length_length)] = 0x1F; char* buffer = new char[kMaxOutgoingPacketSize]; size_t encrypted_length = framer.EncryptPayload(level, QuicPacketNumber(packet_number), *packet, buffer, kMaxOutgoingPacketSize); EXPECT_NE(0u, encrypted_length); return new QuicEncryptedPacket(buffer, encrypted_length, true); } QuicConfig DefaultQuicConfig() { QuicConfig config; config.SetInitialMaxStreamDataBytesIncomingBidirectionalToSend( kInitialStreamFlowControlWindowForTest); config.SetInitialMaxStreamDataBytesOutgoingBidirectionalToSend( kInitialStreamFlowControlWindowForTest); config.SetInitialMaxStreamDataBytesUnidirectionalToSend( kInitialStreamFlowControlWindowForTest); config.SetInitialStreamFlowControlWindowToSend( kInitialStreamFlowControlWindowForTest); config.SetInitialSessionFlowControlWindowToSend( kInitialSessionFlowControlWindowForTest); QuicConfigPeer::SetReceivedMaxBidirectionalStreams( &config, kDefaultMaxStreamsPerConnection); if (!config.HasClientSentConnectionOption(quic::kNSTP, quic::Perspective::IS_CLIENT)) { quic::QuicTagVector connection_options; connection_options.push_back(quic::kNSTP); config.SetConnectionOptionsToSend(connection_options); } return config; } ParsedQuicVersionVector SupportedVersions(ParsedQuicVersion version) { ParsedQuicVersionVector versions; versions.push_back(version); return versions; } MockQuicConnectionDebugVisitor::MockQuicConnectionDebugVisitor() {} MockQuicConnectionDebugVisitor::~MockQuicConnectionDebugVisitor() {} MockReceivedPacketManager::MockReceivedPacketManager(QuicConnectionStats* stats) : QuicReceivedPacketManager(stats) {} MockReceivedPacketManager::~MockReceivedPacketManager() {} MockPacketCreatorDelegate::MockPacketCreatorDelegate() {} MockPacketCreatorDelegate::~MockPacketCreatorDelegate() {} MockSessionNotifier::MockSessionNotifier() {} MockSessionNotifier::~MockSessionNotifier() {} QuicCryptoClientStream::HandshakerInterface* QuicCryptoClientStreamPeer::GetHandshaker(QuicCryptoClientStream* stream) { return stream->handshaker_.get(); } void CreateClientSessionForTest( QuicServerId server_id, QuicTime::Delta connection_start_time, const ParsedQuicVersionVector& supported_versions, MockQuicConnectionHelper* helper, QuicAlarmFactory* alarm_factory, QuicCryptoClientConfig* crypto_client_config, PacketSavingConnection** client_connection, TestQuicSpdyClientSession** client_session) { QUICHE_CHECK(crypto_client_config); QUICHE_CHECK(client_connection); QUICHE_CHECK(client_session); QUICHE_CHECK(!connection_start_time.IsZero()) << "Connections must start at non-zero times, otherwise the " << "strike-register will be unhappy."; QuicConfig config = DefaultQuicConfig(); *client_connection = new PacketSavingConnection( helper, alarm_factory, Perspective::IS_CLIENT, supported_versions); *client_session = new TestQuicSpdyClientSession(*client_connection, config, supported_versions, server_id, crypto_client_config); (*client_connection)->AdvanceTime(connection_start_time); } void CreateServerSessionForTest( QuicServerId , QuicTime::Delta connection_start_time, ParsedQuicVersionVector supported_versions, MockQuicConnectionHelper* helper, QuicAlarmFactory* alarm_factory, QuicCryptoServerConfig* server_crypto_config, QuicCompressedCertsCache* compressed_certs_cache, PacketSavingConnection** server_connection, TestQuicSpdyServerSession** server_session) { QUICHE_CHECK(server_crypto_config); QUICHE_CHECK(server_connection); QUICHE_CHECK(server_session); QUICHE_CHECK(!connection_start_time.IsZero()) << "Connections must start at non-zero times, otherwise the " << "strike-register will be unhappy."; *server_connection = new PacketSavingConnection(helper, alarm_factory, Perspective::IS_SERVER, ParsedVersionOfIndex(supported_versions, 0)); *server_session = new TestQuicSpdyServerSession( *server_connection, DefaultQuicConfig(), supported_versions, server_crypto_config, compressed_certs_cache); (*server_session)->Initialize(); (*server_connection)->AdvanceTime(connection_start_time); } QuicStreamId GetNthClientInitiatedBidirectionalStreamId( QuicTransportVersion version, int n) { int num = n; if (!VersionUsesHttp3(version)) { num++; } return QuicUtils::GetFirstBidirectionalStreamId(version, Perspective::IS_CLIENT) + QuicUtils::StreamIdDelta(version) * num; } QuicStreamId GetNthServerInitiatedBidirectionalStreamId( QuicTransportVersion version, int n) { return QuicUtils::GetFirstBidirectionalStreamId(version, Perspective::IS_SERVER) + QuicUtils::StreamIdDelta(version) * n; } QuicStreamId GetNthServerInitiatedUnidirectionalStreamId( QuicTransportVersion version, int n) { return QuicUtils::GetFirstUnidirectionalStreamId(version, Perspective::IS_SERVER) + QuicUtils::StreamIdDelta(version) * n; } QuicStreamId GetNthClientInitiatedUnidirectionalStreamId( QuicTransportVersion version, int n) { return QuicUtils::GetFirstUnidirectionalStreamId(version, Perspective::IS_CLIENT) + QuicUtils::StreamIdDelta(version) * n; } StreamType DetermineStreamType(QuicStreamId id, ParsedQuicVersion version, Perspective perspective, bool is_incoming, StreamType default_type) { return version.HasIetfQuicFrames() ? QuicUtils::GetStreamType(id, perspective, is_incoming, version) : default_type; } quiche::QuicheMemSlice MemSliceFromString(absl::string_view data) { if (data.empty()) { return quiche::QuicheMemSlice(); } static quiche::SimpleBufferAllocator* allocator = new quiche::SimpleBufferAllocator(); return quiche::QuicheMemSlice(quiche::QuicheBuffer::Copy(allocator, data)); } bool TaggingEncrypter::EncryptPacket(uint64_t , absl::string_view , absl::string_view plaintext, char* output, size_t* output_length, size_t max_output_length) { const size_t len = plaintext.size() + kTagSize; if (max_output_length < len) { return false; } memmove(output, plaintext.data(), plaintext.size()); output += plaintext.size(); memset(output, tag_, kTagSize); *output_length = len; return true; } bool TaggingDecrypter::DecryptPacket(uint64_t , absl::string_view , absl::string_view ciphertext, char* output, size_t* output_length, size_t ) { if (ciphertext.size() < kTagSize) { return false; } if (!CheckTag(ciphertext, GetTag(ciphertext))) { return false; } *output_length = ciphertext.size() - kTagSize; memcpy(output, ciphertext.data(), *output_length); return true; } bool TaggingDecrypter::CheckTag(absl::string_view ciphertext, uint8_t tag) { for (size_t i = ciphertext.size() - kTagSize; i < ciphertext.size(); i++) { if (ciphertext.data()[i] != tag) { return false; } } return true; } TestPacketWriter::TestPacketWriter(ParsedQuicVersion version, MockClock* clock, Perspective perspective) : version_(version), framer_(SupportedVersions(version_), QuicUtils::InvertPerspective(perspective)), clock_(clock) { QuicFramerPeer::SetLastSerializedServerConnectionId(framer_.framer(), TestConnectionId()); framer_.framer()->SetInitialObfuscators(TestConnectionId()); for (int i = 0; i < 128; ++i) { PacketBuffer* p = new PacketBuffer(); packet_buffer_pool_.push_back(p); packet_buffer_pool_index_[p->buffer] = p; packet_buffer_free_list_.push_back(p); } } TestPacketWriter::~TestPacketWriter() { EXPECT_EQ(packet_buffer_pool_.size(), packet_buffer_free_list_.size()) << packet_buffer_pool_.size() - packet_buffer_free_list_.size() << " out of " << packet_buffer_pool_.size() << " packet buffers have been leaked."; for (auto p : packet_buffer_pool_) { delete p; } } WriteResult TestPacketWriter::WritePacket( const char* buffer, size_t buf_len, const QuicIpAddress& self_address, const QuicSocketAddress& peer_address, PerPacketOptions* , const QuicPacketWriterParams& params) { last_write_source_address_ = self_address; last_write_peer_address_ = peer_address; if (packet_buffer_pool_index_.find(const_cast<char*>(buffer)) != packet_buffer_pool_index_.end()) { FreePacketBuffer(buffer); } QuicEncryptedPacket packet(buffer, buf_len); ++packets_write_attempts_; if (packet.length() >= sizeof(final_bytes_of_last_packet_)) { final_bytes_of_previous_packet_ = final_bytes_of_last_packet_; memcpy(&final_bytes_of_last_packet_, packet.data() + packet.length() - 4, sizeof(final_bytes_of_last_packet_)); } if (framer_.framer()->version().KnowsWhichDecrypterToUse()) { framer_.framer()->InstallDecrypter(ENCRYPTION_HANDSHAKE, std::make_unique<TaggingDecrypter>()); framer_.framer()->InstallDecrypter(ENCRYPTION_ZERO_RTT, std::make_unique<TaggingDecrypter>()); framer_.framer()->InstallDecrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingDecrypter>()); } else if (!framer_.framer()->HasDecrypterOfEncryptionLevel( ENCRYPTION_FORWARD_SECURE) && !framer_.framer()->HasDecrypterOfEncryptionLevel( ENCRYPTION_ZERO_RTT)) { framer_.framer()->SetAlternativeDecrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE), false); } EXPECT_EQ(next_packet_processable_, framer_.ProcessPacket(packet)) << framer_.framer()->detailed_error() << " perspective " << framer_.framer()->perspective(); next_packet_processable_ = true; if (block_on_next_write_) { write_blocked_ = true; block_on_next_write_ = false; } if (next_packet_too_large_) { next_packet_too_large_ = false; return WriteResult(WRITE_STATUS_ERROR, *MessageTooBigErrorCode()); } if (always_get_packet_too_large_) { return WriteResult(WRITE_STATUS_ERROR, *MessageTooBigErrorCode()); } if (IsWriteBlocked()) { return WriteResult(is_write_blocked_data_buffered_ ? WRITE_STATUS_BLOCKED_DATA_BUFFERED : WRITE_STATUS_BLOCKED, 0); } if (ShouldWriteFail()) { return WriteResult(WRITE_STATUS_ERROR, write_error_code_); } last_packet_size_ = packet.length(); total_bytes_written_ += packet.length(); last_packet_header_ = framer_.header(); if (!framer_.connection_close_frames().empty()) { ++connection_close_packets_; } if (!write_pause_time_delta_.IsZero()) { clock_->AdvanceTime(write_pause_time_delta_); } if (is_batch_mode_) { bytes_buffered_ += last_packet_size_; return WriteResult(WRITE_STATUS_OK, 0); } last_ecn_sent_ = params.ecn_codepoint; return WriteResult(WRITE_STATUS_OK, last_packet_size_); } QuicPacketBuffer TestPacketWriter::GetNextWriteLocation( const QuicIpAddress& , const QuicSocketAddress& ) { return {AllocPacketBuffer(), [this](const char* p) { FreePacketBuffer(p); }}; } WriteResult TestPacketWriter::Flush() { flush_attempts_++; if (block_on_next_flush_) { block_on_next_flush_ = false; SetWriteBlocked(); return WriteResult(WRITE_STATUS_BLOCKED, -1); } if (write_should_fail_) { return WriteResult(WRITE_STATUS_ERROR, -1); } int bytes_flushed = bytes_buffered_; bytes_buffered_ = 0; return WriteResult(WRITE_STATUS_OK, bytes_flushed); } char* TestPacketWriter::AllocPacketBuffer() { PacketBuffer* p = packet_buffer_free_list_.front(); EXPECT_FALSE(p->in_use); p->in_use = true; packet_buffer_free_list_.pop_front(); return p->buffer; } void TestPacketWriter::FreePacketBuffer(const char* buffer) { auto iter = packet_buffer_pool_index_.find(const_cast<char*>(buffer)); ASSERT_TRUE(iter != packet_buffer_pool_index_.end()); PacketBuffer* p = iter->second; ASSERT_TRUE(p->in_use); p->in_use = false; packet_buffer_free_list_.push_back(p); } bool WriteServerVersionNegotiationProbeResponse( char* packet_bytes, size_t* packet_length_out, const char* source_connection_id_bytes, uint8_t source_connection_id_length) { if (packet_bytes == nullptr) { QUIC_BUG(quic_bug_10256_1) << "Invalid packet_bytes"; return false; } if (packet_length_out == nullptr) { QUIC_BUG(quic_bug_10256_2) << "Invalid packet_length_out"; return false; } QuicConnectionId source_connection_id(source_connection_id_bytes, source_connection_id_length); std::unique_ptr<QuicEncryptedPacket> encrypted_packet = QuicFramer::BuildVersionNegotiationPacket( source_connection_id, EmptyQuicConnectionId(), true, true, ParsedQuicVersionVector{}); if (!encrypted_packet) { QUIC_BUG(quic_bug_10256_3) << "Failed to create version negotiation packet"; return false; } if (*packet_length_out < encrypted_packet->length()) { QUIC_BUG(quic_bug_10256_4) << "Invalid *packet_length_out " << *packet_length_out << " < " << encrypted_packet->length(); return false; } *packet_length_out = encrypted_packet->length(); memcpy(packet_bytes, encrypted_packet->data(), *packet_length_out); return true; } bool ParseClientVersionNegotiationProbePacket( const char* packet_bytes, size_t packet_length, char* destination_connection_id_bytes, uint8_t* destination_connection_id_length_out) { if (packet_bytes == nullptr) { QUIC_BUG(quic_bug_10256_5) << "Invalid packet_bytes"; return false; } if (packet_length < kMinPacketSizeForVersionNegotiation || packet_length > 65535) { QUIC_BUG(quic_bug_10256_6) << "Invalid packet_length"; return false; } if (destination_connection_id_bytes == nullptr) { QUIC_BUG(quic_bug_10256_7) << "Invalid destination_connection_id_bytes"; return false; } if (destination_connection_id_length_out == nullptr) { QUIC_BUG(quic_bug_10256_8) << "Invalid destination_connection_id_length_out"; return false; } QuicEncryptedPacket encrypted_packet(packet_bytes, packet_length); PacketHeaderFormat format; QuicLongHeaderType long_packet_type; bool version_present, has_length_prefix; QuicVersionLabel version_label; ParsedQuicVersion parsed_version = ParsedQuicVersion::Unsupported(); QuicConnectionId destination_connection_id, source_connection_id; std::optional<absl::string_view> retry_token; std::string detailed_error; QuicErrorCode error = QuicFramer::ParsePublicHeaderDispatcher( encrypted_packet, 0, &format, &long_packet_type, &version_present, &has_length_prefix, &version_label, &parsed_version, &destination_connection_id, &source_connection_id, &retry_token, &detailed_error); if (error != QUIC_NO_ERROR) { QUIC_BUG(quic_bug_10256_9) << "Failed to parse packet: " << detailed_error; return false; } if (!version_present) { QUIC_BUG(quic_bug_10256_10) << "Packet is not a long header"; return false; } if (*destination_connection_id_length_out < destination_connection_id.length()) { QUIC_BUG(quic_bug_10256_11) << "destination_connection_id_length_out too small"; return false; } *destination_connection_id_length_out = destination_connection_id.length(); memcpy(destination_connection_id_bytes, destination_connection_id.data(), *destination_connection_id_length_out); return true; } } }
#include "quiche/quic/test_tools/quic_test_utils.h" #include <string> #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { class QuicTestUtilsTest : public QuicTest {}; TEST_F(QuicTestUtilsTest, ConnectionId) { EXPECT_NE(EmptyQuicConnectionId(), TestConnectionId()); EXPECT_NE(EmptyQuicConnectionId(), TestConnectionId(1)); EXPECT_EQ(TestConnectionId(), TestConnectionId()); EXPECT_EQ(TestConnectionId(33), TestConnectionId(33)); EXPECT_NE(TestConnectionId(0xdead), TestConnectionId(0xbeef)); EXPECT_EQ(0x1337u, TestConnectionIdToUInt64(TestConnectionId(0x1337))); EXPECT_NE(0xdeadu, TestConnectionIdToUInt64(TestConnectionId(0xbeef))); } TEST_F(QuicTestUtilsTest, BasicApproxEq) { EXPECT_APPROX_EQ(10, 10, 1e-6f); EXPECT_APPROX_EQ(1000, 1001, 0.01f); EXPECT_NONFATAL_FAILURE(EXPECT_APPROX_EQ(1000, 1100, 0.01f), ""); EXPECT_APPROX_EQ(64, 31, 0.55f); EXPECT_NONFATAL_FAILURE(EXPECT_APPROX_EQ(31, 64, 0.55f), ""); } TEST_F(QuicTestUtilsTest, QuicTimeDelta) { EXPECT_APPROX_EQ(QuicTime::Delta::FromMicroseconds(1000), QuicTime::Delta::FromMicroseconds(1003), 0.01f); EXPECT_NONFATAL_FAILURE( EXPECT_APPROX_EQ(QuicTime::Delta::FromMicroseconds(1000), QuicTime::Delta::FromMicroseconds(1200), 0.01f), ""); } TEST_F(QuicTestUtilsTest, QuicBandwidth) { EXPECT_APPROX_EQ(QuicBandwidth::FromBytesPerSecond(1000), QuicBandwidth::FromBitsPerSecond(8005), 0.01f); EXPECT_NONFATAL_FAILURE( EXPECT_APPROX_EQ(QuicBandwidth::FromBytesPerSecond(1000), QuicBandwidth::FromBitsPerSecond(9005), 0.01f), ""); } TEST_F(QuicTestUtilsTest, SimpleRandomStability) { SimpleRandom rng; rng.set_seed(UINT64_C(0x1234567800010001)); EXPECT_EQ(UINT64_C(12589383305231984671), rng.RandUint64()); EXPECT_EQ(UINT64_C(17775425089941798664), rng.RandUint64()); } TEST_F(QuicTestUtilsTest, SimpleRandomChunks) { SimpleRandom rng; std::string reference(16 * 1024, '\0'); rng.RandBytes(&reference[0], reference.size()); for (size_t chunk_size : {3, 4, 7, 4096}) { rng.set_seed(0); size_t chunks = reference.size() / chunk_size; std::string buffer(chunks * chunk_size, '\0'); for (size_t i = 0; i < chunks; i++) { rng.RandBytes(&buffer[i * chunk_size], chunk_size); } EXPECT_EQ(reference.substr(0, buffer.size()), buffer) << "Failed for chunk_size = " << chunk_size; } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/test_tools/quic_test_utils.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/test_tools/quic_test_utils_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
017b88cb-d4f6-4058-982e-183d7d3cc96e
cpp
google/quiche
simulator
quiche/quic/test_tools/simulator/simulator.cc
quiche/quic/test_tools/simulator/simulator_test.cc
#include "quiche/quic/test_tools/simulator/simulator.h" #include <utility> #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { namespace simulator { Simulator::Simulator() : Simulator(nullptr) {} Simulator::Simulator(QuicRandom* random_generator) : random_generator_(random_generator), alarm_factory_(this, "Default Alarm Manager"), run_for_should_stop_(false), enable_random_delays_(false) { run_for_alarm_.reset( alarm_factory_.CreateAlarm(new RunForDelegate(&run_for_should_stop_))); } Simulator::~Simulator() { run_for_alarm_.reset(); } Simulator::Clock::Clock() : now_(kStartTime) {} QuicTime Simulator::Clock::ApproximateNow() const { return now_; } QuicTime Simulator::Clock::Now() const { return now_; } QuicWallTime Simulator::Clock::WallNow() const { return QuicWallTime::FromUNIXMicroseconds( (now_ - QuicTime::Zero()).ToMicroseconds()); } void Simulator::AddActor(Actor* actor) { auto emplace_times_result = scheduled_times_.insert(std::make_pair(actor, QuicTime::Infinite())); auto emplace_names_result = actor_names_.insert(actor->name()); QUICHE_DCHECK(emplace_times_result.second); QUICHE_DCHECK(emplace_names_result.second); } void Simulator::RemoveActor(Actor* actor) { auto scheduled_time_it = scheduled_times_.find(actor); auto actor_names_it = actor_names_.find(actor->name()); QUICHE_DCHECK(scheduled_time_it != scheduled_times_.end()); QUICHE_DCHECK(actor_names_it != actor_names_.end()); QuicTime scheduled_time = scheduled_time_it->second; if (scheduled_time != QuicTime::Infinite()) { Unschedule(actor); } scheduled_times_.erase(scheduled_time_it); actor_names_.erase(actor_names_it); } void Simulator::Schedule(Actor* actor, QuicTime new_time) { auto scheduled_time_it = scheduled_times_.find(actor); QUICHE_DCHECK(scheduled_time_it != scheduled_times_.end()); QuicTime scheduled_time = scheduled_time_it->second; if (scheduled_time <= new_time) { return; } if (scheduled_time != QuicTime::Infinite()) { Unschedule(actor); } scheduled_time_it->second = new_time; schedule_.insert(std::make_pair(new_time, actor)); } void Simulator::Unschedule(Actor* actor) { auto scheduled_time_it = scheduled_times_.find(actor); QUICHE_DCHECK(scheduled_time_it != scheduled_times_.end()); QuicTime scheduled_time = scheduled_time_it->second; QUICHE_DCHECK(scheduled_time != QuicTime::Infinite()); auto range = schedule_.equal_range(scheduled_time); for (auto it = range.first; it != range.second; ++it) { if (it->second == actor) { schedule_.erase(it); scheduled_time_it->second = QuicTime::Infinite(); return; } } QUICHE_DCHECK(false); } const QuicClock* Simulator::GetClock() const { return &clock_; } QuicRandom* Simulator::GetRandomGenerator() { if (random_generator_ == nullptr) { random_generator_ = QuicRandom::GetInstance(); } return random_generator_; } quiche::QuicheBufferAllocator* Simulator::GetStreamSendBufferAllocator() { return &buffer_allocator_; } QuicAlarmFactory* Simulator::GetAlarmFactory() { return &alarm_factory_; } Simulator::RunForDelegate::RunForDelegate(bool* run_for_should_stop) : run_for_should_stop_(run_for_should_stop) {} void Simulator::RunForDelegate::OnAlarm() { *run_for_should_stop_ = true; } void Simulator::RunFor(QuicTime::Delta time_span) { QUICHE_DCHECK(!run_for_alarm_->IsSet()); const QuicTime end_time = clock_.Now() + time_span; run_for_alarm_->Set(end_time); run_for_should_stop_ = false; bool simulation_result = RunUntil([this]() { return run_for_should_stop_; }); QUICHE_DCHECK(simulation_result); QUICHE_DCHECK(clock_.Now() == end_time); } void Simulator::HandleNextScheduledActor() { const auto current_event_it = schedule_.begin(); QuicTime event_time = current_event_it->first; Actor* actor = current_event_it->second; QUIC_DVLOG(3) << "At t = " << event_time.ToDebuggingValue() << ", calling " << actor->name(); Unschedule(actor); if (clock_.Now() > event_time) { QUIC_BUG(quic_bug_10150_1) << "Error: event registered by [" << actor->name() << "] requires travelling back in time. Current time: " << clock_.Now().ToDebuggingValue() << ", scheduled time: " << event_time.ToDebuggingValue(); } clock_.now_ = event_time; actor->Act(); } } }
#include "quiche/quic/test_tools/simulator/simulator.h" #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/node_hash_map.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/simulator/alarm_factory.h" #include "quiche/quic/test_tools/simulator/link.h" #include "quiche/quic/test_tools/simulator/packet_filter.h" #include "quiche/quic/test_tools/simulator/queue.h" #include "quiche/quic/test_tools/simulator/switch.h" #include "quiche/quic/test_tools/simulator/traffic_policer.h" using testing::_; using testing::Return; using testing::StrictMock; namespace quic { namespace simulator { class Counter : public Actor { public: Counter(Simulator* simulator, std::string name, QuicTime::Delta period) : Actor(simulator, name), value_(-1), period_(period) { Schedule(clock_->Now()); } ~Counter() override {} inline int get_value() const { return value_; } void Act() override { ++value_; QUIC_DVLOG(1) << name_ << " has value " << value_ << " at time " << clock_->Now().ToDebuggingValue(); Schedule(clock_->Now() + period_); } private: int value_; QuicTime::Delta period_; }; class SimulatorTest : public quic::test::QuicTest {}; TEST_F(SimulatorTest, Counters) { Simulator simulator; for (int i = 0; i < 2; ++i) { Counter fast_counter(&simulator, "fast_counter", QuicTime::Delta::FromSeconds(3)); Counter slow_counter(&simulator, "slow_counter", QuicTime::Delta::FromSeconds(10)); simulator.RunUntil( [&slow_counter]() { return slow_counter.get_value() >= 10; }); EXPECT_EQ(10, slow_counter.get_value()); EXPECT_EQ(10 * 10 / 3, fast_counter.get_value()); } } class CounterPort : public UnconstrainedPortInterface { public: CounterPort() { Reset(); } ~CounterPort() override {} inline QuicByteCount bytes() const { return bytes_; } inline QuicPacketCount packets() const { return packets_; } void AcceptPacket(std::unique_ptr<Packet> packet) override { bytes_ += packet->size; packets_ += 1; per_destination_packet_counter_[packet->destination] += 1; } void Reset() { bytes_ = 0; packets_ = 0; per_destination_packet_counter_.clear(); } QuicPacketCount CountPacketsForDestination(std::string destination) const { auto result_it = per_destination_packet_counter_.find(destination); if (result_it == per_destination_packet_counter_.cend()) { return 0; } return result_it->second; } private: QuicByteCount bytes_; QuicPacketCount packets_; absl::node_hash_map<std::string, QuicPacketCount> per_destination_packet_counter_; }; class LinkSaturator : public Endpoint { public: LinkSaturator(Simulator* simulator, std::string name, QuicByteCount packet_size, std::string destination) : Endpoint(simulator, name), packet_size_(packet_size), destination_(std::move(destination)), bytes_transmitted_(0), packets_transmitted_(0) { Schedule(clock_->Now()); } void Act() override { if (tx_port_->TimeUntilAvailable().IsZero()) { auto packet = std::make_unique<Packet>(); packet->source = name_; packet->destination = destination_; packet->tx_timestamp = clock_->Now(); packet->size = packet_size_; tx_port_->AcceptPacket(std::move(packet)); bytes_transmitted_ += packet_size_; packets_transmitted_ += 1; } Schedule(clock_->Now() + tx_port_->TimeUntilAvailable()); } UnconstrainedPortInterface* GetRxPort() override { return static_cast<UnconstrainedPortInterface*>(&rx_port_); } void SetTxPort(ConstrainedPortInterface* port) override { tx_port_ = port; } CounterPort* counter() { return &rx_port_; } inline QuicByteCount bytes_transmitted() const { return bytes_transmitted_; } inline QuicPacketCount packets_transmitted() const { return packets_transmitted_; } void Pause() { Unschedule(); } void Resume() { Schedule(clock_->Now()); } private: QuicByteCount packet_size_; std::string destination_; ConstrainedPortInterface* tx_port_; CounterPort rx_port_; QuicByteCount bytes_transmitted_; QuicPacketCount packets_transmitted_; }; TEST_F(SimulatorTest, DirectLinkSaturation) { Simulator simulator; LinkSaturator saturator_a(&simulator, "Saturator A", 1000, "Saturator B"); LinkSaturator saturator_b(&simulator, "Saturator B", 100, "Saturator A"); SymmetricLink link(&saturator_a, &saturator_b, QuicBandwidth::FromKBytesPerSecond(1000), QuicTime::Delta::FromMilliseconds(100) + QuicTime::Delta::FromMicroseconds(1)); const QuicTime start_time = simulator.GetClock()->Now(); const QuicTime after_first_50_ms = start_time + QuicTime::Delta::FromMilliseconds(50); simulator.RunUntil([&simulator, after_first_50_ms]() { return simulator.GetClock()->Now() >= after_first_50_ms; }); EXPECT_LE(1000u * 50u, saturator_a.bytes_transmitted()); EXPECT_GE(1000u * 51u, saturator_a.bytes_transmitted()); EXPECT_LE(1000u * 50u, saturator_b.bytes_transmitted()); EXPECT_GE(1000u * 51u, saturator_b.bytes_transmitted()); EXPECT_LE(50u, saturator_a.packets_transmitted()); EXPECT_GE(51u, saturator_a.packets_transmitted()); EXPECT_LE(500u, saturator_b.packets_transmitted()); EXPECT_GE(501u, saturator_b.packets_transmitted()); EXPECT_EQ(0u, saturator_a.counter()->bytes()); EXPECT_EQ(0u, saturator_b.counter()->bytes()); simulator.RunUntil([&saturator_a, &saturator_b]() { if (saturator_a.counter()->packets() > 1000 || saturator_b.counter()->packets() > 100) { ADD_FAILURE() << "The simulation did not arrive at the expected " "termination contidition. Saturator A counter: " << saturator_a.counter()->packets() << ", saturator B counter: " << saturator_b.counter()->packets(); return true; } return saturator_a.counter()->packets() == 1000 && saturator_b.counter()->packets() == 100; }); EXPECT_EQ(201u, saturator_a.packets_transmitted()); EXPECT_EQ(2001u, saturator_b.packets_transmitted()); EXPECT_EQ(201u * 1000, saturator_a.bytes_transmitted()); EXPECT_EQ(2001u * 100, saturator_b.bytes_transmitted()); EXPECT_EQ(1000u, saturator_a.counter()->CountPacketsForDestination("Saturator A")); EXPECT_EQ(100u, saturator_b.counter()->CountPacketsForDestination("Saturator B")); EXPECT_EQ(0u, saturator_a.counter()->CountPacketsForDestination("Saturator B")); EXPECT_EQ(0u, saturator_b.counter()->CountPacketsForDestination("Saturator A")); const QuicTime end_time = simulator.GetClock()->Now(); const QuicBandwidth observed_bandwidth = QuicBandwidth::FromBytesAndTimeDelta( saturator_a.bytes_transmitted(), end_time - start_time); EXPECT_APPROX_EQ(link.bandwidth(), observed_bandwidth, 0.01f); } class PacketAcceptor : public ConstrainedPortInterface { public: void AcceptPacket(std::unique_ptr<Packet> packet) override { packets_.emplace_back(std::move(packet)); } QuicTime::Delta TimeUntilAvailable() override { return QuicTime::Delta::Zero(); } std::vector<std::unique_ptr<Packet>>* packets() { return &packets_; } private: std::vector<std::unique_ptr<Packet>> packets_; }; TEST_F(SimulatorTest, Queue) { Simulator simulator; Queue queue(&simulator, "Queue", 1000); PacketAcceptor acceptor; queue.set_tx_port(&acceptor); EXPECT_EQ(0u, queue.bytes_queued()); EXPECT_EQ(0u, queue.packets_queued()); EXPECT_EQ(0u, acceptor.packets()->size()); auto first_packet = std::make_unique<Packet>(); first_packet->size = 600; queue.AcceptPacket(std::move(first_packet)); EXPECT_EQ(600u, queue.bytes_queued()); EXPECT_EQ(1u, queue.packets_queued()); EXPECT_EQ(0u, acceptor.packets()->size()); auto second_packet = std::make_unique<Packet>(); second_packet->size = 500; queue.AcceptPacket(std::move(second_packet)); EXPECT_EQ(600u, queue.bytes_queued()); EXPECT_EQ(1u, queue.packets_queued()); EXPECT_EQ(0u, acceptor.packets()->size()); auto third_packet = std::make_unique<Packet>(); third_packet->size = 400; queue.AcceptPacket(std::move(third_packet)); EXPECT_EQ(1000u, queue.bytes_queued()); EXPECT_EQ(2u, queue.packets_queued()); EXPECT_EQ(0u, acceptor.packets()->size()); simulator.RunUntil([]() { return false; }); EXPECT_EQ(0u, queue.bytes_queued()); EXPECT_EQ(0u, queue.packets_queued()); ASSERT_EQ(2u, acceptor.packets()->size()); EXPECT_EQ(600u, acceptor.packets()->at(0)->size); EXPECT_EQ(400u, acceptor.packets()->at(1)->size); } TEST_F(SimulatorTest, QueueBottleneck) { const QuicBandwidth local_bandwidth = QuicBandwidth::FromKBytesPerSecond(1000); const QuicBandwidth bottleneck_bandwidth = 0.1f * local_bandwidth; const QuicTime::Delta local_propagation_delay = QuicTime::Delta::FromMilliseconds(1); const QuicTime::Delta bottleneck_propagation_delay = QuicTime::Delta::FromMilliseconds(20); const QuicByteCount bdp = bottleneck_bandwidth * (local_propagation_delay + bottleneck_propagation_delay); Simulator simulator; LinkSaturator saturator(&simulator, "Saturator", 1000, "Counter"); ASSERT_GE(bdp, 1000u); Queue queue(&simulator, "Queue", bdp); CounterPort counter; OneWayLink local_link(&simulator, "Local link", &queue, local_bandwidth, local_propagation_delay); OneWayLink bottleneck_link(&simulator, "Bottleneck link", &counter, bottleneck_bandwidth, bottleneck_propagation_delay); saturator.SetTxPort(&local_link); queue.set_tx_port(&bottleneck_link); static const QuicPacketCount packets_received = 1000; simulator.RunUntil( [&counter]() { return counter.packets() == packets_received; }); const double loss_ratio = 1 - static_cast<double>(packets_received) / saturator.packets_transmitted(); EXPECT_NEAR(loss_ratio, 0.9, 0.001); } TEST_F(SimulatorTest, OnePacketQueue) { const QuicBandwidth local_bandwidth = QuicBandwidth::FromKBytesPerSecond(1000); const QuicBandwidth bottleneck_bandwidth = 0.1f * local_bandwidth; const QuicTime::Delta local_propagation_delay = QuicTime::Delta::FromMilliseconds(1); const QuicTime::Delta bottleneck_propagation_delay = QuicTime::Delta::FromMilliseconds(20); Simulator simulator; LinkSaturator saturator(&simulator, "Saturator", 1000, "Counter"); Queue queue(&simulator, "Queue", 1000); CounterPort counter; OneWayLink local_link(&simulator, "Local link", &queue, local_bandwidth, local_propagation_delay); OneWayLink bottleneck_link(&simulator, "Bottleneck link", &counter, bottleneck_bandwidth, bottleneck_propagation_delay); saturator.SetTxPort(&local_link); queue.set_tx_port(&bottleneck_link); static const QuicPacketCount packets_received = 10; const QuicTime deadline = simulator.GetClock()->Now() + QuicTime::Delta::FromSeconds(10); simulator.RunUntil([&simulator, &counter, deadline]() { return counter.packets() == packets_received || simulator.GetClock()->Now() > deadline; }); ASSERT_EQ(packets_received, counter.packets()); } TEST_F(SimulatorTest, SwitchedNetwork) { const QuicBandwidth bandwidth = QuicBandwidth::FromBytesPerSecond(10000); const QuicTime::Delta base_propagation_delay = QuicTime::Delta::FromMilliseconds(50); Simulator simulator; LinkSaturator saturator1(&simulator, "Saturator 1", 1000, "Saturator 2"); LinkSaturator saturator2(&simulator, "Saturator 2", 1000, "Saturator 3"); LinkSaturator saturator3(&simulator, "Saturator 3", 1000, "Saturator 1"); Switch network_switch(&simulator, "Switch", 8, bandwidth * base_propagation_delay * 10); SymmetricLink link1(&saturator1, network_switch.port(1), bandwidth, base_propagation_delay); SymmetricLink link2(&saturator2, network_switch.port(2), bandwidth, base_propagation_delay * 2); SymmetricLink link3(&saturator3, network_switch.port(3), bandwidth, base_propagation_delay * 3); const QuicTime start_time = simulator.GetClock()->Now(); static const QuicPacketCount bytes_received = 64 * 1000; simulator.RunUntil([&saturator1]() { return saturator1.counter()->bytes() >= bytes_received; }); const QuicTime end_time = simulator.GetClock()->Now(); const QuicBandwidth observed_bandwidth = QuicBandwidth::FromBytesAndTimeDelta( bytes_received, end_time - start_time); const double bandwidth_ratio = static_cast<double>(observed_bandwidth.ToBitsPerSecond()) / bandwidth.ToBitsPerSecond(); EXPECT_NEAR(1, bandwidth_ratio, 0.1); const double normalized_received_packets_for_saturator_2 = static_cast<double>(saturator2.counter()->packets()) / saturator1.counter()->packets(); const double normalized_received_packets_for_saturator_3 = static_cast<double>(saturator3.counter()->packets()) / saturator1.counter()->packets(); EXPECT_NEAR(1, normalized_received_packets_for_saturator_2, 0.1); EXPECT_NEAR(1, normalized_received_packets_for_saturator_3, 0.1); EXPECT_EQ(0u, saturator2.counter()->CountPacketsForDestination("Saturator 1")); EXPECT_EQ(0u, saturator3.counter()->CountPacketsForDestination("Saturator 1")); EXPECT_EQ(1u, saturator1.counter()->CountPacketsForDestination("Saturator 2")); EXPECT_EQ(1u, saturator3.counter()->CountPacketsForDestination("Saturator 2")); EXPECT_EQ(1u, saturator1.counter()->CountPacketsForDestination("Saturator 3")); EXPECT_EQ(1u, saturator2.counter()->CountPacketsForDestination("Saturator 3")); } class AlarmToggler : public Actor { public: AlarmToggler(Simulator* simulator, std::string name, QuicAlarm* alarm, QuicTime::Delta interval) : Actor(simulator, name), alarm_(alarm), interval_(interval), deadline_(alarm->deadline()), times_set_(0), times_cancelled_(0) { EXPECT_TRUE(alarm->IsSet()); EXPECT_GE(alarm->deadline(), clock_->Now()); Schedule(clock_->Now()); } void Act() override { if (deadline_ <= clock_->Now()) { return; } if (alarm_->IsSet()) { alarm_->Cancel(); times_cancelled_++; } else { alarm_->Set(deadline_); times_set_++; } Schedule(clock_->Now() + interval_); } inline int times_set() { return times_set_; } inline int times_cancelled() { return times_cancelled_; } private: QuicAlarm* alarm_; QuicTime::Delta interval_; QuicTime deadline_; int times_set_; int times_cancelled_; }; class CounterDelegate : public QuicAlarm::DelegateWithoutContext { public: explicit CounterDelegate(size_t* counter) : counter_(counter) {} void OnAlarm() override { *counter_ += 1; } private: size_t* counter_; }; TEST_F(SimulatorTest, Alarms) { Simulator simulator; QuicAlarmFactory* alarm_factory = simulator.GetAlarmFactory(); size_t fast_alarm_counter = 0; size_t slow_alarm_counter = 0; std::unique_ptr<QuicAlarm> alarm_fast( alarm_factory->CreateAlarm(new CounterDelegate(&fast_alarm_counter))); std::unique_ptr<QuicAlarm> alarm_slow( alarm_factory->CreateAlarm(new CounterDelegate(&slow_alarm_counter))); const QuicTime start_time = simulator.GetClock()->Now(); alarm_fast->Set(start_time + QuicTime::Delta::FromMilliseconds(100)); alarm_slow->Set(start_time + QuicTime::Delta::FromMilliseconds(750)); AlarmToggler toggler(&simulator, "Toggler", alarm_slow.get(), QuicTime::Delta::FromMilliseconds(100)); const QuicTime end_time = start_time + QuicTime::Delta::FromMilliseconds(1000); EXPECT_FALSE(simulator.RunUntil([&simulator, end_time]() { return simulator.GetClock()->Now() >= end_time; })); EXPECT_EQ(1u, slow_alarm_counter); EXPECT_EQ(1u, fast_alarm_counter); EXPECT_EQ(4, toggler.times_set()); EXPECT_EQ(4, toggler.times_cancelled()); } TEST_F(SimulatorTest, AlarmCancelling) { Simulator simulator; QuicAlarmFactory* alarm_factory = simulator.GetAlarmFactory(); size_t alarm_counter = 0; std::unique_ptr<QuicAlarm> alarm( alarm_factory->CreateAlarm(new CounterDelegate(&alarm_counter))); const QuicTime start_time = simulator.GetClock()->Now(); const QuicTime alarm_at = start_time + QuicTime::Delta::FromMilliseconds(300); const QuicTime end_time = start_time + QuicTime::Delta::FromMilliseconds(400); alarm->Set(alarm_at); alarm->Cancel(); EXPECT_FALSE(alarm->IsSet()); EXPECT_FALSE(simulator.RunUntil([&simulator, end_time]() { return simulator.GetClock()->Now() >= end_time; })); EXPECT_FALSE(alarm->IsSet()); EXPECT_EQ(0u, alarm_counter); } TEST_F(SimulatorTest, AlarmInPast) { Simulator simulator; QuicAlarmFactory* alarm_factory = simulator.GetAlarmFactory(); size_t alarm_counter = 0; std::unique_ptr<QuicAlarm> alarm( alarm_factory->CreateAlarm(new CounterDelegate(&alarm_counter))); const QuicTime start_time = simulator.GetClock()->Now(); simulator.RunFor(QuicTime::Delta::FromMilliseconds(400)); alarm->Set(start_time); simulator.RunFor(QuicTime::Delta::FromMilliseconds(1)); EXPECT_FALSE(alarm->IsSet()); EXPECT_EQ(1u, alarm_counter); } TEST_F(SimulatorTest, RunUntilOrTimeout) { Simulator simulator; bool simulation_result; Counter counter(&simulator, "counter", QuicTime::Delta::FromSeconds(1)); simulation_result = simulator.RunUntilOrTimeout( [&counter]() { return counter.get_value() == 10; }, QuicTime::Delta::FromSeconds(20)); ASSERT_TRUE(simulation_result); simulation_result = simulator.RunUntilOrTimeout( [&counter]() { return counter.get_value() == 100; }, QuicTime::Delta::FromSeconds(20)); ASSERT_FALSE(simulation_result); } TEST_F(SimulatorTest, RunFor) { Simulator simulator; Counter counter(&simulator, "counter", QuicTime::Delta::FromSeconds(3)); simulator.RunFor(QuicTime::Delta::FromSeconds(100)); EXPECT_EQ(33, counter.get_value()); } class MockPacketFilter : public PacketFilter { public: MockPacketFilter(Simulator* simulator, std::string name, Endpoint* endpoint) : PacketFilter(simulator, name, endpoint) {} MOCK_METHOD(bool, FilterPacket, (const Packet&), (override)); }; TEST_F(SimulatorTest, PacketFilter) { const QuicBandwidth bandwidth = QuicBandwidth::FromBytesPerSecond(1024 * 1024); const QuicTime::Delta base_propagation_delay = QuicTime::Delta::FromMilliseconds(5); Simulator simulator; LinkSaturator saturator_a(&simulator, "Saturator A", 1000, "Saturator B"); LinkSaturator saturator_b(&simulator, "Saturator B", 1000, "Saturator A"); Switch network_switch(&simulator, "Switch", 8, bandwidth * base_propagation_delay * 10); StrictMock<MockPacketFilter> a_to_b_filter(&simulator, "A -> B filter", network_switch.port(1)); StrictMock<MockPacketFilter> b_to_a_filter(&simulator, "B -> A filter", network_switch.port(2)); SymmetricLink link_a(&a_to_b_filter, &saturator_b, bandwidth, base_propagation_delay); SymmetricLink link_b(&b_to_a_filter, &saturator_a, bandwidth, base_propagation_delay); EXPECT_CALL(a_to_b_filter, FilterPacket(_)).WillRepeatedly(Return(true)); EXPECT_CALL(b_to_a_filter, FilterPacket(_)).WillRepeatedly(Return(false)); simulator.RunFor(QuicTime::Delta::FromSeconds(10)); EXPECT_GE(saturator_b.counter()->packets(), 1u); EXPECT_EQ(saturator_a.counter()->packets(), 0u); } TEST_F(SimulatorTest, TrafficPolicer) { const QuicBandwidth bandwidth = QuicBandwidth::FromBytesPerSecond(1024 * 1024); const QuicTime::Delta base_propagation_delay = QuicTime::Delta::FromMilliseconds(5); const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(10); Simulator simulator; LinkSaturator saturator1(&simulator, "Saturator 1", 1000, "Saturator 2"); LinkSaturator saturator2(&simulator, "Saturator 2", 1000, "Saturator 1"); Switch network_switch(&simulator, "Switch", 8, bandwidth * base_propagation_delay * 10); static const QuicByteCount initial_burst = 1000 * 10; static const QuicByteCount max_bucket_size = 1000 * 100; static const QuicBandwidth target_bandwidth = bandwidth * 0.25; TrafficPolicer policer(&simulator, "Policer", initial_burst, max_bucket_size, target_bandwidth, network_switch.port(2)); SymmetricLink link1(&saturator1, network_switch.port(1), bandwidth, base_propagation_delay); SymmetricLink link2(&saturator2, &policer, bandwidth, base_propagation_delay); bool simulator_result = simulator.RunUntilOrTimeout( [&saturator1]() { return saturator1.bytes_transmitted() == initial_burst; }, timeout); ASSERT_TRUE(simulator_result); saturator1.Pause(); simulator_result = simulator.RunUntilOrTimeout( [&saturator2]() { return saturator2.counter()->bytes() == initial_burst; }, timeout); ASSERT_TRUE(simulator_result); saturator1.Resume(); const QuicTime::Delta simulation_time = QuicTime::Delta::FromSeconds(10); simulator.RunFor(simulation_time); for (auto* saturator : {&saturator1, &saturator2}) { EXPECT_APPROX_EQ(bandwidth * simulation_time, saturator->bytes_transmitted(), 0.01f); } EXPECT_APPROX_EQ(saturator1.bytes_transmitted() / 4, saturator2.counter()->bytes(), 0.1f); EXPECT_APPROX_EQ(saturator2.bytes_transmitted(), saturator1.counter()->bytes(), 0.1f); } TEST_F(SimulatorTest, TrafficPolicerBurst) { const QuicBandwidth bandwidth = QuicBandwidth::FromBytesPerSecond(1024 * 1024); const QuicTime::Delta base_propagation_delay = QuicTime::Delta::FromMilliseconds(5); const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(10); Simulator simulator; LinkSaturator saturator1(&simulator, "Saturator 1", 1000, "Saturator 2"); LinkSaturator saturator2(&simulator, "Saturator 2", 1000, "Saturator 1"); Switch network_switch(&simulator, "Switch", 8, bandwidth * base_propagation_delay * 10); const QuicByteCount initial_burst = 1000 * 10; const QuicByteCount max_bucket_size = 1000 * 100; const QuicBandwidth target_bandwidth = bandwidth * 0.25; TrafficPolicer policer(&simulator, "Policer", initial_burst, max_bucket_size, target_bandwidth, network_switch.port(2)); SymmetricLink link1(&saturator1, network_switch.port(1), bandwidth, base_propagation_delay); SymmetricLink link2(&saturator2, &policer, bandwidth, base_propagation_delay); bool simulator_result = simulator.RunUntilOrTimeout( [&saturator1, &saturator2]() { return saturator1.packets_transmitted() > 0 && saturator2.packets_transmitted() > 0; }, timeout); ASSERT_TRUE(simulator_result); saturator1.Pause(); saturator2.Pause(); simulator.RunFor(1.5f * target_bandwidth.TransferTime(max_bucket_size)); saturator1.Resume(); simulator.RunFor(bandwidth.TransferTime(max_bucket_size)); saturator1.Pause(); simulator.RunFor(2 * base_propagation_delay); EXPECT_APPROX_EQ(saturator1.bytes_transmitted(), saturator2.counter()->bytes(), 0.1f); saturator1.Resume(); simulator.RunFor(QuicTime::Delta::FromSeconds(10)); EXPECT_APPROX_EQ(saturator1.bytes_transmitted() / 4, saturator2.counter()->bytes(), 0.1f); } TEST_F(SimulatorTest, PacketAggregation) { const QuicBandwidth bandwidth = QuicBandwidth::FromBytesPerSecond(1000); const QuicTime::Delta base_propagation_delay = QuicTime::Delta::FromMicroseconds(1); const QuicByteCount aggregation_threshold = 1000; const QuicTime::Delta aggregation_timeout = QuicTime::Delta::FromSeconds(30); Simulator simulator; LinkSaturator saturator1(&simulator, "Saturator 1", 10, "Saturator 2"); LinkSaturator saturator2(&simulator, "Saturator 2", 10, "Saturator 1"); Switch network_switch(&simulator, "Switch", 8, 10 * aggregation_threshold); SymmetricLink link1(&saturator1, network_switch.port(1), bandwidth, base_propagation_delay); SymmetricLink link2(&saturator2, network_switch.port(2), bandwidth, 2 * base_propagation_delay); Queue* queue = network_switch.port_queue(2); queue->EnableAggregation(aggregation_threshold, aggregation_timeout); network_switch.port_queue(1)->EnableAggregation(5, aggregation_timeout); simulator.RunFor(0.9 * bandwidth.TransferTime(aggregation_threshold)); EXPECT_EQ(0u, saturator2.counter()->bytes()); saturator1.Pause(); saturator2.Pause(); simulator.RunFor(QuicTime::Delta::FromSeconds(10)); EXPECT_EQ(0u, saturator2.counter()->bytes()); EXPECT_EQ(900u, queue->bytes_queued()); EXPECT_EQ(910u, saturator1.counter()->bytes()); saturator1.Resume(); simulator.RunFor(0.5 * bandwidth.TransferTime(aggregation_threshold)); saturator1.Pause(); simulator.RunFor(QuicTime::Delta::FromSeconds(10)); EXPECT_EQ(1000u, saturator2.counter()->bytes()); EXPECT_EQ(400u, queue->bytes_queued()); simulator.RunFor(aggregation_timeout); EXPECT_EQ(1400u, saturator2.counter()->bytes()); EXPECT_EQ(0u, queue->bytes_queued()); saturator1.Resume(); simulator.RunFor(5.5 * bandwidth.TransferTime(aggregation_threshold)); saturator1.Pause(); simulator.RunFor(QuicTime::Delta::FromSeconds(10)); EXPECT_EQ(6400u, saturator2.counter()->bytes()); EXPECT_EQ(500u, queue->bytes_queued()); simulator.RunFor(aggregation_timeout); EXPECT_EQ(6900u, saturator2.counter()->bytes()); EXPECT_EQ(0u, queue->bytes_queued()); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/test_tools/simulator/simulator.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/test_tools/simulator/simulator_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
58149a92-130e-465a-897d-2bb9af5d8f4b
cpp
google/quiche
quic_endpoint
quiche/quic/test_tools/simulator/quic_endpoint.cc
quiche/quic/test_tools/simulator/quic_endpoint_test.cc
#include "quiche/quic/test_tools/simulator/quic_endpoint.h" #include <algorithm> #include <memory> #include <string> #include <utility> #include "quiche/quic/core/crypto/crypto_handshake_message.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/platform/api/quic_test_output.h" #include "quiche/quic/test_tools/quic_config_peer.h" #include "quiche/quic/test_tools/quic_connection_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/simulator/simulator.h" namespace quic { namespace simulator { const QuicStreamId kDataStream = 3; const QuicByteCount kWriteChunkSize = 128 * 1024; const char kStreamDataContents = 'Q'; QuicEndpoint::QuicEndpoint(Simulator* simulator, std::string name, std::string peer_name, Perspective perspective, QuicConnectionId connection_id) : QuicEndpointBase(simulator, name, peer_name), bytes_to_transfer_(0), bytes_transferred_(0), wrong_data_received_(false), notifier_(nullptr) { connection_ = std::make_unique<QuicConnection>( connection_id, GetAddressFromName(name), GetAddressFromName(peer_name), simulator, simulator->GetAlarmFactory(), &writer_, false, perspective, ParsedVersionOfIndex(CurrentSupportedVersions(), 0), connection_id_generator_); connection_->set_visitor(this); connection_->SetEncrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<quic::test::TaggingEncrypter>( ENCRYPTION_FORWARD_SECURE)); connection_->SetEncrypter(ENCRYPTION_INITIAL, nullptr); if (connection_->version().KnowsWhichDecrypterToUse()) { connection_->InstallDecrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<quic::test::StrictTaggingDecrypter>( ENCRYPTION_FORWARD_SECURE)); connection_->RemoveDecrypter(ENCRYPTION_INITIAL); } else { connection_->SetDecrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<quic::test::StrictTaggingDecrypter>( ENCRYPTION_FORWARD_SECURE)); } connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_->OnHandshakeComplete(); if (perspective == Perspective::IS_SERVER) { test::QuicConnectionPeer::SetNegotiatedVersion(connection_.get()); } test::QuicConnectionPeer::SetAddressValidated(connection_.get()); connection_->SetDataProducer(&producer_); connection_->SetSessionNotifier(this); notifier_ = std::make_unique<test::SimpleSessionNotifier>(connection_.get()); std::string error; CryptoHandshakeMessage peer_hello; peer_hello.SetValue(kICSL, static_cast<uint32_t>(kMaximumIdleTimeoutSecs - 1)); peer_hello.SetValue(kMIBS, static_cast<uint32_t>(kDefaultMaxStreamsPerConnection)); QuicConfig config; QuicErrorCode error_code = config.ProcessPeerHello( peer_hello, perspective == Perspective::IS_CLIENT ? SERVER : CLIENT, &error); QUICHE_DCHECK_EQ(error_code, QUIC_NO_ERROR) << "Configuration failed: " << error; if (connection_->version().UsesTls()) { if (connection_->perspective() == Perspective::IS_CLIENT) { test::QuicConfigPeer::SetReceivedOriginalConnectionId( &config, connection_->connection_id()); test::QuicConfigPeer::SetReceivedInitialSourceConnectionId( &config, connection_->connection_id()); } else { test::QuicConfigPeer::SetReceivedInitialSourceConnectionId( &config, connection_->client_connection_id()); } } connection_->SetFromConfig(config); connection_->DisableMtuDiscovery(); } QuicByteCount QuicEndpoint::bytes_received() const { QuicByteCount total = 0; for (auto& interval : offsets_received_) { total += interval.max() - interval.min(); } return total; } QuicByteCount QuicEndpoint::bytes_to_transfer() const { if (notifier_ != nullptr) { return notifier_->StreamBytesToSend(); } return bytes_to_transfer_; } QuicByteCount QuicEndpoint::bytes_transferred() const { if (notifier_ != nullptr) { return notifier_->StreamBytesSent(); } return bytes_transferred_; } void QuicEndpoint::AddBytesToTransfer(QuicByteCount bytes) { if (notifier_ != nullptr) { if (notifier_->HasBufferedStreamData()) { Schedule(clock_->Now()); } notifier_->WriteOrBufferData(kDataStream, bytes, NO_FIN); return; } if (bytes_to_transfer_ > 0) { Schedule(clock_->Now()); } bytes_to_transfer_ += bytes; WriteStreamData(); } void QuicEndpoint::OnStreamFrame(const QuicStreamFrame& frame) { QUICHE_DCHECK(frame.stream_id == kDataStream); for (size_t i = 0; i < frame.data_length; i++) { if (frame.data_buffer[i] != kStreamDataContents) { wrong_data_received_ = true; } } offsets_received_.Add(frame.offset, frame.offset + frame.data_length); QUICHE_DCHECK_LE(offsets_received_.Size(), 1000u); } void QuicEndpoint::OnCryptoFrame(const QuicCryptoFrame& ) {} void QuicEndpoint::OnCanWrite() { if (notifier_ != nullptr) { notifier_->OnCanWrite(); return; } WriteStreamData(); } bool QuicEndpoint::WillingAndAbleToWrite() const { if (notifier_ != nullptr) { return notifier_->WillingToWrite(); } return bytes_to_transfer_ != 0; } bool QuicEndpoint::ShouldKeepConnectionAlive() const { return true; } bool QuicEndpoint::AllowSelfAddressChange() const { return false; } bool QuicEndpoint::OnFrameAcked(const QuicFrame& frame, QuicTime::Delta ack_delay_time, QuicTime receive_timestamp) { if (notifier_ != nullptr) { return notifier_->OnFrameAcked(frame, ack_delay_time, receive_timestamp); } return false; } void QuicEndpoint::OnFrameLost(const QuicFrame& frame) { QUICHE_DCHECK(notifier_); notifier_->OnFrameLost(frame); } bool QuicEndpoint::RetransmitFrames(const QuicFrames& frames, TransmissionType type) { QUICHE_DCHECK(notifier_); return notifier_->RetransmitFrames(frames, type); } bool QuicEndpoint::IsFrameOutstanding(const QuicFrame& frame) const { QUICHE_DCHECK(notifier_); return notifier_->IsFrameOutstanding(frame); } bool QuicEndpoint::HasUnackedCryptoData() const { return false; } bool QuicEndpoint::HasUnackedStreamData() const { if (notifier_ != nullptr) { return notifier_->HasUnackedStreamData(); } return false; } HandshakeState QuicEndpoint::GetHandshakeState() const { return HANDSHAKE_COMPLETE; } WriteStreamDataResult QuicEndpoint::DataProducer::WriteStreamData( QuicStreamId , QuicStreamOffset , QuicByteCount data_length, QuicDataWriter* writer) { writer->WriteRepeatedByte(kStreamDataContents, data_length); return WRITE_SUCCESS; } bool QuicEndpoint::DataProducer::WriteCryptoData(EncryptionLevel , QuicStreamOffset , QuicByteCount , QuicDataWriter* ) { QUIC_BUG(quic_bug_10157_1) << "QuicEndpoint::DataProducer::WriteCryptoData is unimplemented"; return false; } void QuicEndpoint::WriteStreamData() { QuicConnection::ScopedPacketFlusher flusher(connection_.get()); while (bytes_to_transfer_ > 0) { const size_t transmission_size = std::min(kWriteChunkSize, bytes_to_transfer_); QuicConsumedData consumed_data = connection_->SendStreamData( kDataStream, transmission_size, bytes_transferred_, NO_FIN); QUICHE_DCHECK(consumed_data.bytes_consumed <= transmission_size); bytes_transferred_ += consumed_data.bytes_consumed; bytes_to_transfer_ -= consumed_data.bytes_consumed; if (consumed_data.bytes_consumed != transmission_size) { return; } } } } }
#include "quiche/quic/test_tools/simulator/quic_endpoint.h" #include <memory> #include <utility> #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_connection_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/simulator/simulator.h" #include "quiche/quic/test_tools/simulator/switch.h" using ::testing::_; using ::testing::NiceMock; using ::testing::Return; namespace quic { namespace simulator { const QuicBandwidth kDefaultBandwidth = QuicBandwidth::FromKBitsPerSecond(10 * 1000); const QuicTime::Delta kDefaultPropagationDelay = QuicTime::Delta::FromMilliseconds(20); const QuicByteCount kDefaultBdp = kDefaultBandwidth * kDefaultPropagationDelay; class QuicEndpointTest : public quic::test::QuicTest { public: QuicEndpointTest() : simulator_(), switch_(&simulator_, "Switch", 8, kDefaultBdp * 2) {} protected: Simulator simulator_; Switch switch_; std::unique_ptr<SymmetricLink> Link(Endpoint* a, Endpoint* b) { return std::make_unique<SymmetricLink>(a, b, kDefaultBandwidth, kDefaultPropagationDelay); } std::unique_ptr<SymmetricLink> CustomLink(Endpoint* a, Endpoint* b, uint64_t extra_rtt_ms) { return std::make_unique<SymmetricLink>( a, b, kDefaultBandwidth, kDefaultPropagationDelay + QuicTime::Delta::FromMilliseconds(extra_rtt_ms)); } }; TEST_F(QuicEndpointTest, OneWayTransmission) { QuicEndpoint endpoint_a(&simulator_, "Endpoint A", "Endpoint B", Perspective::IS_CLIENT, test::TestConnectionId(42)); QuicEndpoint endpoint_b(&simulator_, "Endpoint B", "Endpoint A", Perspective::IS_SERVER, test::TestConnectionId(42)); auto link_a = Link(&endpoint_a, switch_.port(1)); auto link_b = Link(&endpoint_b, switch_.port(2)); endpoint_a.AddBytesToTransfer(600); QuicTime end_time = simulator_.GetClock()->Now() + QuicTime::Delta::FromMilliseconds(1000); simulator_.RunUntil( [this, end_time]() { return simulator_.GetClock()->Now() >= end_time; }); EXPECT_EQ(600u, endpoint_a.bytes_transferred()); ASSERT_EQ(600u, endpoint_b.bytes_received()); EXPECT_FALSE(endpoint_a.wrong_data_received()); EXPECT_FALSE(endpoint_b.wrong_data_received()); endpoint_a.AddBytesToTransfer(2 * 1024 * 1024); end_time = simulator_.GetClock()->Now() + QuicTime::Delta::FromSeconds(5); simulator_.RunUntil( [this, end_time]() { return simulator_.GetClock()->Now() >= end_time; }); const QuicByteCount total_bytes_transferred = 600 + 2 * 1024 * 1024; EXPECT_EQ(total_bytes_transferred, endpoint_a.bytes_transferred()); EXPECT_EQ(total_bytes_transferred, endpoint_b.bytes_received()); EXPECT_EQ(0u, endpoint_a.write_blocked_count()); EXPECT_FALSE(endpoint_a.wrong_data_received()); EXPECT_FALSE(endpoint_b.wrong_data_received()); } TEST_F(QuicEndpointTest, WriteBlocked) { QuicEndpoint endpoint_a(&simulator_, "Endpoint A", "Endpoint B", Perspective::IS_CLIENT, test::TestConnectionId(42)); QuicEndpoint endpoint_b(&simulator_, "Endpoint B", "Endpoint A", Perspective::IS_SERVER, test::TestConnectionId(42)); auto link_a = Link(&endpoint_a, switch_.port(1)); auto link_b = Link(&endpoint_b, switch_.port(2)); auto* sender = new NiceMock<test::MockSendAlgorithm>(); EXPECT_CALL(*sender, CanSend(_)).WillRepeatedly(Return(true)); EXPECT_CALL(*sender, PacingRate(_)) .WillRepeatedly(Return(10 * kDefaultBandwidth)); EXPECT_CALL(*sender, BandwidthEstimate()) .WillRepeatedly(Return(10 * kDefaultBandwidth)); EXPECT_CALL(*sender, GetCongestionWindow()) .WillRepeatedly(Return(kMaxOutgoingPacketSize * GetQuicFlag(quic_max_congestion_window))); test::QuicConnectionPeer::SetSendAlgorithm(endpoint_a.connection(), sender); QuicByteCount bytes_to_transfer = 3 * 1024 * 1024; endpoint_a.AddBytesToTransfer(bytes_to_transfer); QuicTime end_time = simulator_.GetClock()->Now() + QuicTime::Delta::FromSeconds(30); simulator_.RunUntil([this, &endpoint_b, bytes_to_transfer, end_time]() { return endpoint_b.bytes_received() == bytes_to_transfer || simulator_.GetClock()->Now() >= end_time; }); EXPECT_EQ(bytes_to_transfer, endpoint_a.bytes_transferred()); EXPECT_EQ(bytes_to_transfer, endpoint_b.bytes_received()); EXPECT_GT(endpoint_a.write_blocked_count(), 0u); EXPECT_FALSE(endpoint_a.wrong_data_received()); EXPECT_FALSE(endpoint_b.wrong_data_received()); } TEST_F(QuicEndpointTest, TwoWayTransmission) { QuicEndpoint endpoint_a(&simulator_, "Endpoint A", "Endpoint B", Perspective::IS_CLIENT, test::TestConnectionId(42)); QuicEndpoint endpoint_b(&simulator_, "Endpoint B", "Endpoint A", Perspective::IS_SERVER, test::TestConnectionId(42)); auto link_a = Link(&endpoint_a, switch_.port(1)); auto link_b = Link(&endpoint_b, switch_.port(2)); endpoint_a.RecordTrace(); endpoint_b.RecordTrace(); endpoint_a.AddBytesToTransfer(1024 * 1024); endpoint_b.AddBytesToTransfer(1024 * 1024); QuicTime end_time = simulator_.GetClock()->Now() + QuicTime::Delta::FromSeconds(5); simulator_.RunUntil( [this, end_time]() { return simulator_.GetClock()->Now() >= end_time; }); EXPECT_EQ(1024u * 1024u, endpoint_a.bytes_transferred()); EXPECT_EQ(1024u * 1024u, endpoint_b.bytes_transferred()); EXPECT_EQ(1024u * 1024u, endpoint_a.bytes_received()); EXPECT_EQ(1024u * 1024u, endpoint_b.bytes_received()); EXPECT_FALSE(endpoint_a.wrong_data_received()); EXPECT_FALSE(endpoint_b.wrong_data_received()); } TEST_F(QuicEndpointTest, Competition) { auto endpoint_a = std::make_unique<QuicEndpoint>( &simulator_, "Endpoint A", "Endpoint D (A)", Perspective::IS_CLIENT, test::TestConnectionId(42)); auto endpoint_b = std::make_unique<QuicEndpoint>( &simulator_, "Endpoint B", "Endpoint D (B)", Perspective::IS_CLIENT, test::TestConnectionId(43)); auto endpoint_c = std::make_unique<QuicEndpoint>( &simulator_, "Endpoint C", "Endpoint D (C)", Perspective::IS_CLIENT, test::TestConnectionId(44)); auto endpoint_d_a = std::make_unique<QuicEndpoint>( &simulator_, "Endpoint D (A)", "Endpoint A", Perspective::IS_SERVER, test::TestConnectionId(42)); auto endpoint_d_b = std::make_unique<QuicEndpoint>( &simulator_, "Endpoint D (B)", "Endpoint B", Perspective::IS_SERVER, test::TestConnectionId(43)); auto endpoint_d_c = std::make_unique<QuicEndpoint>( &simulator_, "Endpoint D (C)", "Endpoint C", Perspective::IS_SERVER, test::TestConnectionId(44)); QuicEndpointMultiplexer endpoint_d( "Endpoint D", {endpoint_d_a.get(), endpoint_d_b.get(), endpoint_d_c.get()}); auto link_a = CustomLink(endpoint_a.get(), switch_.port(1), 0); auto link_b = CustomLink(endpoint_b.get(), switch_.port(2), 1); auto link_c = CustomLink(endpoint_c.get(), switch_.port(3), 2); auto link_d = Link(&endpoint_d, switch_.port(4)); endpoint_a->AddBytesToTransfer(2 * 1024 * 1024); endpoint_b->AddBytesToTransfer(2 * 1024 * 1024); endpoint_c->AddBytesToTransfer(2 * 1024 * 1024); QuicTime end_time = simulator_.GetClock()->Now() + QuicTime::Delta::FromSeconds(12); simulator_.RunUntil( [this, end_time]() { return simulator_.GetClock()->Now() >= end_time; }); for (QuicEndpoint* endpoint : {endpoint_a.get(), endpoint_b.get(), endpoint_c.get()}) { EXPECT_EQ(2u * 1024u * 1024u, endpoint->bytes_transferred()); EXPECT_GE(endpoint->connection()->GetStats().packets_lost, 0u); } for (QuicEndpoint* endpoint : {endpoint_d_a.get(), endpoint_d_b.get(), endpoint_d_c.get()}) { EXPECT_EQ(2u * 1024u * 1024u, endpoint->bytes_received()); EXPECT_FALSE(endpoint->wrong_data_received()); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/test_tools/simulator/quic_endpoint.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/test_tools/simulator/quic_endpoint_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
e025328a-7fcb-4e73-a31a-719e9981215e
cpp
google/quiche
quic_socket_address
quiche/quic/platform/api/quic_socket_address.cc
quiche/quic/platform/api/quic_socket_address_test.cc
#include "quiche/quic/platform/api/quic_socket_address.h" #include <cstring> #include <limits> #include <string> #include "absl/strings/str_cat.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_ip_address_family.h" namespace quic { namespace { uint32_t HashIP(const QuicIpAddress& ip) { if (ip.IsIPv4()) { return ip.GetIPv4().s_addr; } if (ip.IsIPv6()) { auto v6addr = ip.GetIPv6(); const uint32_t* v6_as_ints = reinterpret_cast<const uint32_t*>(&v6addr.s6_addr); return v6_as_ints[0] ^ v6_as_ints[1] ^ v6_as_ints[2] ^ v6_as_ints[3]; } return 0; } } QuicSocketAddress::QuicSocketAddress(QuicIpAddress address, uint16_t port) : host_(address), port_(port) {} QuicSocketAddress::QuicSocketAddress(const struct sockaddr_storage& saddr) { switch (saddr.ss_family) { case AF_INET: { const sockaddr_in* v4 = reinterpret_cast<const sockaddr_in*>(&saddr); host_ = QuicIpAddress(v4->sin_addr); port_ = ntohs(v4->sin_port); break; } case AF_INET6: { const sockaddr_in6* v6 = reinterpret_cast<const sockaddr_in6*>(&saddr); host_ = QuicIpAddress(v6->sin6_addr); port_ = ntohs(v6->sin6_port); break; } default: QUIC_BUG(quic_bug_10075_1) << "Unknown address family passed: " << saddr.ss_family; break; } } QuicSocketAddress::QuicSocketAddress(const sockaddr* saddr, socklen_t len) { sockaddr_storage storage; static_assert(std::numeric_limits<socklen_t>::max() >= sizeof(storage), "Cannot cast sizeof(storage) to socklen_t as it does not fit"); if (len < static_cast<socklen_t>(sizeof(sockaddr)) || (saddr->sa_family == AF_INET && len < static_cast<socklen_t>(sizeof(sockaddr_in))) || (saddr->sa_family == AF_INET6 && len < static_cast<socklen_t>(sizeof(sockaddr_in6))) || len > static_cast<socklen_t>(sizeof(storage))) { QUIC_BUG(quic_bug_10075_2) << "Socket address of invalid length provided"; return; } memcpy(&storage, saddr, len); *this = QuicSocketAddress(storage); } bool operator==(const QuicSocketAddress& lhs, const QuicSocketAddress& rhs) { return lhs.host_ == rhs.host_ && lhs.port_ == rhs.port_; } bool operator!=(const QuicSocketAddress& lhs, const QuicSocketAddress& rhs) { return !(lhs == rhs); } bool QuicSocketAddress::IsInitialized() const { return host_.IsInitialized(); } std::string QuicSocketAddress::ToString() const { switch (host_.address_family()) { case IpAddressFamily::IP_V4: return absl::StrCat(host_.ToString(), ":", port_); case IpAddressFamily::IP_V6: return absl::StrCat("[", host_.ToString(), "]:", port_); default: return ""; } } int QuicSocketAddress::FromSocket(int fd) { sockaddr_storage addr; socklen_t addr_len = sizeof(addr); int result = getsockname(fd, reinterpret_cast<sockaddr*>(&addr), &addr_len); bool success = result == 0 && addr_len > 0 && static_cast<size_t>(addr_len) <= sizeof(addr); if (success) { *this = QuicSocketAddress(addr); return 0; } return -1; } QuicSocketAddress QuicSocketAddress::Normalized() const { return QuicSocketAddress(host_.Normalized(), port_); } QuicIpAddress QuicSocketAddress::host() const { return host_; } uint16_t QuicSocketAddress::port() const { return port_; } sockaddr_storage QuicSocketAddress::generic_address() const { union { sockaddr_storage storage; sockaddr_in v4; sockaddr_in6 v6; } result; memset(&result.storage, 0, sizeof(result.storage)); switch (host_.address_family()) { case IpAddressFamily::IP_V4: result.v4.sin_family = AF_INET; result.v4.sin_addr = host_.GetIPv4(); result.v4.sin_port = htons(port_); break; case IpAddressFamily::IP_V6: result.v6.sin6_family = AF_INET6; result.v6.sin6_addr = host_.GetIPv6(); result.v6.sin6_port = htons(port_); break; default: result.storage.ss_family = AF_UNSPEC; break; } return result.storage; } uint32_t QuicSocketAddress::Hash() const { uint32_t value = 0; value ^= HashIP(host_); value ^= port_ | (port_ << 16); return value; } }
#include "quiche/quic/platform/api/quic_socket_address.h" #include <memory> #include <sstream> #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace { TEST(QuicSocketAddress, Uninitialized) { QuicSocketAddress uninitialized; EXPECT_FALSE(uninitialized.IsInitialized()); } TEST(QuicSocketAddress, ExplicitConstruction) { QuicSocketAddress ipv4_address(QuicIpAddress::Loopback4(), 443); QuicSocketAddress ipv6_address(QuicIpAddress::Loopback6(), 443); EXPECT_TRUE(ipv4_address.IsInitialized()); EXPECT_EQ("127.0.0.1:443", ipv4_address.ToString()); EXPECT_EQ("[::1]:443", ipv6_address.ToString()); EXPECT_EQ(QuicIpAddress::Loopback4(), ipv4_address.host()); EXPECT_EQ(QuicIpAddress::Loopback6(), ipv6_address.host()); EXPECT_EQ(443, ipv4_address.port()); } TEST(QuicSocketAddress, OutputToStream) { QuicSocketAddress ipv4_address(QuicIpAddress::Loopback4(), 443); std::stringstream stream; stream << ipv4_address; EXPECT_EQ("127.0.0.1:443", stream.str()); } TEST(QuicSocketAddress, FromSockaddrIPv4) { union { sockaddr_storage storage; sockaddr addr; sockaddr_in v4; } address; memset(&address, 0, sizeof(address)); address.v4.sin_family = AF_INET; address.v4.sin_addr = QuicIpAddress::Loopback4().GetIPv4(); address.v4.sin_port = htons(443); EXPECT_EQ("127.0.0.1:443", QuicSocketAddress(&address.addr, sizeof(address.v4)).ToString()); EXPECT_EQ("127.0.0.1:443", QuicSocketAddress(address.storage).ToString()); } TEST(QuicSocketAddress, FromSockaddrIPv6) { union { sockaddr_storage storage; sockaddr addr; sockaddr_in6 v6; } address; memset(&address, 0, sizeof(address)); address.v6.sin6_family = AF_INET6; address.v6.sin6_addr = QuicIpAddress::Loopback6().GetIPv6(); address.v6.sin6_port = htons(443); EXPECT_EQ("[::1]:443", QuicSocketAddress(&address.addr, sizeof(address.v6)).ToString()); EXPECT_EQ("[::1]:443", QuicSocketAddress(address.storage).ToString()); } TEST(QuicSocketAddres, ToSockaddrIPv4) { union { sockaddr_storage storage; sockaddr_in v4; } address; address.storage = QuicSocketAddress(QuicIpAddress::Loopback4(), 443).generic_address(); ASSERT_EQ(AF_INET, address.v4.sin_family); EXPECT_EQ(QuicIpAddress::Loopback4(), QuicIpAddress(address.v4.sin_addr)); EXPECT_EQ(htons(443), address.v4.sin_port); } TEST(QuicSocketAddress, Normalize) { QuicIpAddress dual_stacked; ASSERT_TRUE(dual_stacked.FromString("::ffff:127.0.0.1")); ASSERT_TRUE(dual_stacked.IsIPv6()); QuicSocketAddress not_normalized(dual_stacked, 443); QuicSocketAddress normalized = not_normalized.Normalized(); EXPECT_EQ("[::ffff:127.0.0.1]:443", not_normalized.ToString()); EXPECT_EQ("127.0.0.1:443", normalized.ToString()); } #if defined(__linux__) && !defined(ANDROID) #include <errno.h> #include <sys/socket.h> #include <sys/types.h> TEST(QuicSocketAddress, FromSocket) { int fd; QuicSocketAddress address; bool bound = false; for (int port = 50000; port < 50400; port++) { fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP); ASSERT_GT(fd, 0); address = QuicSocketAddress(QuicIpAddress::Loopback6(), port); sockaddr_storage raw_address = address.generic_address(); int bind_result = bind(fd, reinterpret_cast<const sockaddr*>(&raw_address), sizeof(sockaddr_in6)); if (bind_result < 0 && errno == EADDRINUSE) { close(fd); continue; } ASSERT_EQ(0, bind_result); bound = true; break; } ASSERT_TRUE(bound); QuicSocketAddress real_address; ASSERT_EQ(0, real_address.FromSocket(fd)); ASSERT_TRUE(real_address.IsInitialized()); EXPECT_EQ(real_address, address); close(fd); } #endif } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/platform/api/quic_socket_address.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/platform/api/quic_socket_address_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
a89d6cb3-79a8-4858-8019-c96a1d6c109d
cpp
google/quiche
quic_libevent
quiche/quic/bindings/quic_libevent.cc
quiche/quic/bindings/quic_libevent_test.cc
#include "quiche/quic/bindings/quic_libevent.h" #include <memory> #include <utility> #include "absl/time/time.h" #include "event2/event.h" #include "event2/event_struct.h" #include "event2/thread.h" #include "quiche/quic/core/io/quic_event_loop.h" #include "quiche/quic/core/quic_alarm.h" #include "quiche/quic/core/quic_clock.h" #include "quiche/quic/core/quic_default_clock.h" #include "quiche/quic/core/quic_time.h" namespace quic { using LibeventEventMask = short; QuicSocketEventMask LibeventEventMaskToQuicEvents(int events) { return ((events & EV_READ) ? kSocketEventReadable : 0) | ((events & EV_WRITE) ? kSocketEventWritable : 0); } LibeventEventMask QuicEventsToLibeventEventMask(QuicSocketEventMask events) { return ((events & kSocketEventReadable) ? EV_READ : 0) | ((events & kSocketEventWritable) ? EV_WRITE : 0); } class LibeventAlarm : public QuicAlarm { public: LibeventAlarm(LibeventQuicEventLoop* loop, QuicArenaScopedPtr<QuicAlarm::Delegate> delegate) : QuicAlarm(std::move(delegate)), clock_(loop->clock()) { event_.reset(evtimer_new( loop->base(), [](evutil_socket_t, LibeventEventMask, void* arg) { LibeventAlarm* self = reinterpret_cast<LibeventAlarm*>(arg); self->Fire(); }, this)); } protected: void SetImpl() override { absl::Duration timeout = absl::Microseconds((deadline() - clock_->Now()).ToMicroseconds()); timeval unix_time = absl::ToTimeval(timeout); event_add(event_.get(), &unix_time); } void CancelImpl() override { event_del(event_.get()); } private: std::unique_ptr<event, LibeventEventDeleter> event_; QuicClock* clock_; }; LibeventQuicEventLoop::LibeventQuicEventLoop(event_base* base, QuicClock* clock) : base_(base), edge_triggered_(event_base_get_features(base) & EV_FEATURE_ET), clock_(clock), artifical_event_timer_(evtimer_new( base_, [](evutil_socket_t, LibeventEventMask, void* arg) { auto* self = reinterpret_cast<LibeventQuicEventLoop*>(arg); self->ActivateArtificialEvents(); }, this)) { QUICHE_CHECK_LE(sizeof(event), event_get_struct_event_size()) << "libevent ABI mismatch: sizeof(event) is bigger than the one QUICHE " "has been compiled with"; } LibeventQuicEventLoop::~LibeventQuicEventLoop() { event_del(artifical_event_timer_.get()); } bool LibeventQuicEventLoop::RegisterSocket(QuicUdpSocketFd fd, QuicSocketEventMask events, QuicSocketEventListener* listener) { auto [it, success] = registration_map_.try_emplace(fd, this, fd, events, listener); return success; } bool LibeventQuicEventLoop::UnregisterSocket(QuicUdpSocketFd fd) { fds_with_artifical_events_.erase(fd); return registration_map_.erase(fd); } bool LibeventQuicEventLoop::RearmSocket(QuicUdpSocketFd fd, QuicSocketEventMask events) { if (edge_triggered_) { QUICHE_BUG(LibeventQuicEventLoop_RearmSocket_called_on_ET) << "RearmSocket() called on an edge-triggered event loop"; return false; } auto it = registration_map_.find(fd); if (it == registration_map_.end()) { return false; } it->second.Rearm(events); return true; } bool LibeventQuicEventLoop::ArtificiallyNotifyEvent( QuicUdpSocketFd fd, QuicSocketEventMask events) { auto it = registration_map_.find(fd); if (it == registration_map_.end()) { return false; } it->second.RecordArtificalEvents(events); fds_with_artifical_events_.insert(fd); if (!evtimer_pending(artifical_event_timer_.get(), nullptr)) { struct timeval tv = {0, 0}; evtimer_add(artifical_event_timer_.get(), &tv); } return true; } void LibeventQuicEventLoop::ActivateArtificialEvents() { absl::flat_hash_set<QuicUdpSocketFd> fds_with_artifical_events; { using std::swap; swap(fds_with_artifical_events_, fds_with_artifical_events); } for (QuicUdpSocketFd fd : fds_with_artifical_events) { auto it = registration_map_.find(fd); if (it == registration_map_.end()) { continue; } it->second.MaybeNotifyArtificalEvents(); } } void LibeventQuicEventLoop::RunEventLoopOnce(QuicTime::Delta default_timeout) { timeval timeout = absl::ToTimeval(absl::Microseconds(default_timeout.ToMicroseconds())); event_base_loopexit(base_, &timeout); event_base_loop(base_, EVLOOP_ONCE); } void LibeventQuicEventLoop::WakeUp() { timeval timeout = absl::ToTimeval(absl::ZeroDuration()); event_base_loopexit(base_, &timeout); } LibeventQuicEventLoop::Registration::Registration( LibeventQuicEventLoop* loop, QuicUdpSocketFd fd, QuicSocketEventMask events, QuicSocketEventListener* listener) : loop_(loop), listener_(listener) { event_callback_fn callback = [](evutil_socket_t fd, LibeventEventMask events, void* arg) { auto* self = reinterpret_cast<LibeventQuicEventLoop::Registration*>(arg); self->listener_->OnSocketEvent(self->loop_, fd, LibeventEventMaskToQuicEvents(events)); }; if (loop_->SupportsEdgeTriggered()) { LibeventEventMask mask = QuicEventsToLibeventEventMask(events) | EV_PERSIST | EV_ET; event_assign(&both_events_, loop_->base(), fd, mask, callback, this); event_add(&both_events_, nullptr); } else { event_assign(&read_event_, loop_->base(), fd, EV_READ, callback, this); event_assign(&write_event_, loop_->base(), fd, EV_WRITE, callback, this); Rearm(events); } } LibeventQuicEventLoop::Registration::~Registration() { if (loop_->SupportsEdgeTriggered()) { event_del(&both_events_); } else { event_del(&read_event_); event_del(&write_event_); } } void LibeventQuicEventLoop::Registration::RecordArtificalEvents( QuicSocketEventMask events) { artificial_events_ |= events; } void LibeventQuicEventLoop::Registration::MaybeNotifyArtificalEvents() { if (artificial_events_ == 0) { return; } QuicSocketEventMask events = artificial_events_; artificial_events_ = 0; if (loop_->SupportsEdgeTriggered()) { event_active(&both_events_, QuicEventsToLibeventEventMask(events), 0); return; } if (events & kSocketEventReadable) { event_active(&read_event_, EV_READ, 0); } if (events & kSocketEventWritable) { event_active(&write_event_, EV_WRITE, 0); } } void LibeventQuicEventLoop::Registration::Rearm(QuicSocketEventMask events) { QUICHE_DCHECK(!loop_->SupportsEdgeTriggered()); if (events & kSocketEventReadable) { event_add(&read_event_, nullptr); } if (events & kSocketEventWritable) { event_add(&write_event_, nullptr); } } QuicAlarm* LibeventQuicEventLoop::AlarmFactory::CreateAlarm( QuicAlarm::Delegate* delegate) { return new LibeventAlarm(loop_, QuicArenaScopedPtr<QuicAlarm::Delegate>(delegate)); } QuicArenaScopedPtr<QuicAlarm> LibeventQuicEventLoop::AlarmFactory::CreateAlarm( QuicArenaScopedPtr<QuicAlarm::Delegate> delegate, QuicConnectionArena* arena) { if (arena != nullptr) { return arena->New<LibeventAlarm>(loop_, std::move(delegate)); } return QuicArenaScopedPtr<QuicAlarm>( new LibeventAlarm(loop_, std::move(delegate))); } QuicLibeventEventLoopFactory::QuicLibeventEventLoopFactory( bool force_level_triggered) : force_level_triggered_(force_level_triggered) { std::unique_ptr<QuicEventLoop> event_loop = Create(QuicDefaultClock::Get()); name_ = absl::StrFormat( "libevent(%s)", event_base_get_method( static_cast<LibeventQuicEventLoopWithOwnership*>(event_loop.get()) ->base())); } struct LibeventConfigDeleter { void operator()(event_config* config) { event_config_free(config); } }; std::unique_ptr<LibeventQuicEventLoopWithOwnership> LibeventQuicEventLoopWithOwnership::Create(QuicClock* clock, bool force_level_triggered) { static int threads_initialized = []() { #ifdef _WIN32 return evthread_use_windows_threads(); #else return evthread_use_pthreads(); #endif }(); QUICHE_DCHECK_EQ(threads_initialized, 0); std::unique_ptr<event_config, LibeventConfigDeleter> config( event_config_new()); if (force_level_triggered) { event_config_avoid_method(config.get(), "epoll"); event_config_avoid_method(config.get(), "kqueue"); } return std::make_unique<LibeventQuicEventLoopWithOwnership>( event_base_new_with_config(config.get()), clock); } }
#include "quiche/quic/bindings/quic_libevent.h" #include <atomic> #include <memory> #include "absl/memory/memory.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "quiche/quic/core/quic_alarm.h" #include "quiche/quic/core/quic_default_clock.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/platform/api/quic_thread.h" namespace quic::test { namespace { class FailureAlarmDelegate : public QuicAlarm::Delegate { public: QuicConnectionContext* GetConnectionContext() override { return nullptr; } void OnAlarm() override { ADD_FAILURE() << "Test timed out"; } }; class LoopBreakThread : public QuicThread { public: LoopBreakThread(LibeventQuicEventLoop* loop) : QuicThread("LoopBreakThread"), loop_(loop) {} void Run() override { absl::SleepFor(absl::Milliseconds(250)); loop_broken_.store(true); loop_->WakeUp(); } std::atomic<int>& loop_broken() { return loop_broken_; } private: LibeventQuicEventLoop* loop_; std::atomic<int> loop_broken_ = 0; }; TEST(QuicLibeventTest, WakeUpFromAnotherThread) { QuicClock* clock = QuicDefaultClock::Get(); auto event_loop_owned = QuicLibeventEventLoopFactory::Get()->Create(clock); LibeventQuicEventLoop* event_loop = static_cast<LibeventQuicEventLoop*>(event_loop_owned.get()); std::unique_ptr<QuicAlarmFactory> alarm_factory = event_loop->CreateAlarmFactory(); std::unique_ptr<QuicAlarm> timeout_alarm = absl::WrapUnique(alarm_factory->CreateAlarm(new FailureAlarmDelegate())); const QuicTime kTimeoutAt = clock->Now() + QuicTime::Delta::FromSeconds(10); timeout_alarm->Set(kTimeoutAt); LoopBreakThread thread(event_loop); thread.Start(); event_loop->RunEventLoopOnce(QuicTime::Delta::FromSeconds(5 * 60)); EXPECT_TRUE(thread.loop_broken().load()); thread.Join(); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/bindings/quic_libevent.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/bindings/quic_libevent_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
af8f681c-9589-46e6-9745-f5b0612bf4d2
cpp
google/quiche
moqt_messages
quiche/quic/moqt/moqt_messages.cc
quiche/quic/moqt/moqt_messages_test.cc
#include "quiche/quic/moqt/moqt_messages.h" #include <cstdint> #include <string> #include <vector> #include "absl/algorithm/container.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" namespace moqt { MoqtObjectStatus IntegerToObjectStatus(uint64_t integer) { if (integer >= static_cast<uint64_t>(MoqtObjectStatus::kInvalidObjectStatus)) { return MoqtObjectStatus::kInvalidObjectStatus; } return static_cast<MoqtObjectStatus>(integer); } MoqtFilterType GetFilterType(const MoqtSubscribe& message) { if (!message.end_group.has_value() && message.end_object.has_value()) { return MoqtFilterType::kNone; } bool has_start = message.start_group.has_value() && message.start_object.has_value(); if (message.end_group.has_value()) { if (has_start) { if (*message.end_group < *message.start_group) { return MoqtFilterType::kNone; } else if (*message.end_group == *message.start_group && *message.end_object <= *message.start_object) { if (*message.end_object < *message.start_object) { return MoqtFilterType::kNone; } else if (*message.end_object == *message.start_object) { return MoqtFilterType::kAbsoluteStart; } } return MoqtFilterType::kAbsoluteRange; } } else { if (has_start) { return MoqtFilterType::kAbsoluteStart; } else if (!message.start_group.has_value()) { if (message.start_object.has_value()) { if (message.start_object.value() == 0) { return MoqtFilterType::kLatestGroup; } } else { return MoqtFilterType::kLatestObject; } } } return MoqtFilterType::kNone; } std::string MoqtMessageTypeToString(const MoqtMessageType message_type) { switch (message_type) { case MoqtMessageType::kClientSetup: return "CLIENT_SETUP"; case MoqtMessageType::kServerSetup: return "SERVER_SETUP"; case MoqtMessageType::kSubscribe: return "SUBSCRIBE_REQUEST"; case MoqtMessageType::kSubscribeOk: return "SUBSCRIBE_OK"; case MoqtMessageType::kSubscribeError: return "SUBSCRIBE_ERROR"; case MoqtMessageType::kUnsubscribe: return "UNSUBSCRIBE"; case MoqtMessageType::kSubscribeDone: return "SUBSCRIBE_DONE"; case MoqtMessageType::kSubscribeUpdate: return "SUBSCRIBE_UPDATE"; case MoqtMessageType::kAnnounceCancel: return "ANNOUNCE_CANCEL"; case MoqtMessageType::kTrackStatusRequest: return "TRACK_STATUS_REQUEST"; case MoqtMessageType::kTrackStatus: return "TRACK_STATUS"; case MoqtMessageType::kAnnounce: return "ANNOUNCE"; case MoqtMessageType::kAnnounceOk: return "ANNOUNCE_OK"; case MoqtMessageType::kAnnounceError: return "ANNOUNCE_ERROR"; case MoqtMessageType::kUnannounce: return "UNANNOUNCE"; case MoqtMessageType::kGoAway: return "GOAWAY"; case MoqtMessageType::kSubscribeNamespace: return "SUBSCRIBE_NAMESPACE"; case MoqtMessageType::kSubscribeNamespaceOk: return "SUBSCRIBE_NAMESPACE_OK"; case MoqtMessageType::kSubscribeNamespaceError: return "SUBSCRIBE_NAMESPACE_ERROR"; case MoqtMessageType::kUnsubscribeNamespace: return "UNSUBSCRIBE_NAMESPACE"; case MoqtMessageType::kMaxSubscribeId: return "MAX_SUBSCRIBE_ID"; case MoqtMessageType::kObjectAck: return "OBJECT_ACK"; } return "Unknown message " + std::to_string(static_cast<int>(message_type)); } std::string MoqtDataStreamTypeToString(MoqtDataStreamType type) { switch (type) { case MoqtDataStreamType::kObjectDatagram: return "OBJECT_PREFER_DATAGRAM"; case MoqtDataStreamType::kStreamHeaderTrack: return "STREAM_HEADER_TRACK"; case MoqtDataStreamType::kStreamHeaderSubgroup: return "STREAM_HEADER_SUBGROUP"; case MoqtDataStreamType::kPadding: return "PADDING"; } return "Unknown stream type " + absl::StrCat(static_cast<int>(type)); } std::string MoqtForwardingPreferenceToString( MoqtForwardingPreference preference) { switch (preference) { case MoqtForwardingPreference::kDatagram: return "DATAGRAM"; case MoqtForwardingPreference::kTrack: return "TRACK"; case MoqtForwardingPreference::kSubgroup: return "SUBGROUP"; } QUIC_BUG(quic_bug_bad_moqt_message_type_01) << "Unknown preference " << std::to_string(static_cast<int>(preference)); return "Unknown preference " + std::to_string(static_cast<int>(preference)); } MoqtForwardingPreference GetForwardingPreference(MoqtDataStreamType type) { switch (type) { case MoqtDataStreamType::kObjectDatagram: return MoqtForwardingPreference::kDatagram; case MoqtDataStreamType::kStreamHeaderTrack: return MoqtForwardingPreference::kTrack; case MoqtDataStreamType::kStreamHeaderSubgroup: return MoqtForwardingPreference::kSubgroup; default: break; } QUIC_BUG(quic_bug_bad_moqt_message_type_02) << "Message type does not indicate forwarding preference"; return MoqtForwardingPreference::kSubgroup; }; MoqtDataStreamType GetMessageTypeForForwardingPreference( MoqtForwardingPreference preference) { switch (preference) { case MoqtForwardingPreference::kDatagram: return MoqtDataStreamType::kObjectDatagram; case MoqtForwardingPreference::kTrack: return MoqtDataStreamType::kStreamHeaderTrack; case MoqtForwardingPreference::kSubgroup: return MoqtDataStreamType::kStreamHeaderSubgroup; } QUIC_BUG(quic_bug_bad_moqt_message_type_03) << "Forwarding preference does not indicate message type"; return MoqtDataStreamType::kStreamHeaderSubgroup; } std::string FullTrackName::ToString() const { std::vector<std::string> bits; bits.reserve(tuple_.size()); for (absl::string_view raw_bit : tuple_) { bits.push_back(absl::StrCat("\"", absl::CHexEscape(raw_bit), "\"")); } return absl::StrCat("{", absl::StrJoin(bits, ", "), "}"); } bool FullTrackName::operator==(const FullTrackName& other) const { if (tuple_.size() != other.tuple_.size()) { return false; } return absl::c_equal(tuple_, other.tuple_); } bool FullTrackName::operator<(const FullTrackName& other) const { return absl::c_lexicographical_compare(tuple_, other.tuple_); } FullTrackName::FullTrackName(absl::Span<const absl::string_view> elements) : tuple_(elements.begin(), elements.end()) {} }
#include "quiche/quic/moqt/moqt_messages.h" #include <vector> #include "absl/hash/hash.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_test.h" namespace moqt::test { namespace { TEST(MoqtMessagesTest, FullTrackNameConstructors) { FullTrackName name1({"foo", "bar"}); std::vector<absl::string_view> list = {"foo", "bar"}; FullTrackName name2(list); EXPECT_EQ(name1, name2); EXPECT_EQ(absl::HashOf(name1), absl::HashOf(name2)); } TEST(MoqtMessagesTest, FullTrackNameOrder) { FullTrackName name1({"a", "b"}); FullTrackName name2({"a", "b", "c"}); FullTrackName name3({"b", "a"}); EXPECT_LT(name1, name2); EXPECT_LT(name2, name3); EXPECT_LT(name1, name3); } TEST(MoqtMessagesTest, FullTrackNameInNamespace) { FullTrackName name1({"a", "b"}); FullTrackName name2({"a", "b", "c"}); FullTrackName name3({"d", "b"}); EXPECT_TRUE(name2.InNamespace(name1)); EXPECT_FALSE(name1.InNamespace(name2)); EXPECT_TRUE(name1.InNamespace(name1)); EXPECT_FALSE(name2.InNamespace(name3)); } TEST(MoqtMessagesTest, FullTrackNameToString) { FullTrackName name1({"a", "b"}); EXPECT_EQ(name1.ToString(), R"({"a", "b"})"); FullTrackName name2({"\xff", "\x61"}); EXPECT_EQ(name2.ToString(), R"({"\xff", "a"})"); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/moqt/moqt_messages.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/moqt/moqt_messages_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
8ff0df2a-07c8-4646-97be-0b6b24b801e6
cpp
google/quiche
moqt_outgoing_queue
quiche/quic/moqt/moqt_outgoing_queue.cc
quiche/quic/moqt/moqt_outgoing_queue_test.cc
#include "quiche/quic/moqt/moqt_outgoing_queue.h" #include <memory> #include <optional> #include <utility> #include <vector> #include "absl/status/statusor.h" #include "quiche/quic/moqt/moqt_cached_object.h" #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/quic/moqt/moqt_publisher.h" #include "quiche/quic/moqt/moqt_subscribe_windows.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_mem_slice.h" namespace moqt { void MoqtOutgoingQueue::AddObject(quiche::QuicheMemSlice payload, bool key) { if (queue_.empty() && !key) { QUICHE_BUG(MoqtOutgoingQueue_AddObject_first_object_not_key) << "The first object ever added to the queue must have the \"key\" " "flag."; return; } if (key) { if (!queue_.empty()) { AddRawObject(MoqtObjectStatus::kEndOfGroup, quiche::QuicheMemSlice()); } if (queue_.size() == kMaxQueuedGroups) { queue_.erase(queue_.begin()); } queue_.emplace_back(); ++current_group_id_; } AddRawObject(MoqtObjectStatus::kNormal, std::move(payload)); } void MoqtOutgoingQueue::AddRawObject(MoqtObjectStatus status, quiche::QuicheMemSlice payload) { FullSequence sequence{current_group_id_, queue_.back().size()}; queue_.back().push_back(CachedObject{ sequence, status, std::make_shared<quiche::QuicheMemSlice>(std::move(payload))}); for (MoqtObjectListener* listener : listeners_) { listener->OnNewObjectAvailable(sequence); } } std::optional<PublishedObject> MoqtOutgoingQueue::GetCachedObject( FullSequence sequence) const { if (sequence.group < first_group_in_queue()) { return PublishedObject{FullSequence{sequence.group, sequence.object}, MoqtObjectStatus::kGroupDoesNotExist, quiche::QuicheMemSlice()}; } if (sequence.group > current_group_id_) { return std::nullopt; } const std::vector<CachedObject>& group = queue_[sequence.group - first_group_in_queue()]; if (sequence.object >= group.size()) { if (sequence.group == current_group_id_) { return std::nullopt; } return PublishedObject{FullSequence{sequence.group, sequence.object}, MoqtObjectStatus::kObjectDoesNotExist, quiche::QuicheMemSlice()}; } QUICHE_DCHECK(sequence == group[sequence.object].sequence); return CachedObjectToPublishedObject(group[sequence.object]); } std::vector<FullSequence> MoqtOutgoingQueue::GetCachedObjectsInRange( FullSequence start, FullSequence end) const { std::vector<FullSequence> sequences; SubscribeWindow window(start, end); for (const Group& group : queue_) { for (const CachedObject& object : group) { if (window.InWindow(object.sequence)) { sequences.push_back(object.sequence); } } } return sequences; } absl::StatusOr<MoqtTrackStatusCode> MoqtOutgoingQueue::GetTrackStatus() const { if (queue_.empty()) { return MoqtTrackStatusCode::kNotYetBegun; } return MoqtTrackStatusCode::kInProgress; } FullSequence MoqtOutgoingQueue::GetLargestSequence() const { if (queue_.empty()) { QUICHE_BUG(MoqtOutgoingQueue_GetLargestSequence_not_begun) << "Calling GetLargestSequence() on a track that hasn't begun"; return FullSequence{0, 0}; } return FullSequence{current_group_id_, queue_.back().size() - 1}; } }
#include "quiche/quic/moqt/moqt_outgoing_queue.h" #include <cstdint> #include <optional> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/quic/moqt/moqt_publisher.h" #include "quiche/quic/moqt/moqt_subscribe_windows.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/platform/api/quiche_expect_bug.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" namespace moqt { namespace { using ::quic::test::MemSliceFromString; using ::testing::AnyOf; class TestMoqtOutgoingQueue : public MoqtOutgoingQueue, public MoqtObjectListener { public: TestMoqtOutgoingQueue() : MoqtOutgoingQueue(FullTrackName{"test", "track"}, MoqtForwardingPreference::kSubgroup) { AddObjectListener(this); } void OnNewObjectAvailable(FullSequence sequence) override { std::optional<PublishedObject> object = GetCachedObject(sequence); QUICHE_CHECK(object.has_value()); ASSERT_THAT(object->status, AnyOf(MoqtObjectStatus::kNormal, MoqtObjectStatus::kEndOfGroup)); if (object->status == MoqtObjectStatus::kNormal) { PublishObject(object->sequence.group, object->sequence.object, object->payload.AsStringView()); } else { CloseStreamForGroup(object->sequence.group); } } void CallSubscribeForPast(const SubscribeWindow& window) { std::vector<FullSequence> objects = GetCachedObjectsInRange(FullSequence(0, 0), GetLargestSequence()); for (FullSequence object : objects) { if (window.InWindow(object)) { OnNewObjectAvailable(object); } } } MOCK_METHOD(void, CloseStreamForGroup, (uint64_t group_id), ()); MOCK_METHOD(void, PublishObject, (uint64_t group_id, uint64_t object_id, absl::string_view payload), ()); }; TEST(MoqtOutgoingQueue, FirstObjectNotKeyframe) { TestMoqtOutgoingQueue queue; EXPECT_QUICHE_BUG(queue.AddObject(MemSliceFromString("a"), false), "The first object"); } TEST(MoqtOutgoingQueue, SingleGroup) { TestMoqtOutgoingQueue queue; { testing::InSequence seq; EXPECT_CALL(queue, PublishObject(0, 0, "a")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, PublishObject(0, 2, "c")); } queue.AddObject(MemSliceFromString("a"), true); queue.AddObject(MemSliceFromString("b"), false); queue.AddObject(MemSliceFromString("c"), false); } TEST(MoqtOutgoingQueue, SingleGroupPastSubscribeFromZero) { TestMoqtOutgoingQueue queue; { testing::InSequence seq; EXPECT_CALL(queue, PublishObject(0, 0, "a")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, PublishObject(0, 2, "c")); EXPECT_CALL(queue, PublishObject(0, 0, "a")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, PublishObject(0, 2, "c")); } queue.AddObject(MemSliceFromString("a"), true); queue.AddObject(MemSliceFromString("b"), false); queue.AddObject(MemSliceFromString("c"), false); queue.CallSubscribeForPast(SubscribeWindow(0, 0)); } TEST(MoqtOutgoingQueue, SingleGroupPastSubscribeFromMidGroup) { TestMoqtOutgoingQueue queue; { testing::InSequence seq; EXPECT_CALL(queue, PublishObject(0, 0, "a")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, PublishObject(0, 2, "c")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, PublishObject(0, 2, "c")); } queue.AddObject(MemSliceFromString("a"), true); queue.AddObject(MemSliceFromString("b"), false); queue.AddObject(MemSliceFromString("c"), false); queue.CallSubscribeForPast(SubscribeWindow(0, 1)); } TEST(MoqtOutgoingQueue, TwoGroups) { TestMoqtOutgoingQueue queue; { testing::InSequence seq; EXPECT_CALL(queue, PublishObject(0, 0, "a")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, PublishObject(0, 2, "c")); EXPECT_CALL(queue, CloseStreamForGroup(0)); EXPECT_CALL(queue, PublishObject(1, 0, "d")); EXPECT_CALL(queue, PublishObject(1, 1, "e")); EXPECT_CALL(queue, PublishObject(1, 2, "f")); } queue.AddObject(MemSliceFromString("a"), true); queue.AddObject(MemSliceFromString("b"), false); queue.AddObject(MemSliceFromString("c"), false); queue.AddObject(MemSliceFromString("d"), true); queue.AddObject(MemSliceFromString("e"), false); queue.AddObject(MemSliceFromString("f"), false); } TEST(MoqtOutgoingQueue, TwoGroupsPastSubscribe) { TestMoqtOutgoingQueue queue; { testing::InSequence seq; EXPECT_CALL(queue, PublishObject(0, 0, "a")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, PublishObject(0, 2, "c")); EXPECT_CALL(queue, CloseStreamForGroup(0)); EXPECT_CALL(queue, PublishObject(1, 0, "d")); EXPECT_CALL(queue, PublishObject(1, 1, "e")); EXPECT_CALL(queue, PublishObject(1, 2, "f")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, PublishObject(0, 2, "c")); EXPECT_CALL(queue, CloseStreamForGroup(0)); EXPECT_CALL(queue, PublishObject(1, 0, "d")); EXPECT_CALL(queue, PublishObject(1, 1, "e")); EXPECT_CALL(queue, PublishObject(1, 2, "f")); } queue.AddObject(MemSliceFromString("a"), true); queue.AddObject(MemSliceFromString("b"), false); queue.AddObject(MemSliceFromString("c"), false); queue.AddObject(MemSliceFromString("d"), true); queue.AddObject(MemSliceFromString("e"), false); queue.AddObject(MemSliceFromString("f"), false); queue.CallSubscribeForPast(SubscribeWindow(0, 1)); } TEST(MoqtOutgoingQueue, FiveGroups) { TestMoqtOutgoingQueue queue; { testing::InSequence seq; EXPECT_CALL(queue, PublishObject(0, 0, "a")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, CloseStreamForGroup(0)); EXPECT_CALL(queue, PublishObject(1, 0, "c")); EXPECT_CALL(queue, PublishObject(1, 1, "d")); EXPECT_CALL(queue, CloseStreamForGroup(1)); EXPECT_CALL(queue, PublishObject(2, 0, "e")); EXPECT_CALL(queue, PublishObject(2, 1, "f")); EXPECT_CALL(queue, CloseStreamForGroup(2)); EXPECT_CALL(queue, PublishObject(3, 0, "g")); EXPECT_CALL(queue, PublishObject(3, 1, "h")); EXPECT_CALL(queue, CloseStreamForGroup(3)); EXPECT_CALL(queue, PublishObject(4, 0, "i")); EXPECT_CALL(queue, PublishObject(4, 1, "j")); } queue.AddObject(MemSliceFromString("a"), true); queue.AddObject(MemSliceFromString("b"), false); queue.AddObject(MemSliceFromString("c"), true); queue.AddObject(MemSliceFromString("d"), false); queue.AddObject(MemSliceFromString("e"), true); queue.AddObject(MemSliceFromString("f"), false); queue.AddObject(MemSliceFromString("g"), true); queue.AddObject(MemSliceFromString("h"), false); queue.AddObject(MemSliceFromString("i"), true); queue.AddObject(MemSliceFromString("j"), false); } TEST(MoqtOutgoingQueue, FiveGroupsPastSubscribe) { TestMoqtOutgoingQueue queue; { testing::InSequence seq; EXPECT_CALL(queue, PublishObject(0, 0, "a")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, CloseStreamForGroup(0)); EXPECT_CALL(queue, PublishObject(1, 0, "c")); EXPECT_CALL(queue, PublishObject(1, 1, "d")); EXPECT_CALL(queue, CloseStreamForGroup(1)); EXPECT_CALL(queue, PublishObject(2, 0, "e")); EXPECT_CALL(queue, PublishObject(2, 1, "f")); EXPECT_CALL(queue, CloseStreamForGroup(2)); EXPECT_CALL(queue, PublishObject(3, 0, "g")); EXPECT_CALL(queue, PublishObject(3, 1, "h")); EXPECT_CALL(queue, CloseStreamForGroup(3)); EXPECT_CALL(queue, PublishObject(4, 0, "i")); EXPECT_CALL(queue, PublishObject(4, 1, "j")); EXPECT_CALL(queue, PublishObject(2, 0, "e")); EXPECT_CALL(queue, PublishObject(2, 1, "f")); EXPECT_CALL(queue, CloseStreamForGroup(2)); EXPECT_CALL(queue, PublishObject(3, 0, "g")); EXPECT_CALL(queue, PublishObject(3, 1, "h")); EXPECT_CALL(queue, CloseStreamForGroup(3)); EXPECT_CALL(queue, PublishObject(4, 0, "i")); EXPECT_CALL(queue, PublishObject(4, 1, "j")); } queue.AddObject(MemSliceFromString("a"), true); queue.AddObject(MemSliceFromString("b"), false); queue.AddObject(MemSliceFromString("c"), true); queue.AddObject(MemSliceFromString("d"), false); queue.AddObject(MemSliceFromString("e"), true); queue.AddObject(MemSliceFromString("f"), false); queue.AddObject(MemSliceFromString("g"), true); queue.AddObject(MemSliceFromString("h"), false); queue.AddObject(MemSliceFromString("i"), true); queue.AddObject(MemSliceFromString("j"), false); queue.CallSubscribeForPast(SubscribeWindow(0, 0)); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/moqt/moqt_outgoing_queue.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/moqt/moqt_outgoing_queue_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
5da530f5-75a9-4bfc-ad08-cd8396413f6e
cpp
google/quiche
moqt_session
quiche/quic/moqt/moqt_session.cc
quiche/quic/moqt/moqt_session_test.cc
#include "quiche/quic/moqt/moqt_session.h" #include <algorithm> #include <array> #include <cstdint> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/algorithm/container.h" #include "absl/container/btree_map.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/container/node_hash_map.h" #include "absl/functional/bind_front.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/moqt/moqt_framer.h" #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/quic/moqt/moqt_parser.h" #include "quiche/quic/moqt/moqt_priority.h" #include "quiche/quic/moqt/moqt_publisher.h" #include "quiche/quic/moqt/moqt_subscribe_windows.h" #include "quiche/quic/moqt/moqt_track.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_buffer_allocator.h" #include "quiche/common/quiche_stream.h" #include "quiche/common/simple_buffer_allocator.h" #include "quiche/web_transport/web_transport.h" #define ENDPOINT \ (perspective() == Perspective::IS_SERVER ? "MoQT Server: " : "MoQT Client: ") namespace moqt { namespace { using ::quic::Perspective; constexpr MoqtPriority kDefaultSubscriberPriority = 0x80; constexpr webtransport::SendGroupId kMoqtSendGroupId = 0; bool PublisherHasData(const MoqtTrackPublisher& publisher) { absl::StatusOr<MoqtTrackStatusCode> status = publisher.GetTrackStatus(); return status.ok() && DoesTrackStatusImplyHavingData(*status); } SubscribeWindow SubscribeMessageToWindow(const MoqtSubscribe& subscribe, MoqtTrackPublisher& publisher) { const FullSequence sequence = PublisherHasData(publisher) ? publisher.GetLargestSequence() : FullSequence{0, 0}; switch (GetFilterType(subscribe)) { case MoqtFilterType::kLatestGroup: return SubscribeWindow(sequence.group, 0); case MoqtFilterType::kLatestObject: return SubscribeWindow(sequence.group, sequence.object); case MoqtFilterType::kAbsoluteStart: return SubscribeWindow(*subscribe.start_group, *subscribe.start_object); case MoqtFilterType::kAbsoluteRange: return SubscribeWindow(*subscribe.start_group, *subscribe.start_object, *subscribe.end_group, *subscribe.end_object); case MoqtFilterType::kNone: QUICHE_BUG(MoqtSession_Subscription_invalid_filter_passed); return SubscribeWindow(0, 0); } } class DefaultPublisher : public MoqtPublisher { public: static DefaultPublisher* GetInstance() { static DefaultPublisher* instance = new DefaultPublisher(); return instance; } absl::StatusOr<std::shared_ptr<MoqtTrackPublisher>> GetTrack( const FullTrackName& track_name) override { return absl::NotFoundError("No tracks published"); } }; } MoqtSession::MoqtSession(webtransport::Session* session, MoqtSessionParameters parameters, MoqtSessionCallbacks callbacks) : session_(session), parameters_(parameters), callbacks_(std::move(callbacks)), framer_(quiche::SimpleBufferAllocator::Get(), parameters.using_webtrans), publisher_(DefaultPublisher::GetInstance()), local_max_subscribe_id_(parameters.max_subscribe_id), liveness_token_(std::make_shared<Empty>()) {} MoqtSession::ControlStream* MoqtSession::GetControlStream() { if (!control_stream_.has_value()) { return nullptr; } webtransport::Stream* raw_stream = session_->GetStreamById(*control_stream_); if (raw_stream == nullptr) { return nullptr; } return static_cast<ControlStream*>(raw_stream->visitor()); } void MoqtSession::SendControlMessage(quiche::QuicheBuffer message) { ControlStream* control_stream = GetControlStream(); if (control_stream == nullptr) { QUICHE_LOG(DFATAL) << "Trying to send a message on the control stream " "while it does not exist"; return; } control_stream->SendOrBufferMessage(std::move(message)); } void MoqtSession::OnSessionReady() { QUICHE_DLOG(INFO) << ENDPOINT << "Underlying session ready"; if (parameters_.perspective == Perspective::IS_SERVER) { return; } webtransport::Stream* control_stream = session_->OpenOutgoingBidirectionalStream(); if (control_stream == nullptr) { Error(MoqtError::kInternalError, "Unable to open a control stream"); return; } control_stream->SetVisitor( std::make_unique<ControlStream>(this, control_stream)); control_stream_ = control_stream->GetStreamId(); MoqtClientSetup setup = MoqtClientSetup{ .supported_versions = std::vector<MoqtVersion>{parameters_.version}, .role = MoqtRole::kPubSub, .max_subscribe_id = parameters_.max_subscribe_id, .supports_object_ack = parameters_.support_object_acks, }; if (!parameters_.using_webtrans) { setup.path = parameters_.path; } SendControlMessage(framer_.SerializeClientSetup(setup)); QUIC_DLOG(INFO) << ENDPOINT << "Send the SETUP message"; } void MoqtSession::OnSessionClosed(webtransport::SessionErrorCode, const std::string& error_message) { if (!error_.empty()) { return; } QUICHE_DLOG(INFO) << ENDPOINT << "Underlying session closed with message: " << error_message; error_ = error_message; std::move(callbacks_.session_terminated_callback)(error_message); } void MoqtSession::OnIncomingBidirectionalStreamAvailable() { while (webtransport::Stream* stream = session_->AcceptIncomingBidirectionalStream()) { if (control_stream_.has_value()) { Error(MoqtError::kProtocolViolation, "Bidirectional stream already open"); return; } stream->SetVisitor(std::make_unique<ControlStream>(this, stream)); stream->visitor()->OnCanRead(); } } void MoqtSession::OnIncomingUnidirectionalStreamAvailable() { while (webtransport::Stream* stream = session_->AcceptIncomingUnidirectionalStream()) { stream->SetVisitor(std::make_unique<IncomingDataStream>(this, stream)); stream->visitor()->OnCanRead(); } } void MoqtSession::OnDatagramReceived(absl::string_view datagram) { MoqtObject message; absl::string_view payload = ParseDatagram(datagram, message); QUICHE_DLOG(INFO) << ENDPOINT << "Received OBJECT message in datagram for subscribe_id " << message.subscribe_id << " for track alias " << message.track_alias << " with sequence " << message.group_id << ":" << message.object_id << " priority " << message.publisher_priority << " length " << payload.size(); auto [full_track_name, visitor] = TrackPropertiesFromAlias(message); if (visitor != nullptr) { visitor->OnObjectFragment(full_track_name, message.group_id, message.object_id, message.publisher_priority, message.object_status, message.forwarding_preference, payload, true); } } void MoqtSession::Error(MoqtError code, absl::string_view error) { if (!error_.empty()) { return; } QUICHE_DLOG(INFO) << ENDPOINT << "MOQT session closed with code: " << static_cast<int>(code) << " and message: " << error; error_ = std::string(error); session_->CloseSession(static_cast<uint64_t>(code), error); std::move(callbacks_.session_terminated_callback)(error); } void MoqtSession::Announce(FullTrackName track_namespace, MoqtOutgoingAnnounceCallback announce_callback) { if (peer_role_ == MoqtRole::kPublisher) { std::move(announce_callback)( track_namespace, MoqtAnnounceErrorReason{MoqtAnnounceErrorCode::kInternalError, "ANNOUNCE cannot be sent to Publisher"}); return; } if (pending_outgoing_announces_.contains(track_namespace)) { std::move(announce_callback)( track_namespace, MoqtAnnounceErrorReason{ MoqtAnnounceErrorCode::kInternalError, "ANNOUNCE message already outstanding for namespace"}); return; } MoqtAnnounce message; message.track_namespace = track_namespace; SendControlMessage(framer_.SerializeAnnounce(message)); QUIC_DLOG(INFO) << ENDPOINT << "Sent ANNOUNCE message for " << message.track_namespace; pending_outgoing_announces_[track_namespace] = std::move(announce_callback); } bool MoqtSession::SubscribeAbsolute(const FullTrackName& name, uint64_t start_group, uint64_t start_object, RemoteTrack::Visitor* visitor, MoqtSubscribeParameters parameters) { MoqtSubscribe message; message.full_track_name = name; message.subscriber_priority = kDefaultSubscriberPriority; message.group_order = std::nullopt; message.start_group = start_group; message.start_object = start_object; message.end_group = std::nullopt; message.end_object = std::nullopt; message.parameters = std::move(parameters); return Subscribe(message, visitor); } bool MoqtSession::SubscribeAbsolute(const FullTrackName& name, uint64_t start_group, uint64_t start_object, uint64_t end_group, RemoteTrack::Visitor* visitor, MoqtSubscribeParameters parameters) { if (end_group < start_group) { QUIC_DLOG(ERROR) << "Subscription end is before beginning"; return false; } MoqtSubscribe message; message.full_track_name = name; message.subscriber_priority = kDefaultSubscriberPriority; message.group_order = std::nullopt; message.start_group = start_group; message.start_object = start_object; message.end_group = end_group; message.end_object = std::nullopt; message.parameters = std::move(parameters); return Subscribe(message, visitor); } bool MoqtSession::SubscribeAbsolute(const FullTrackName& name, uint64_t start_group, uint64_t start_object, uint64_t end_group, uint64_t end_object, RemoteTrack::Visitor* visitor, MoqtSubscribeParameters parameters) { if (end_group < start_group) { QUIC_DLOG(ERROR) << "Subscription end is before beginning"; return false; } if (end_group == start_group && end_object < start_object) { QUIC_DLOG(ERROR) << "Subscription end is before beginning"; return false; } MoqtSubscribe message; message.full_track_name = name; message.subscriber_priority = kDefaultSubscriberPriority; message.group_order = std::nullopt; message.start_group = start_group; message.start_object = start_object; message.end_group = end_group; message.end_object = end_object; message.parameters = std::move(parameters); return Subscribe(message, visitor); } bool MoqtSession::SubscribeCurrentObject(const FullTrackName& name, RemoteTrack::Visitor* visitor, MoqtSubscribeParameters parameters) { MoqtSubscribe message; message.full_track_name = name; message.subscriber_priority = kDefaultSubscriberPriority; message.group_order = std::nullopt; message.start_group = std::nullopt; message.start_object = std::nullopt; message.end_group = std::nullopt; message.end_object = std::nullopt; message.parameters = std::move(parameters); return Subscribe(message, visitor); } bool MoqtSession::SubscribeCurrentGroup(const FullTrackName& name, RemoteTrack::Visitor* visitor, MoqtSubscribeParameters parameters) { MoqtSubscribe message; message.full_track_name = name; message.subscriber_priority = kDefaultSubscriberPriority; message.group_order = std::nullopt; message.start_group = std::nullopt; message.start_object = 0; message.end_group = std::nullopt; message.end_object = std::nullopt; message.parameters = std::move(parameters); return Subscribe(message, visitor); } bool MoqtSession::SubscribeIsDone(uint64_t subscribe_id, SubscribeDoneCode code, absl::string_view reason_phrase) { auto it = published_subscriptions_.find(subscribe_id); if (it == published_subscriptions_.end()) { return false; } PublishedSubscription& subscription = *it->second; std::vector<webtransport::StreamId> streams_to_reset = subscription.GetAllStreams(); MoqtSubscribeDone subscribe_done; subscribe_done.subscribe_id = subscribe_id; subscribe_done.status_code = code; subscribe_done.reason_phrase = reason_phrase; subscribe_done.final_id = subscription.largest_sent(); SendControlMessage(framer_.SerializeSubscribeDone(subscribe_done)); QUIC_DLOG(INFO) << ENDPOINT << "Sent SUBSCRIBE_DONE message for " << subscribe_id; published_subscriptions_.erase(it); for (webtransport::StreamId stream_id : streams_to_reset) { webtransport::Stream* stream = session_->GetStreamById(stream_id); if (stream == nullptr) { continue; } stream->ResetWithUserCode(kResetCodeSubscriptionGone); } return true; } bool MoqtSession::Subscribe(MoqtSubscribe& message, RemoteTrack::Visitor* visitor) { if (peer_role_ == MoqtRole::kSubscriber) { QUIC_DLOG(INFO) << ENDPOINT << "Tried to send SUBSCRIBE to subscriber peer"; return false; } if (next_subscribe_id_ > peer_max_subscribe_id_) { QUIC_DLOG(INFO) << ENDPOINT << "Tried to send SUBSCRIBE with ID " << next_subscribe_id_ << " which is greater than the maximum ID " << peer_max_subscribe_id_; return false; } message.subscribe_id = next_subscribe_id_++; auto it = remote_track_aliases_.find(message.full_track_name); if (it != remote_track_aliases_.end()) { message.track_alias = it->second; if (message.track_alias >= next_remote_track_alias_) { next_remote_track_alias_ = message.track_alias + 1; } } else { message.track_alias = next_remote_track_alias_++; } if (SupportsObjectAck() && visitor != nullptr) { visitor->OnCanAckObjects(absl::bind_front(&MoqtSession::SendObjectAck, this, message.subscribe_id)); } else { QUICHE_DLOG_IF(WARNING, message.parameters.object_ack_window.has_value()) << "Attempting to set object_ack_window on a connection that does not " "support it."; message.parameters.object_ack_window = std::nullopt; } SendControlMessage(framer_.SerializeSubscribe(message)); QUIC_DLOG(INFO) << ENDPOINT << "Sent SUBSCRIBE message for " << message.full_track_name; active_subscribes_.try_emplace(message.subscribe_id, message, visitor); return true; } webtransport::Stream* MoqtSession::OpenOrQueueDataStream( uint64_t subscription_id, FullSequence first_object) { auto it = published_subscriptions_.find(subscription_id); if (it == published_subscriptions_.end()) { return nullptr; } PublishedSubscription& subscription = *it->second; if (!session_->CanOpenNextOutgoingUnidirectionalStream()) { subscription.AddQueuedOutgoingDataStream(first_object); return nullptr; } return OpenDataStream(subscription, first_object); } webtransport::Stream* MoqtSession::OpenDataStream( PublishedSubscription& subscription, FullSequence first_object) { webtransport::Stream* new_stream = session_->OpenOutgoingUnidirectionalStream(); if (new_stream == nullptr) { QUICHE_BUG(MoqtSession_OpenDataStream_blocked) << "OpenDataStream called when creation of new streams is blocked."; return nullptr; } new_stream->SetVisitor(std::make_unique<OutgoingDataStream>( this, new_stream, subscription, first_object)); subscription.OnDataStreamCreated(new_stream->GetStreamId(), first_object); return new_stream; } void MoqtSession::OnCanCreateNewOutgoingUnidirectionalStream() { while (!subscribes_with_queued_outgoing_data_streams_.empty() && session_->CanOpenNextOutgoingUnidirectionalStream()) { auto next = subscribes_with_queued_outgoing_data_streams_.rbegin(); auto subscription = published_subscriptions_.find(next->subscription_id); if (subscription == published_subscriptions_.end()) { subscribes_with_queued_outgoing_data_streams_.erase((++next).base()); continue; } webtransport::Stream* stream = OpenDataStream(*subscription->second, subscription->second->NextQueuedOutgoingDataStream()); if (stream != nullptr) { stream->visitor()->OnCanWrite(); } } } void MoqtSession::UpdateQueuedSendOrder( uint64_t subscribe_id, std::optional<webtransport::SendOrder> old_send_order, std::optional<webtransport::SendOrder> new_send_order) { if (old_send_order == new_send_order) { return; } if (old_send_order.has_value()) { subscribes_with_queued_outgoing_data_streams_.erase( SubscriptionWithQueuedStream{*old_send_order, subscribe_id}); } if (new_send_order.has_value()) { subscribes_with_queued_outgoing_data_streams_.emplace(*new_send_order, subscribe_id); } } void MoqtSession::GrantMoreSubscribes(uint64_t num_subscribes) { local_max_subscribe_id_ += num_subscribes; MoqtMaxSubscribeId message; message.max_subscribe_id = local_max_subscribe_id_; SendControlMessage(framer_.SerializeMaxSubscribeId(message)); } std::pair<FullTrackName, RemoteTrack::Visitor*> MoqtSession::TrackPropertiesFromAlias(const MoqtObject& message) { auto it = remote_tracks_.find(message.track_alias); RemoteTrack::Visitor* visitor = nullptr; if (it == remote_tracks_.end()) { auto subscribe_it = active_subscribes_.find(message.subscribe_id); if (subscribe_it == active_subscribes_.end()) { return std::pair<FullTrackName, RemoteTrack::Visitor*>( {FullTrackName{}, nullptr}); } ActiveSubscribe& subscribe = subscribe_it->second; visitor = subscribe.visitor; subscribe.received_object = true; if (subscribe.forwarding_preference.has_value()) { if (message.forwarding_preference != *subscribe.forwarding_preference) { Error(MoqtError::kProtocolViolation, "Forwarding preference changes mid-track"); return std::pair<FullTrackName, RemoteTrack::Visitor*>( {FullTrackName{}, nullptr}); } } else { subscribe.forwarding_preference = message.forwarding_preference; } return std::make_pair(subscribe.message.full_track_name, subscribe.visitor); } RemoteTrack& track = it->second; if (!track.CheckForwardingPreference(message.forwarding_preference)) { Error(MoqtError::kProtocolViolation, "Forwarding preference changes mid-track"); return std::pair<FullTrackName, RemoteTrack::Visitor*>( {FullTrackName{}, nullptr}); } return std::make_pair(track.full_track_name(), track.visitor()); } template <class Parser> static void ForwardStreamDataToParser(webtransport::Stream& stream, Parser& parser) { bool fin = quiche::ProcessAllReadableRegions(stream, [&](absl::string_view chunk) { parser.ProcessData(chunk, false); }); if (fin) { parser.ProcessData("", true); } } MoqtSession::ControlStream::ControlStream(MoqtSession* session, webtransport::Stream* stream) : session_(session), stream_(stream), parser_(session->parameters_.using_webtrans, *this) { stream_->SetPriority( webtransport::StreamPriority{kMoqtSendGroupId, kMoqtControlStreamSendOrder}); } void MoqtSession::ControlStream::OnCanRead() { ForwardStreamDataToParser(*stream_, parser_); } void MoqtSession::ControlStream::OnCanWrite() { } void MoqtSession::ControlStream::OnResetStreamReceived( webtransport::StreamErrorCode error) { session_->Error(MoqtError::kProtocolViolation, absl::StrCat("Control stream reset with error code ", error)); } void MoqtSession::ControlStream::OnStopSendingReceived( webtransport::StreamErrorCode error) { session_->Error(MoqtError::kProtocolViolation, absl::StrCat("Control stream reset with error code ", error)); } void MoqtSession::ControlStream::OnClientSetupMessage( const MoqtClientSetup& message) { session_->control_stream_ = stream_->GetStreamId(); if (perspective() == Perspective::IS_CLIENT) { session_->Error(MoqtError::kProtocolViolation, "Received CLIENT_SETUP from server"); return; } if (absl::c_find(message.supported_versions, session_->parameters_.version) == message.supported_versions.end()) { session_->Error(MoqtError::kProtocolViolation, absl::StrCat("Version mismatch: expected 0x", absl::Hex(session_->parameters_.version))); return; } session_->peer_supports_object_ack_ = message.supports_object_ack; QUICHE_DLOG(INFO) << ENDPOINT << "Received the SETUP message"; if (session_->parameters_.perspective == Perspective::IS_SERVER) { MoqtServerSetup response; response.selected_version = session_->parameters_.version; response.role = MoqtRole::kPubSub; response.max_subscribe_id = session_->parameters_.max_subscribe_id; response.supports_object_ack = session_->parameters_.support_object_acks; SendOrBufferMessage(session_->framer_.SerializeServerSetup(response)); QUIC_DLOG(INFO) << ENDPOINT << "Sent the SETUP message"; } if (message.max_subscribe_id.has_value()) { session_->peer_max_subscribe_id_ = *message.max_subscribe_id; } std::move(session_->callbacks_.session_established_callback)(); session_->peer_role_ = *message.role; } void MoqtSession::ControlStream::OnServerSetupMessage( const MoqtServerSetup& message) { if (perspective() == Perspective::IS_SERVER) { session_->Error(MoqtError::kProtocolViolation, "Received SERVER_SETUP from client"); return; } if (message.selected_version != session_->parameters_.version) { session_->Error(MoqtError::kProtocolViolation, absl::StrCat("Version mismatch: expected 0x", absl::Hex(session_->parameters_.version))); return; } session_->peer_supports_object_ack_ = message.supports_object_ack; QUIC_DLOG(INFO) << ENDPOINT << "Received the SETUP message"; if (message.max_subscribe_id.has_value()) { session_->peer_max_subscribe_id_ = *message.max_subscribe_id; } std::move(session_->callbacks_.session_established_callback)(); session_->peer_role_ = *message.role; } void MoqtSession::ControlStream::SendSubscribeError( const MoqtSubscribe& message, SubscribeErrorCode error_code, absl::string_view reason_phrase, uint64_t track_alias) { MoqtSubscribeError subscribe_error; subscribe_error.subscribe_id = message.subscribe_id; subscribe_error.error_code = error_code; subscribe_error.reason_phrase = reason_phrase; subscribe_error.track_alias = track_alias; SendOrBufferMessage( session_->framer_.SerializeSubscribeError(subscribe_error)); } void MoqtSession::ControlStream::OnSubscribeMessage( const MoqtSubscribe& message) { if (session_->peer_role_ == MoqtRole::kPublisher) { QUIC_DLOG(INFO) << ENDPOINT << "Publisher peer sent SUBSCRIBE"; session_->Error(MoqtError::kProtocolViolation, "Received SUBSCRIBE from publisher"); return; } if (message.subscribe_id > session_->local_max_subscribe_id_) { QUIC_DLOG(INFO) << ENDPOINT << "Received SUBSCRIBE with too large ID"; session_->Error(MoqtError::kTooManySubscribes, "Received SUBSCRIBE with too large ID"); return; } QUIC_DLOG(INFO) << ENDPOINT << "Received a SUBSCRIBE for " << message.full_track_name; const FullTrackName& track_name = message.full_track_name; absl::StatusOr<std::shared_ptr<MoqtTrackPublisher>> track_publisher = session_->publisher_->GetTrack(track_name); if (!track_publisher.ok()) { QUIC_DLOG(INFO) << ENDPOINT << "SUBSCRIBE for " << track_name << " rejected by the application: " << track_publisher.status(); SendSubscribeError(message, SubscribeErrorCode::kTrackDoesNotExist, track_publisher.status().message(), message.track_alias); return; } std::optional<FullSequence> largest_id; if (PublisherHasData(**track_publisher)) { largest_id = (*track_publisher)->GetLargestSequence(); } MoqtDeliveryOrder delivery_order = (*track_publisher)->GetDeliveryOrder(); MoqtPublishingMonitorInterface* monitoring = nullptr; auto monitoring_it = session_->monitoring_interfaces_for_published_tracks_.find(track_name); if (monitoring_it != session_->monitoring_interfaces_for_published_tracks_.end()) { monitoring = monitoring_it->second; session_->monitoring_interfaces_for_published_tracks_.erase(monitoring_it); } auto subscription = std::make_unique<MoqtSession::PublishedSubscription>( session_, *std::move(track_publisher), message, monitoring); auto [it, success] = session_->published_subscriptions_.emplace( message.subscribe_id, std::move(subscription)); if (!success) { SendSubscribeError(message, SubscribeErrorCode::kInternalError, "Duplicate subscribe ID", message.track_alias); } MoqtSubscribeOk subscribe_ok; subscribe_ok.subscribe_id = message.subscribe_id; subscribe_ok.group_order = delivery_order; subscribe_ok.largest_id = largest_id; SendOrBufferMessage(session_->framer_.SerializeSubscribeOk(subscribe_ok)); if (largest_id.has_value()) { it->second->Backfill(); } } void MoqtSession::ControlStream::OnSubscribeOkMessage( const MoqtSubscribeOk& message) { auto it = session_->active_subscribes_.find(message.subscribe_id); if (it == session_->active_subscribes_.end()) { session_->Error(MoqtError::kProtocolViolation, "Received SUBSCRIBE_OK for nonexistent subscribe"); return; } MoqtSubscribe& subscribe = it->second.message; QUIC_DLOG(INFO) << ENDPOINT << "Received the SUBSCRIBE_OK for " << "subscribe_id = " << message.subscribe_id << " " << subscribe.full_track_name; RemoteTrack::Visitor* visitor = it->second.visitor; auto [track_iter, new_entry] = session_->remote_tracks_.try_emplace( subscribe.track_alias, subscribe.full_track_name, subscribe.track_alias, visitor); if (it->second.forwarding_preference.has_value()) { if (!track_iter->second.CheckForwardingPreference( *it->second.forwarding_preference)) { session_->Error(MoqtError::kProtocolViolation, "Forwarding preference different in early objects"); return; } } if (visitor != nullptr) { visitor->OnReply(subscribe.full_track_name, std::nullopt); } session_->active_subscribes_.erase(it); } void MoqtSession::ControlStream::OnSubscribeErrorMessage( const MoqtSubscribeError& message) { auto it = session_->active_subscribes_.find(message.subscribe_id); if (it == session_->active_subscribes_.end()) { session_->Error(MoqtError::kProtocolViolation, "Received SUBSCRIBE_ERROR for nonexistent subscribe"); return; } if (it->second.received_object) { session_->Error(MoqtError::kProtocolViolation, "Received SUBSCRIBE_ERROR after object"); return; } MoqtSubscribe& subscribe = it->second.message; QUIC_DLOG(INFO) << ENDPOINT << "Received the SUBSCRIBE_ERROR for " << "subscribe_id = " << message.subscribe_id << " (" << subscribe.full_track_name << ")" << ", error = " << static_cast<int>(message.error_code) << " (" << message.reason_phrase << ")"; RemoteTrack::Visitor* visitor = it->second.visitor; if (message.error_code == SubscribeErrorCode::kRetryTrackAlias) { session_->remote_track_aliases_[subscribe.full_track_name] = message.track_alias; session_->Subscribe(subscribe, visitor); } else if (visitor != nullptr) { visitor->OnReply(subscribe.full_track_name, message.reason_phrase); } session_->active_subscribes_.erase(it); } void MoqtSession::ControlStream::OnUnsubscribeMessage( const MoqtUnsubscribe& message) { session_->SubscribeIsDone(message.subscribe_id, SubscribeDoneCode::kUnsubscribed, ""); } void MoqtSession::ControlStream::OnSubscribeUpdateMessage( const MoqtSubscribeUpdate& message) { auto it = session_->published_subscriptions_.find(message.subscribe_id); if (it == session_->published_subscriptions_.end()) { return; } FullSequence start(message.start_group, message.start_object); std::optional<FullSequence> end; if (message.end_group.has_value()) { end = FullSequence(*message.end_group, message.end_object.has_value() ? *message.end_object : UINT64_MAX); } it->second->Update(start, end, message.subscriber_priority); } void MoqtSession::ControlStream::OnAnnounceMessage( const MoqtAnnounce& message) { if (session_->peer_role_ == MoqtRole::kSubscriber) { QUIC_DLOG(INFO) << ENDPOINT << "Subscriber peer sent SUBSCRIBE"; session_->Error(MoqtError::kProtocolViolation, "Received ANNOUNCE from Subscriber"); return; } std::optional<MoqtAnnounceErrorReason> error = session_->callbacks_.incoming_announce_callback(message.track_namespace); if (error.has_value()) { MoqtAnnounceError reply; reply.track_namespace = message.track_namespace; reply.error_code = error->error_code; reply.reason_phrase = error->reason_phrase; SendOrBufferMessage(session_->framer_.SerializeAnnounceError(reply)); return; } MoqtAnnounceOk ok; ok.track_namespace = message.track_namespace; SendOrBufferMessage(session_->framer_.SerializeAnnounceOk(ok)); } void MoqtSession::ControlStream::OnAnnounceOkMessage( const MoqtAnnounceOk& message) { auto it = session_->pending_outgoing_announces_.find(message.track_namespace); if (it == session_->pending_outgoing_announces_.end()) { session_->Error(MoqtError::kProtocolViolation, "Received ANNOUNCE_OK for nonexistent announce"); return; } std::move(it->second)(message.track_namespace, std::nullopt); session_->pending_outgoing_announces_.erase(it); } void MoqtSession::ControlStream::OnAnnounceErrorMessage( const MoqtAnnounceError& message) { auto it = session_->pending_outgoing_announces_.find(message.track_namespace); if (it == session_->pending_outgoing_announces_.end()) { session_->Error(MoqtError::kProtocolViolation, "Received ANNOUNCE_ERROR for nonexistent announce"); return; } std::move(it->second)( message.track_namespace, MoqtAnnounceErrorReason{message.error_code, std::string(message.reason_phrase)}); session_->pending_outgoing_announces_.erase(it); } void MoqtSession::ControlStream::OnAnnounceCancelMessage( const MoqtAnnounceCancel& message) { } void MoqtSession::ControlStream::OnMaxSubscribeIdMessage( const MoqtMaxSubscribeId& message) { if (session_->peer_role_ == MoqtRole::kSubscriber) { QUIC_DLOG(INFO) << ENDPOINT << "Subscriber peer sent MAX_SUBSCRIBE_ID"; session_->Error(MoqtError::kProtocolViolation, "Received MAX_SUBSCRIBE_ID from Subscriber"); return; } if (message.max_subscribe_id < session_->peer_max_subscribe_id_) { QUIC_DLOG(INFO) << ENDPOINT << "Peer sent MAX_SUBSCRIBE_ID message with " "lower value than previous"; session_->Error(MoqtError::kProtocolViolation, "MAX_SUBSCRIBE_ID message has lower value than previous"); return; } session_->peer_max_subscribe_id_ = message.max_subscribe_id; } void MoqtSession::ControlStream::OnParsingError(MoqtError error_code, absl::string_view reason) { session_->Error(error_code, absl::StrCat("Parse error: ", reason)); } void MoqtSession::ControlStream::SendOrBufferMessage( quiche::QuicheBuffer message, bool fin) { quiche::StreamWriteOptions options; options.set_send_fin(fin); options.set_buffer_unconditionally(true); std::array<absl::string_view, 1> write_vector = {message.AsStringView()}; absl::Status success = stream_->Writev(absl::MakeSpan(write_vector), options); if (!success.ok()) { session_->Error(MoqtError::kInternalError, "Failed to write a control message"); } } void MoqtSession::IncomingDataStream::OnObjectMessage(const MoqtObject& message, absl::string_view payload, bool end_of_message) { QUICHE_DVLOG(1) << ENDPOINT << "Received OBJECT message on stream " << stream_->GetStreamId() << " for subscribe_id " << message.subscribe_id << " for track alias " << message.track_alias << " with sequence " << message.group_id << ":" << message.object_id << " priority " << message.publisher_priority << " forwarding_preference " << MoqtForwardingPreferenceToString( message.forwarding_preference) << " length " << payload.size() << " length " << message.payload_length << (end_of_message ? "F" : ""); if (!session_->parameters_.deliver_partial_objects) { if (!end_of_message) { if (partial_object_.empty()) { partial_object_.reserve(message.payload_length); } absl::StrAppend(&partial_object_, payload); return; } if (!partial_object_.empty()) { absl::StrAppend(&partial_object_, payload); payload = absl::string_view(partial_object_); } } auto [full_track_name, visitor] = session_->TrackPropertiesFromAlias(message); if (visitor != nullptr) { visitor->OnObjectFragment( full_track_name, message.group_id, message.object_id, message.publisher_priority, message.object_status, message.forwarding_preference, payload, end_of_message); } partial_object_.clear(); } void MoqtSession::IncomingDataStream::OnCanRead() { ForwardStreamDataToParser(*stream_, parser_); } void MoqtSession::IncomingDataStream::OnControlMessageReceived() { session_->Error(MoqtError::kProtocolViolation, "Received a control message on a data stream"); } void MoqtSession::IncomingDataStream::OnParsingError(MoqtError error_code, absl::string_view reason) { session_->Error(error_code, absl::StrCat("Parse error: ", reason)); } MoqtSession::PublishedSubscription::PublishedSubscription( MoqtSession* session, std::shared_ptr<MoqtTrackPublisher> track_publisher, const MoqtSubscribe& subscribe, MoqtPublishingMonitorInterface* monitoring_interface) : subscription_id_(subscribe.subscribe_id), session_(session), track_publisher_(track_publisher), track_alias_(subscribe.track_alias), window_(SubscribeMessageToWindow(subscribe, *track_publisher)), subscriber_priority_(subscribe.subscriber_priority), subscriber_delivery_order_(subscribe.group_order), monitoring_interface_(monitoring_interface) { track_publisher->AddObjectListener(this); if (monitoring_interface_ != nullptr) { monitoring_interface_->OnObjectAckSupportKnown( subscribe.parameters.object_ack_window.has_value()); } QUIC_DLOG(INFO) << ENDPOINT << "Created subscription for " << subscribe.full_track_name; } MoqtSession::PublishedSubscription::~PublishedSubscription() { track_publisher_->RemoveObjectListener(this); } SendStreamMap& MoqtSession::PublishedSubscription::stream_map() { if (!lazily_initialized_stream_map_.has_value()) { QUICHE_DCHECK( DoesTrackStatusImplyHavingData(*track_publisher_->GetTrackStatus())); lazily_initialized_stream_map_.emplace( track_publisher_->GetForwardingPreference()); } return *lazily_initialized_stream_map_; } void MoqtSession::PublishedSubscription::Update( FullSequence start, std::optional<FullSequence> end, MoqtPriority subscriber_priority) { window_.UpdateStartEnd(start, end); subscriber_priority_ = subscriber_priority; } void MoqtSession::PublishedSubscription::set_subscriber_priority( MoqtPriority priority) { if (priority == subscriber_priority_) { return; } if (queued_outgoing_data_streams_.empty()) { subscriber_priority_ = priority; return; } webtransport::SendOrder old_send_order = FinalizeSendOrder(queued_outgoing_data_streams_.rbegin()->first); subscriber_priority_ = priority; session_->UpdateQueuedSendOrder(subscription_id_, old_send_order, FinalizeSendOrder(old_send_order)); }; void MoqtSession::PublishedSubscription::OnNewObjectAvailable( FullSequence sequence) { if (!window_.InWindow(sequence)) { return; } MoqtForwardingPreference forwarding_preference = track_publisher_->GetForwardingPreference(); if (forwarding_preference == MoqtForwardingPreference::kDatagram) { SendDatagram(sequence); return; } std::optional<webtransport::StreamId> stream_id = stream_map().GetStreamForSequence(sequence); webtransport::Stream* raw_stream = nullptr; if (stream_id.has_value()) { raw_stream = session_->session_->GetStreamById(*stream_id); } else { raw_stream = session_->OpenOrQueueDataStream(subscription_id_, sequence); } if (raw_stream == nullptr) { return; } OutgoingDataStream* stream = static_cast<OutgoingDataStream*>(raw_stream->visitor()); stream->SendObjects(*this); } void MoqtSession::PublishedSubscription::Backfill() { const FullSequence start = window_.start(); const FullSequence end = track_publisher_->GetLargestSequence(); const MoqtForwardingPreference preference = track_publisher_->GetForwardingPreference(); absl::flat_hash_set<ReducedSequenceIndex> already_opened; std::vector<FullSequence> objects = track_publisher_->GetCachedObjectsInRange(start, end); QUICHE_DCHECK(absl::c_is_sorted(objects)); for (FullSequence sequence : objects) { auto [it, was_missing] = already_opened.insert(ReducedSequenceIndex(sequence, preference)); if (!was_missing) { continue; } OnNewObjectAvailable(sequence); } } std::vector<webtransport::StreamId> MoqtSession::PublishedSubscription::GetAllStreams() const { if (!lazily_initialized_stream_map_.has_value()) { return {}; } return lazily_initialized_stream_map_->GetAllStreams(); } webtransport::SendOrder MoqtSession::PublishedSubscription::GetSendOrder( FullSequence sequence) const { MoqtForwardingPreference forwarding_preference = track_publisher_->GetForwardingPreference(); MoqtPriority publisher_priority = track_publisher_->GetPublisherPriority(); MoqtDeliveryOrder delivery_order = subscriber_delivery_order().value_or( track_publisher_->GetDeliveryOrder()); switch (forwarding_preference) { case MoqtForwardingPreference::kTrack: return SendOrderForStream(subscriber_priority_, publisher_priority, 0, delivery_order); break; case MoqtForwardingPreference::kSubgroup: return SendOrderForStream(subscriber_priority_, publisher_priority, sequence.group, sequence.subgroup, delivery_order); break; case MoqtForwardingPreference::kDatagram: QUICHE_NOTREACHED(); return 0; } } void MoqtSession::PublishedSubscription::AddQueuedOutgoingDataStream( FullSequence first_object) { std::optional<webtransport::SendOrder> start_send_order = queued_outgoing_data_streams_.empty() ? std::optional<webtransport::SendOrder>() : queued_outgoing_data_streams_.rbegin()->first; webtransport::SendOrder send_order = GetSendOrder(first_object); queued_outgoing_data_streams_.emplace( UpdateSendOrderForSubscriberPriority(send_order, 0), first_object); if (!start_send_order.has_value()) { session_->UpdateQueuedSendOrder(subscription_id_, std::nullopt, send_order); } else if (*start_send_order < send_order) { session_->UpdateQueuedSendOrder( subscription_id_, FinalizeSendOrder(*start_send_order), send_order); } } FullSequence MoqtSession::PublishedSubscription::NextQueuedOutgoingDataStream() { QUICHE_DCHECK(!queued_outgoing_data_streams_.empty()); if (queued_outgoing_data_streams_.empty()) { return FullSequence(); } auto it = queued_outgoing_data_streams_.rbegin(); webtransport::SendOrder old_send_order = FinalizeSendOrder(it->first); FullSequence first_object = it->second; queued_outgoing_data_streams_.erase((++it).base()); if (queued_outgoing_data_streams_.empty()) { session_->UpdateQueuedSendOrder(subscription_id_, old_send_order, std::nullopt); } else { webtransport::SendOrder new_send_order = FinalizeSendOrder(queued_outgoing_data_streams_.rbegin()->first); if (old_send_order != new_send_order) { session_->UpdateQueuedSendOrder(subscription_id_, old_send_order, new_send_order); } } return first_object; } void MoqtSession::PublishedSubscription::OnDataStreamCreated( webtransport::StreamId id, FullSequence start_sequence) { stream_map().AddStream(start_sequence, id); } void MoqtSession::PublishedSubscription::OnDataStreamDestroyed( webtransport::StreamId id, FullSequence end_sequence) { stream_map().RemoveStream(end_sequence, id); } void MoqtSession::PublishedSubscription::OnObjectSent(FullSequence sequence) { if (largest_sent_.has_value()) { largest_sent_ = std::max(*largest_sent_, sequence); } else { largest_sent_ = sequence; } } MoqtSession::OutgoingDataStream::OutgoingDataStream( MoqtSession* session, webtransport::Stream* stream, PublishedSubscription& subscription, FullSequence first_object) : session_(session), stream_(stream), subscription_id_(subscription.subscription_id()), next_object_(first_object), session_liveness_(session->liveness_token_) { UpdateSendOrder(subscription); } MoqtSession::OutgoingDataStream::~OutgoingDataStream() { if (session_liveness_.expired()) { return; } auto it = session_->published_subscriptions_.find(subscription_id_); if (it != session_->published_subscriptions_.end()) { it->second->OnDataStreamDestroyed(stream_->GetStreamId(), next_object_); } } void MoqtSession::OutgoingDataStream::OnCanWrite() { PublishedSubscription* subscription = GetSubscriptionIfValid(); if (subscription == nullptr) { return; } SendObjects(*subscription); } MoqtSession::PublishedSubscription* MoqtSession::OutgoingDataStream::GetSubscriptionIfValid() { auto it = session_->published_subscriptions_.find(subscription_id_); if (it == session_->published_subscriptions_.end()) { stream_->ResetWithUserCode(kResetCodeSubscriptionGone); return nullptr; } PublishedSubscription* subscription = it->second.get(); MoqtTrackPublisher& publisher = subscription->publisher(); absl::StatusOr<MoqtTrackStatusCode> status = publisher.GetTrackStatus(); if (!status.ok()) { return nullptr; } if (!DoesTrackStatusImplyHavingData(*status)) { QUICHE_BUG(GetSubscriptionIfValid_InvalidTrackStatus) << "The track publisher returned a status indicating that no objects " "are available, but a stream for those objects exists."; session_->Error(MoqtError::kInternalError, "Invalid track state provided by application"); return nullptr; } return subscription; } void MoqtSession::OutgoingDataStream::SendObjects( PublishedSubscription& subscription) { while (stream_->CanWrite()) { std::optional<PublishedObject> object = subscription.publisher().GetCachedObject(next_object_); if (!object.has_value()) { break; } if (!subscription.InWindow(next_object_)) { bool success = stream_->SendFin(); QUICHE_BUG_IF(OutgoingDataStream_fin_due_to_update, !success) << "Writing FIN failed despite CanWrite() being true."; return; } SendNextObject(subscription, *std::move(object)); } } void MoqtSession::OutgoingDataStream::SendNextObject( PublishedSubscription& subscription, PublishedObject object) { QUICHE_DCHECK(object.sequence == next_object_); QUICHE_DCHECK(stream_->CanWrite()); MoqtTrackPublisher& publisher = subscription.publisher(); QUICHE_DCHECK(DoesTrackStatusImplyHavingData(*publisher.GetTrackStatus())); MoqtForwardingPreference forwarding_preference = publisher.GetForwardingPreference(); UpdateSendOrder(subscription); MoqtObject header; header.subscribe_id = subscription_id_; header.track_alias = subscription.track_alias(); header.group_id = object.sequence.group; header.object_id = object.sequence.object; header.publisher_priority = publisher.GetPublisherPriority(); header.object_status = object.status; header.forwarding_preference = forwarding_preference; header.subgroup_id = (forwarding_preference == MoqtForwardingPreference::kSubgroup) ? 0 : std::optional<uint64_t>(); header.payload_length = object.payload.length(); quiche::QuicheBuffer serialized_header = session_->framer_.SerializeObjectHeader(header, !stream_header_written_); bool fin = false; switch (forwarding_preference) { case MoqtForwardingPreference::kTrack: if (object.status == MoqtObjectStatus::kEndOfGroup || object.status == MoqtObjectStatus::kGroupDoesNotExist) { ++next_object_.group; next_object_.object = 0; } else { ++next_object_.object; } fin = object.status == MoqtObjectStatus::kEndOfTrack || !subscription.InWindow(next_object_); break; case MoqtForwardingPreference::kSubgroup: ++next_object_.object; fin = object.status == MoqtObjectStatus::kEndOfTrack || object.status == MoqtObjectStatus::kEndOfGroup || object.status == MoqtObjectStatus::kEndOfSubgroup || object.status == MoqtObjectStatus::kGroupDoesNotExist || !subscription.InWindow(next_object_); break; case MoqtForwardingPreference::kDatagram: QUICHE_NOTREACHED(); break; } std::array<absl::string_view, 2> write_vector = { serialized_header.AsStringView(), object.payload.AsStringView()}; quiche::StreamWriteOptions options; options.set_send_fin(fin); absl::Status write_status = stream_->Writev(write_vector, options); if (!write_status.ok()) { QUICHE_BUG(MoqtSession_SendNextObject_write_failed) << "Writing into MoQT stream failed despite CanWrite() being true " "before; status: " << write_status; session_->Error(MoqtError::kInternalError, "Data stream write error"); return; } QUIC_DVLOG(1) << "Stream " << stream_->GetStreamId() << " successfully wrote " << object.sequence << ", fin = " << fin << ", next: " << next_object_; stream_header_written_ = true; subscription.OnObjectSent(object.sequence); } void MoqtSession::PublishedSubscription::SendDatagram(FullSequence sequence) { std::optional<PublishedObject> object = track_publisher_->GetCachedObject(sequence); if (!object.has_value()) { QUICHE_BUG(PublishedSubscription_SendDatagram_object_not_in_cache) << "Got notification about an object that is not in the cache"; return; } MoqtObject header; header.subscribe_id = subscription_id_; header.track_alias = track_alias(); header.group_id = object->sequence.group; header.object_id = object->sequence.object; header.publisher_priority = track_publisher_->GetPublisherPriority(); header.object_status = object->status; header.forwarding_preference = MoqtForwardingPreference::kDatagram; header.subgroup_id = std::nullopt; header.payload_length = object->payload.length(); quiche::QuicheBuffer datagram = session_->framer_.SerializeObjectDatagram( header, object->payload.AsStringView()); session_->session_->SendOrQueueDatagram(datagram.AsStringView()); OnObjectSent(object->sequence); } void MoqtSession::OutgoingDataStream::UpdateSendOrder( PublishedSubscription& subscription) { stream_->SetPriority( webtransport::StreamPriority{kMoqtSendGroupId, subscription.GetSendOrder(next_object_)}); } }
#include "quiche/quic/moqt/moqt_session.h" #include <cstdint> #include <cstring> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/core/quic_data_reader.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/moqt/moqt_known_track_publisher.h" #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/quic/moqt/moqt_parser.h" #include "quiche/quic/moqt/moqt_priority.h" #include "quiche/quic/moqt/moqt_publisher.h" #include "quiche/quic/moqt/moqt_track.h" #include "quiche/quic/moqt/tools/moqt_mock_visitor.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/quiche_stream.h" #include "quiche/web_transport/test_tools/mock_web_transport.h" #include "quiche/web_transport/web_transport.h" namespace moqt { namespace test { namespace { using ::quic::test::MemSliceFromString; using ::testing::_; using ::testing::AnyNumber; using ::testing::Return; using ::testing::StrictMock; constexpr webtransport::StreamId kControlStreamId = 4; constexpr webtransport::StreamId kIncomingUniStreamId = 15; constexpr webtransport::StreamId kOutgoingUniStreamId = 14; static std::optional<MoqtMessageType> ExtractMessageType( const absl::string_view message) { quic::QuicDataReader reader(message); uint64_t value; if (!reader.ReadVarInt62(&value)) { return std::nullopt; } return static_cast<MoqtMessageType>(value); } static std::shared_ptr<MockTrackPublisher> SetupPublisher( FullTrackName track_name, MoqtForwardingPreference forwarding_preference, FullSequence largest_sequence) { auto publisher = std::make_shared<MockTrackPublisher>(std::move(track_name)); ON_CALL(*publisher, GetTrackStatus()) .WillByDefault(Return(MoqtTrackStatusCode::kInProgress)); ON_CALL(*publisher, GetForwardingPreference()) .WillByDefault(Return(forwarding_preference)); ON_CALL(*publisher, GetLargestSequence()) .WillByDefault(Return(largest_sequence)); return publisher; } } class MoqtSessionPeer { public: static std::unique_ptr<MoqtControlParserVisitor> CreateControlStream( MoqtSession* session, webtransport::test::MockStream* stream) { auto new_stream = std::make_unique<MoqtSession::ControlStream>(session, stream); session->control_stream_ = kControlStreamId; EXPECT_CALL(*stream, visitor()) .Times(AnyNumber()) .WillRepeatedly(Return(new_stream.get())); return new_stream; } static std::unique_ptr<MoqtDataParserVisitor> CreateIncomingDataStream( MoqtSession* session, webtransport::Stream* stream) { auto new_stream = std::make_unique<MoqtSession::IncomingDataStream>(session, stream); return new_stream; } static MoqtControlParserVisitor* FetchParserVisitorFromWebtransportStreamVisitor( MoqtSession* session, webtransport::StreamVisitor* visitor) { return static_cast<MoqtSession::ControlStream*>(visitor); } static void CreateRemoteTrack(MoqtSession* session, const FullTrackName& name, RemoteTrack::Visitor* visitor, uint64_t track_alias) { session->remote_tracks_.try_emplace(track_alias, name, track_alias, visitor); session->remote_track_aliases_.try_emplace(name, track_alias); } static void AddActiveSubscribe(MoqtSession* session, uint64_t subscribe_id, MoqtSubscribe& subscribe, RemoteTrack::Visitor* visitor) { session->active_subscribes_[subscribe_id] = {subscribe, visitor}; } static MoqtObjectListener* AddSubscription( MoqtSession* session, std::shared_ptr<MoqtTrackPublisher> publisher, uint64_t subscribe_id, uint64_t track_alias, uint64_t start_group, uint64_t start_object) { MoqtSubscribe subscribe; subscribe.full_track_name = publisher->GetTrackName(); subscribe.track_alias = track_alias; subscribe.subscribe_id = subscribe_id; subscribe.start_group = start_group; subscribe.start_object = start_object; subscribe.subscriber_priority = 0x80; session->published_subscriptions_.emplace( subscribe_id, std::make_unique<MoqtSession::PublishedSubscription>( session, std::move(publisher), subscribe, nullptr)); return session->published_subscriptions_[subscribe_id].get(); } static void DeleteSubscription(MoqtSession* session, uint64_t subscribe_id) { session->published_subscriptions_.erase(subscribe_id); } static void UpdateSubscriberPriority(MoqtSession* session, uint64_t subscribe_id, MoqtPriority priority) { session->published_subscriptions_[subscribe_id]->set_subscriber_priority( priority); } static void set_peer_role(MoqtSession* session, MoqtRole role) { session->peer_role_ = role; } static RemoteTrack& remote_track(MoqtSession* session, uint64_t track_alias) { return session->remote_tracks_.find(track_alias)->second; } static void set_next_subscribe_id(MoqtSession* session, uint64_t id) { session->next_subscribe_id_ = id; } static void set_peer_max_subscribe_id(MoqtSession* session, uint64_t id) { session->peer_max_subscribe_id_ = id; } }; class MoqtSessionTest : public quic::test::QuicTest { public: MoqtSessionTest() : session_(&mock_session_, MoqtSessionParameters(quic::Perspective::IS_CLIENT, ""), session_callbacks_.AsSessionCallbacks()) { session_.set_publisher(&publisher_); MoqtSessionPeer::set_peer_max_subscribe_id(&session_, kDefaultInitialMaxSubscribeId); } ~MoqtSessionTest() { EXPECT_CALL(session_callbacks_.session_deleted_callback, Call()); } MockSessionCallbacks session_callbacks_; StrictMock<webtransport::test::MockSession> mock_session_; MoqtSession session_; MoqtKnownTrackPublisher publisher_; }; TEST_F(MoqtSessionTest, Queries) { EXPECT_EQ(session_.perspective(), quic::Perspective::IS_CLIENT); } TEST_F(MoqtSessionTest, OnSessionReady) { webtransport::test::MockStream mock_stream; EXPECT_CALL(mock_session_, OpenOutgoingBidirectionalStream()) .WillOnce(Return(&mock_stream)); std::unique_ptr<webtransport::StreamVisitor> visitor; EXPECT_CALL(mock_stream, SetVisitor(_)) .WillOnce([&](std::unique_ptr<webtransport::StreamVisitor> new_visitor) { visitor = std::move(new_visitor); }); EXPECT_CALL(mock_stream, GetStreamId()) .WillOnce(Return(webtransport::StreamId(4))); EXPECT_CALL(mock_session_, GetStreamById(4)).WillOnce(Return(&mock_stream)); bool correct_message = false; EXPECT_CALL(mock_stream, visitor()).WillOnce([&] { return visitor.get(); }); EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kClientSetup); return absl::OkStatus(); }); session_.OnSessionReady(); EXPECT_TRUE(correct_message); MoqtControlParserVisitor* stream_input = MoqtSessionPeer::FetchParserVisitorFromWebtransportStreamVisitor( &session_, visitor.get()); MoqtServerSetup setup = { kDefaultMoqtVersion, MoqtRole::kPubSub, }; EXPECT_CALL(session_callbacks_.session_established_callback, Call()).Times(1); stream_input->OnServerSetupMessage(setup); } TEST_F(MoqtSessionTest, OnClientSetup) { MoqtSession server_session( &mock_session_, MoqtSessionParameters(quic::Perspective::IS_SERVER), session_callbacks_.AsSessionCallbacks()); webtransport::test::MockStream mock_stream; std::unique_ptr<MoqtControlParserVisitor> stream_input = MoqtSessionPeer::CreateControlStream(&server_session, &mock_stream); MoqtClientSetup setup = { {kDefaultMoqtVersion}, MoqtRole::kPubSub, std::nullopt, }; bool correct_message = false; EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kServerSetup); return absl::OkStatus(); }); EXPECT_CALL(mock_stream, GetStreamId()).WillOnce(Return(0)); EXPECT_CALL(session_callbacks_.session_established_callback, Call()).Times(1); stream_input->OnClientSetupMessage(setup); } TEST_F(MoqtSessionTest, OnSessionClosed) { bool reported_error = false; EXPECT_CALL(session_callbacks_.session_terminated_callback, Call(_)) .WillOnce([&](absl::string_view error_message) { reported_error = true; EXPECT_EQ(error_message, "foo"); }); session_.OnSessionClosed(webtransport::SessionErrorCode(1), "foo"); EXPECT_TRUE(reported_error); } TEST_F(MoqtSessionTest, OnIncomingBidirectionalStream) { ::testing::InSequence seq; webtransport::test::MockStream mock_stream; StrictMock<webtransport::test::MockStreamVisitor> mock_stream_visitor; EXPECT_CALL(mock_session_, AcceptIncomingBidirectionalStream()) .WillOnce(Return(&mock_stream)); EXPECT_CALL(mock_stream, SetVisitor(_)).Times(1); EXPECT_CALL(mock_stream, visitor()).WillOnce(Return(&mock_stream_visitor)); EXPECT_CALL(mock_stream_visitor, OnCanRead()).Times(1); EXPECT_CALL(mock_session_, AcceptIncomingBidirectionalStream()) .WillOnce(Return(nullptr)); session_.OnIncomingBidirectionalStreamAvailable(); } TEST_F(MoqtSessionTest, OnIncomingUnidirectionalStream) { ::testing::InSequence seq; webtransport::test::MockStream mock_stream; StrictMock<webtransport::test::MockStreamVisitor> mock_stream_visitor; EXPECT_CALL(mock_session_, AcceptIncomingUnidirectionalStream()) .WillOnce(Return(&mock_stream)); EXPECT_CALL(mock_stream, SetVisitor(_)).Times(1); EXPECT_CALL(mock_stream, visitor()).WillOnce(Return(&mock_stream_visitor)); EXPECT_CALL(mock_stream_visitor, OnCanRead()).Times(1); EXPECT_CALL(mock_session_, AcceptIncomingUnidirectionalStream()) .WillOnce(Return(nullptr)); session_.OnIncomingUnidirectionalStreamAvailable(); } TEST_F(MoqtSessionTest, Error) { bool reported_error = false; EXPECT_CALL( mock_session_, CloseSession(static_cast<uint64_t>(MoqtError::kParameterLengthMismatch), "foo")) .Times(1); EXPECT_CALL(session_callbacks_.session_terminated_callback, Call(_)) .WillOnce([&](absl::string_view error_message) { reported_error = (error_message == "foo"); }); session_.Error(MoqtError::kParameterLengthMismatch, "foo"); EXPECT_TRUE(reported_error); } TEST_F(MoqtSessionTest, AddLocalTrack) { MoqtSubscribe request = { 1, 2, FullTrackName({"foo", "bar"}), 0x80, std::nullopt, 0, 0, std::nullopt, std::nullopt, MoqtSubscribeParameters(), }; webtransport::test::MockStream mock_stream; std::unique_ptr<MoqtControlParserVisitor> stream_input = MoqtSessionPeer::CreateControlStream(&session_, &mock_stream); bool correct_message = false; EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kSubscribeError); return absl::OkStatus(); }); stream_input->OnSubscribeMessage(request); EXPECT_TRUE(correct_message); auto track_publisher = std::make_shared<MockTrackPublisher>(FullTrackName("foo", "bar")); EXPECT_CALL(*track_publisher, GetTrackStatus()) .WillRepeatedly(Return(MoqtTrackStatusCode::kStatusNotAvailable)); publisher_.Add(track_publisher); correct_message = true; EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kSubscribeOk); return absl::OkStatus(); }); stream_input->OnSubscribeMessage(request); EXPECT_TRUE(correct_message); } TEST_F(MoqtSessionTest, AnnounceWithOk) { testing::MockFunction<void( FullTrackName track_namespace, std::optional<MoqtAnnounceErrorReason> error_message)> announce_resolved_callback; webtransport::test::MockStream mock_stream; std::unique_ptr<MoqtControlParserVisitor> stream_input = MoqtSessionPeer::CreateControlStream(&session_, &mock_stream); EXPECT_CALL(mock_session_, GetStreamById(_)).WillOnce(Return(&mock_stream)); bool correct_message = true; EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kAnnounce); return absl::OkStatus(); }); session_.Announce(FullTrackName{"foo"}, announce_resolved_callback.AsStdFunction()); EXPECT_TRUE(correct_message); MoqtAnnounceOk ok = { FullTrackName{"foo"}, }; correct_message = false; EXPECT_CALL(announce_resolved_callback, Call(_, _)) .WillOnce([&](FullTrackName track_namespace, std::optional<MoqtAnnounceErrorReason> error) { correct_message = true; EXPECT_EQ(track_namespace, FullTrackName{"foo"}); EXPECT_FALSE(error.has_value()); }); stream_input->OnAnnounceOkMessage(ok); EXPECT_TRUE(correct_message); } TEST_F(MoqtSessionTest, AnnounceWithError) { testing::MockFunction<void( FullTrackName track_namespace, std::optional<MoqtAnnounceErrorReason> error_message)> announce_resolved_callback; webtransport::test::MockStream mock_stream; std::unique_ptr<MoqtControlParserVisitor> stream_input = MoqtSessionPeer::CreateControlStream(&session_, &mock_stream); EXPECT_CALL(mock_session_, GetStreamById(_)).WillOnce(Return(&mock_stream)); bool correct_message = true; EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kAnnounce); return absl::OkStatus(); }); session_.Announce(FullTrackName{"foo"}, announce_resolved_callback.AsStdFunction()); EXPECT_TRUE(correct_message); MoqtAnnounceError error = { FullTrackName{"foo"}, MoqtAnnounceErrorCode::kInternalError, "Test error", }; correct_message = false; EXPECT_CALL(announce_resolved_callback, Call(_, _)) .WillOnce([&](FullTrackName track_namespace, std::optional<MoqtAnnounceErrorReason> error) { correct_message = true; EXPECT_EQ(track_namespace, FullTrackName{"foo"}); ASSERT_TRUE(error.has_value()); EXPECT_EQ(error->error_code, MoqtAnnounceErrorCode::kInternalError); EXPECT_EQ(error->reason_phrase, "Test error"); }); stream_input->OnAnnounceErrorMessage(error); EXPECT_TRUE(correct_message); } TEST_F(MoqtSessionTest, SubscribeForPast) { FullTrackName ftn("foo", "bar"); auto track = std::make_shared<MockTrackPublisher>(ftn); EXPECT_CALL(*track, GetTrackStatus()) .WillRepeatedly(Return(MoqtTrackStatusCode::kInProgress)); EXPECT_CALL(*track, GetCachedObject(_)).WillRepeatedly([] { return std::optional<PublishedObject>(); }); EXPECT_CALL(*track, GetCachedObjectsInRange(_, _)) .WillRepeatedly(Return(std::vector<FullSequence>())); EXPECT_CALL(*track, GetLargestSequence()) .WillRepeatedly(Return(FullSequence(10, 20))); publisher_.Add(track); MoqtSubscribe request = { 1, 2, FullTrackName({"foo", "bar"}), 0x80, std::nullopt, 0, 0, std::nullopt, std::nullopt, MoqtSubscribeParameters(), }; webtransport::test::MockStream mock_stream; std::unique_ptr<MoqtControlParserVisitor> stream_input = MoqtSessionPeer::CreateControlStream(&session_, &mock_stream); bool correct_message = true; EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kSubscribeOk); return absl::OkStatus(); }); stream_input->OnSubscribeMessage(request); EXPECT_TRUE(correct_message); } TEST_F(MoqtSessionTest, SubscribeIdTooHigh) { MoqtSubscribe request = { kDefaultInitialMaxSubscribeId + 1, 2, FullTrackName({"foo", "bar"}), 0x80, std::nullopt, 0, 0, std::nullopt, std::nullopt, MoqtSubscribeParameters(), }; webtransport::test::MockStream mock_stream; std::unique_ptr<MoqtControlParserVisitor> stream_input = MoqtSessionPeer::CreateControlStream(&session_, &mock_stream); EXPECT_CALL(mock_session_, CloseSession(static_cast<uint64_t>(MoqtError::kTooManySubscribes), "Received SUBSCRIBE with too large ID")) .Times(1); stream_input->OnSubscribeMessage(request); } TEST_F(MoqtSessionTest, TooManySubscribes) { MoqtSessionPeer::set_next_subscribe_id(&session_, kDefaultInitialMaxSubscribeId); MockRemoteTrackVisitor remote_track_visitor; webtransport::test::MockStream mock_stream; std::unique_ptr<MoqtControlParserVisitor> stream_input = MoqtSessionPeer::CreateControlStream(&session_, &mock_stream); EXPECT_CALL(mock_session_, GetStreamById(_)).WillOnce(Return(&mock_stream)); bool correct_message = true; EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kSubscribe); return absl::OkStatus(); }); EXPECT_TRUE(session_.SubscribeCurrentGroup(FullTrackName("foo", "bar"), &remote_track_visitor)); EXPECT_FALSE(session_.SubscribeCurrentGroup(FullTrackName("foo", "bar"), &remote_track_visitor)); } TEST_F(MoqtSessionTest, SubscribeWithOk) { webtransport::test::MockStream mock_stream; std::unique_ptr<MoqtControlParserVisitor> stream_input = MoqtSessionPeer::CreateControlStream(&session_, &mock_stream); MockRemoteTrackVisitor remote_track_visitor; EXPECT_CALL(mock_session_, GetStreamById(_)).WillOnce(Return(&mock_stream)); bool correct_message = true; EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kSubscribe); return absl::OkStatus(); }); session_.SubscribeCurrentGroup(FullTrackName("foo", "bar"), &remote_track_visitor); MoqtSubscribeOk ok = { 0, quic::QuicTimeDelta::FromMilliseconds(0), }; correct_message = false; EXPECT_CALL(remote_track_visitor, OnReply(_, _)) .WillOnce([&](const FullTrackName& ftn, std::optional<absl::string_view> error_message) { correct_message = true; EXPECT_EQ(ftn, FullTrackName("foo", "bar")); EXPECT_FALSE(error_message.has_value()); }); stream_input->OnSubscribeOkMessage(ok); EXPECT_TRUE(correct_message); } TEST_F(MoqtSessionTest, MaxSubscribeIdChangesResponse) { MoqtSessionPeer::set_next_subscribe_id(&session_, kDefaultInitialMaxSubscribeId + 1); MockRemoteTrackVisitor remote_track_visitor; EXPECT_FALSE(session_.SubscribeCurrentGroup(FullTrackName("foo", "bar"), &remote_track_visitor)); MoqtMaxSubscribeId max_subscribe_id = { kDefaultInitialMaxSubscribeId + 1, }; webtransport::test::MockStream mock_stream; std::unique_ptr<MoqtControlParserVisitor> stream_input = MoqtSessionPeer::CreateControlStream(&session_, &mock_stream); stream_input->OnMaxSubscribeIdMessage(max_subscribe_id); EXPECT_CALL(mock_session_, GetStreamById(_)).WillOnce(Return(&mock_stream)); bool correct_message = true; EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kSubscribe); return absl::OkStatus(); }); EXPECT_TRUE(session_.SubscribeCurrentGroup(FullTrackName("foo", "bar"), &remote_track_visitor)); EXPECT_TRUE(correct_message); } TEST_F(MoqtSessionTest, LowerMaxSubscribeIdIsAnError) { MoqtMaxSubscribeId max_subscribe_id = { kDefaultInitialMaxSubscribeId - 1, }; webtransport::test::MockStream mock_stream; std::unique_ptr<MoqtControlParserVisitor> stream_input = MoqtSessionPeer::CreateControlStream(&session_, &mock_stream); EXPECT_CALL( mock_session_, CloseSession(static_cast<uint64_t>(MoqtError::kProtocolViolation), "MAX_SUBSCRIBE_ID message has lower value than previous")) .Times(1); stream_input->OnMaxSubscribeIdMessage(max_subscribe_id); } TEST_F(MoqtSessionTest, GrantMoreSubscribes) { webtransport::test::MockStream mock_stream; std::unique_ptr<MoqtControlParserVisitor> stream_input = MoqtSessionPeer::CreateControlStream(&session_, &mock_stream); EXPECT_CALL(mock_session_, GetStreamById(_)).WillOnce(Return(&mock_stream)); bool correct_message = true; EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kMaxSubscribeId); return absl::OkStatus(); }); session_.GrantMoreSubscribes(1); EXPECT_TRUE(correct_message); MoqtSubscribe request = { kDefaultInitialMaxSubscribeId + 1, 2, FullTrackName({"foo", "bar"}), 0x80, std::nullopt, 0, 0, std::nullopt, std::nullopt, MoqtSubscribeParameters(), }; correct_message = false; FullTrackName ftn("foo", "bar"); auto track = std::make_shared<MockTrackPublisher>(ftn); EXPECT_CALL(*track, GetTrackStatus()) .WillRepeatedly(Return(MoqtTrackStatusCode::kInProgress)); EXPECT_CALL(*track, GetCachedObject(_)).WillRepeatedly([] { return std::optional<PublishedObject>(); }); EXPECT_CALL(*track, GetCachedObjectsInRange(_, _)) .WillRepeatedly(Return(std::vector<FullSequence>())); EXPECT_CALL(*track, GetLargestSequence()) .WillRepeatedly(Return(FullSequence(10, 20))); publisher_.Add(track); EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kSubscribeOk); return absl::OkStatus(); }); stream_input->OnSubscribeMessage(request); EXPECT_TRUE(correct_message); } TEST_F(MoqtSessionTest, SubscribeWithError) { webtransport::test::MockStream mock_stream; std::unique_ptr<MoqtControlParserVisitor> stream_input = MoqtSessionPeer::CreateControlStream(&session_, &mock_stream); MockRemoteTrackVisitor remote_track_visitor; EXPECT_CALL(mock_session_, GetStreamById(_)).WillOnce(Return(&mock_stream)); bool correct_message = true; EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kSubscribe); return absl::OkStatus(); }); session_.SubscribeCurrentGroup(FullTrackName("foo", "bar"), &remote_track_visitor); MoqtSubscribeError error = { 0, SubscribeErrorCode::kInvalidRange, "deadbeef", 2, }; correct_message = false; EXPECT_CALL(remote_track_visitor, OnReply(_, _)) .WillOnce([&](const FullTrackName& ftn, std::optional<absl::string_view> error_message) { correct_message = true; EXPECT_EQ(ftn, FullTrackName("foo", "bar")); EXPECT_EQ(*error_message, "deadbeef"); }); stream_input->OnSubscribeErrorMessage(error); EXPECT_TRUE(correct_message); } TEST_F(MoqtSessionTest, ReplyToAnnounce) { webtransport::test::MockStream mock_stream; std::unique_ptr<MoqtControlParserVisitor> stream_input = MoqtSessionPeer::CreateControlStream(&session_, &mock_stream); MoqtAnnounce announce = { FullTrackName{"foo"}, }; bool correct_message = false; EXPECT_CALL(session_callbacks_.incoming_announce_callback, Call(FullTrackName{"foo"})) .WillOnce(Return(std::nullopt)); EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kAnnounceOk); return absl::OkStatus(); }); stream_input->OnAnnounceMessage(announce); EXPECT_TRUE(correct_message); } TEST_F(MoqtSessionTest, IncomingObject) { MockRemoteTrackVisitor visitor_; FullTrackName ftn("foo", "bar"); std::string payload = "deadbeef"; MoqtSessionPeer::CreateRemoteTrack(&session_, ftn, &visitor_, 2); MoqtObject object = { 1, 2, 0, 0, 0, MoqtObjectStatus::kNormal, MoqtForwardingPreference::kSubgroup, 0, 8, }; webtransport::test::MockStream mock_stream; std::unique_ptr<MoqtDataParserVisitor> object_stream = MoqtSessionPeer::CreateIncomingDataStream(&session_, &mock_stream); EXPECT_CALL(visitor_, OnObjectFragment(_, _, _, _, _, _, _, _)).Times(1); EXPECT_CALL(mock_stream, GetStreamId()) .WillRepeatedly(Return(kIncomingUniStreamId)); object_stream->OnObjectMessage(object, payload, true); } TEST_F(MoqtSessionTest, IncomingPartialObject) { MockRemoteTrackVisitor visitor_; FullTrackName ftn("foo", "bar"); std::string payload = "deadbeef"; MoqtSessionPeer::CreateRemoteTrack(&session_, ftn, &visitor_, 2); MoqtObject object = { 1, 2, 0, 0, 0, MoqtObjectStatus::kNormal, MoqtForwardingPreference::kSubgroup, 0, 16, }; webtransport::test::MockStream mock_stream; std::unique_ptr<MoqtDataParserVisitor> object_stream = MoqtSessionPeer::CreateIncomingDataStream(&session_, &mock_stream); EXPECT_CALL(visitor_, OnObjectFragment(_, _, _, _, _, _, _, _)).Times(1); EXPECT_CALL(mock_stream, GetStreamId()) .WillRepeatedly(Return(kIncomingUniStreamId)); object_stream->OnObjectMessage(object, payload, false); object_stream->OnObjectMessage(object, payload, true); } TEST_F(MoqtSessionTest, IncomingPartialObjectNoBuffer) { MoqtSessionParameters parameters(quic::Perspective::IS_CLIENT); parameters.deliver_partial_objects = true; MoqtSession session(&mock_session_, parameters, session_callbacks_.AsSessionCallbacks()); MockRemoteTrackVisitor visitor_; FullTrackName ftn("foo", "bar"); std::string payload = "deadbeef"; MoqtSessionPeer::CreateRemoteTrack(&session, ftn, &visitor_, 2); MoqtObject object = { 1, 2, 0, 0, 0, MoqtObjectStatus::kNormal, MoqtForwardingPreference::kSubgroup, 0, 16, }; webtransport::test::MockStream mock_stream; std::unique_ptr<MoqtDataParserVisitor> object_stream = MoqtSessionPeer::CreateIncomingDataStream(&session, &mock_stream); EXPECT_CALL(visitor_, OnObjectFragment(_, _, _, _, _, _, _, _)).Times(2); EXPECT_CALL(mock_stream, GetStreamId()) .WillRepeatedly(Return(kIncomingUniStreamId)); object_stream->OnObjectMessage(object, payload, false); object_stream->OnObjectMessage(object, payload, true); } TEST_F(MoqtSessionTest, ObjectBeforeSubscribeOk) { MockRemoteTrackVisitor visitor_; FullTrackName ftn("foo", "bar"); std::string payload = "deadbeef"; MoqtSubscribe subscribe = { 1, 2, ftn, 0x80, std::nullopt, 0, 0, std::nullopt, std::nullopt, }; MoqtSessionPeer::AddActiveSubscribe(&session_, 1, subscribe, &visitor_); MoqtObject object = { 1, 2, 0, 0, 0, MoqtObjectStatus::kNormal, MoqtForwardingPreference::kSubgroup, 0, 8, }; webtransport::test::MockStream mock_stream; std::unique_ptr<MoqtDataParserVisitor> object_stream = MoqtSessionPeer::CreateIncomingDataStream(&session_, &mock_stream); EXPECT_CALL(visitor_, OnObjectFragment(_, _, _, _, _, _, _, _)) .WillOnce([&](const FullTrackName& full_track_name, uint64_t group_sequence, uint64_t object_sequence, MoqtPriority publisher_priority, MoqtObjectStatus status, MoqtForwardingPreference forwarding_preference, absl::string_view payload, bool end_of_message) { EXPECT_EQ(full_track_name, ftn); EXPECT_EQ(group_sequence, object.group_id); EXPECT_EQ(object_sequence, object.object_id); }); EXPECT_CALL(mock_stream, GetStreamId()) .WillRepeatedly(Return(kIncomingUniStreamId)); object_stream->OnObjectMessage(object, payload, true); MoqtSubscribeOk ok = { 1, quic::QuicTimeDelta::FromMilliseconds(0), MoqtDeliveryOrder::kAscending, std::nullopt, }; webtransport::test::MockStream mock_control_stream; std::unique_ptr<MoqtControlParserVisitor> control_stream = MoqtSessionPeer::CreateControlStream(&session_, &mock_control_stream); EXPECT_CALL(visitor_, OnReply(_, _)).Times(1); control_stream->OnSubscribeOkMessage(ok); } TEST_F(MoqtSessionTest, ObjectBeforeSubscribeError) { MockRemoteTrackVisitor visitor; FullTrackName ftn("foo", "bar"); std::string payload = "deadbeef"; MoqtSubscribe subscribe = { 1, 2, ftn, 0x80, std::nullopt, 0, 0, std::nullopt, std::nullopt, }; MoqtSessionPeer::AddActiveSubscribe(&session_, 1, subscribe, &visitor); MoqtObject object = { 1, 2, 0, 0, 0, MoqtObjectStatus::kNormal, MoqtForwardingPreference::kSubgroup, 0, 8, }; webtransport::test::MockStream mock_stream; std::unique_ptr<MoqtDataParserVisitor> object_stream = MoqtSessionPeer::CreateIncomingDataStream(&session_, &mock_stream); EXPECT_CALL(visitor, OnObjectFragment(_, _, _, _, _, _, _, _)) .WillOnce([&](const FullTrackName& full_track_name, uint64_t group_sequence, uint64_t object_sequence, MoqtPriority publisher_priority, MoqtObjectStatus status, MoqtForwardingPreference forwarding_preference, absl::string_view payload, bool end_of_message) { EXPECT_EQ(full_track_name, ftn); EXPECT_EQ(group_sequence, object.group_id); EXPECT_EQ(object_sequence, object.object_id); }); EXPECT_CALL(mock_stream, GetStreamId()) .WillRepeatedly(Return(kIncomingUniStreamId)); object_stream->OnObjectMessage(object, payload, true); MoqtSubscribeError subscribe_error = { 1, SubscribeErrorCode::kRetryTrackAlias, "foo", 3, }; webtransport::test::MockStream mock_control_stream; std::unique_ptr<MoqtControlParserVisitor> control_stream = MoqtSessionPeer::CreateControlStream(&session_, &mock_control_stream); EXPECT_CALL(mock_session_, CloseSession(static_cast<uint64_t>(MoqtError::kProtocolViolation), "Received SUBSCRIBE_ERROR after object")) .Times(1); control_stream->OnSubscribeErrorMessage(subscribe_error); } TEST_F(MoqtSessionTest, TwoEarlyObjectsDifferentForwarding) { MockRemoteTrackVisitor visitor; FullTrackName ftn("foo", "bar"); std::string payload = "deadbeef"; MoqtSubscribe subscribe = { 1, 2, ftn, 0x80, std::nullopt, 0, 0, std::nullopt, std::nullopt, }; MoqtSessionPeer::AddActiveSubscribe(&session_, 1, subscribe, &visitor); MoqtObject object = { 1, 2, 0, 0, 0, MoqtObjectStatus::kNormal, MoqtForwardingPreference::kSubgroup, 0, 8, }; webtransport::test::MockStream mock_stream; std::unique_ptr<MoqtDataParserVisitor> object_stream = MoqtSessionPeer::CreateIncomingDataStream(&session_, &mock_stream); EXPECT_CALL(visitor, OnObjectFragment(_, _, _, _, _, _, _, _)) .WillOnce([&](const FullTrackName& full_track_name, uint64_t group_sequence, uint64_t object_sequence, MoqtPriority publisher_priority, MoqtObjectStatus status, MoqtForwardingPreference forwarding_preference, absl::string_view payload, bool end_of_message) { EXPECT_EQ(full_track_name, ftn); EXPECT_EQ(group_sequence, object.group_id); EXPECT_EQ(object_sequence, object.object_id); }); EXPECT_CALL(mock_stream, GetStreamId()) .WillRepeatedly(Return(kIncomingUniStreamId)); object_stream->OnObjectMessage(object, payload, true); object.forwarding_preference = MoqtForwardingPreference::kTrack; ++object.object_id; EXPECT_CALL(mock_session_, CloseSession(static_cast<uint64_t>(MoqtError::kProtocolViolation), "Forwarding preference changes mid-track")) .Times(1); object_stream->OnObjectMessage(object, payload, true); } TEST_F(MoqtSessionTest, EarlyObjectForwardingDoesNotMatchTrack) { MockRemoteTrackVisitor visitor; FullTrackName ftn("foo", "bar"); std::string payload = "deadbeef"; MoqtSubscribe subscribe = { 1, 2, ftn, 0x80, std::nullopt, 0, 0, std::nullopt, std::nullopt, }; MoqtSessionPeer::AddActiveSubscribe(&session_, 1, subscribe, &visitor); MoqtObject object = { 1, 2, 0, 0, 0, MoqtObjectStatus::kNormal, MoqtForwardingPreference::kSubgroup, 0, 8, }; webtransport::test::MockStream mock_stream; std::unique_ptr<MoqtDataParserVisitor> object_stream = MoqtSessionPeer::CreateIncomingDataStream(&session_, &mock_stream); EXPECT_CALL(visitor, OnObjectFragment(_, _, _, _, _, _, _, _)) .WillOnce([&](const FullTrackName& full_track_name, uint64_t group_sequence, uint64_t object_sequence, MoqtPriority publisher_priority, MoqtObjectStatus status, MoqtForwardingPreference forwarding_preference, absl::string_view payload, bool end_of_message) { EXPECT_EQ(full_track_name, ftn); EXPECT_EQ(group_sequence, object.group_id); EXPECT_EQ(object_sequence, object.object_id); }); EXPECT_CALL(mock_stream, GetStreamId()) .WillRepeatedly(Return(kIncomingUniStreamId)); object_stream->OnObjectMessage(object, payload, true); MoqtSessionPeer::CreateRemoteTrack(&session_, ftn, &visitor, 2); MoqtSessionPeer::remote_track(&session_, 2) .CheckForwardingPreference(MoqtForwardingPreference::kTrack); MoqtSubscribeOk ok = { 1, quic::QuicTimeDelta::FromMilliseconds(0), MoqtDeliveryOrder::kAscending, std::nullopt, }; webtransport::test::MockStream mock_control_stream; std::unique_ptr<MoqtControlParserVisitor> control_stream = MoqtSessionPeer::CreateControlStream(&session_, &mock_control_stream); EXPECT_CALL(mock_session_, CloseSession(static_cast<uint64_t>(MoqtError::kProtocolViolation), "Forwarding preference different in early objects")) .Times(1); control_stream->OnSubscribeOkMessage(ok); } TEST_F(MoqtSessionTest, CreateIncomingDataStreamAndSend) { FullTrackName ftn("foo", "bar"); auto track = SetupPublisher(ftn, MoqtForwardingPreference::kSubgroup, FullSequence(4, 2)); MoqtObjectListener* subscription = MoqtSessionPeer::AddSubscription(&session_, track, 0, 2, 5, 0); EXPECT_CALL(mock_session_, CanOpenNextOutgoingUnidirectionalStream()) .WillOnce(Return(true)); bool fin = false; webtransport::test::MockStream mock_stream; EXPECT_CALL(mock_stream, CanWrite()).WillRepeatedly([&] { return !fin; }); EXPECT_CALL(mock_session_, OpenOutgoingUnidirectionalStream()) .WillOnce(Return(&mock_stream)); std::unique_ptr<webtransport::StreamVisitor> stream_visitor; EXPECT_CALL(mock_stream, SetVisitor(_)) .WillOnce([&](std::unique_ptr<webtransport::StreamVisitor> visitor) { stream_visitor = std::move(visitor); }); EXPECT_CALL(mock_stream, visitor()).WillOnce([&] { return stream_visitor.get(); }); EXPECT_CALL(mock_stream, GetStreamId()) .WillRepeatedly(Return(kOutgoingUniStreamId)); EXPECT_CALL(mock_session_, GetStreamById(kOutgoingUniStreamId)) .WillRepeatedly(Return(&mock_stream)); bool correct_message = false; const std::string kExpectedMessage = {0x04, 0x00, 0x02, 0x05, 0x00, 0x00}; EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = absl::StartsWith(data[0], kExpectedMessage); fin |= options.send_fin(); return absl::OkStatus(); }); EXPECT_CALL(*track, GetCachedObject(FullSequence(5, 0))).WillRepeatedly([] { return PublishedObject{FullSequence(5, 0), MoqtObjectStatus::kNormal, MemSliceFromString("deadbeef")}; }); EXPECT_CALL(*track, GetCachedObject(FullSequence(5, 1))).WillRepeatedly([] { return std::optional<PublishedObject>(); }); subscription->OnNewObjectAvailable(FullSequence(5, 0)); EXPECT_TRUE(correct_message); } TEST_F(MoqtSessionTest, UnidirectionalStreamCannotBeOpened) { FullTrackName ftn("foo", "bar"); auto track = SetupPublisher(ftn, MoqtForwardingPreference::kSubgroup, FullSequence(4, 2)); MoqtObjectListener* subscription = MoqtSessionPeer::AddSubscription(&session_, track, 0, 2, 5, 0); EXPECT_CALL(mock_session_, CanOpenNextOutgoingUnidirectionalStream()) .WillOnce(Return(false)); subscription->OnNewObjectAvailable(FullSequence(5, 0)); EXPECT_CALL(mock_session_, CanOpenNextOutgoingUnidirectionalStream()) .WillOnce(Return(true)); bool fin = false; webtransport::test::MockStream mock_stream; EXPECT_CALL(mock_stream, CanWrite()).WillRepeatedly([&] { return !fin; }); EXPECT_CALL(mock_session_, OpenOutgoingUnidirectionalStream()) .WillOnce(Return(&mock_stream)); std::unique_ptr<webtransport::StreamVisitor> stream_visitor; EXPECT_CALL(mock_stream, SetVisitor(_)) .WillOnce([&](std::unique_ptr<webtransport::StreamVisitor> visitor) { stream_visitor = std::move(visitor); }); EXPECT_CALL(mock_stream, visitor()).WillOnce([&] { return stream_visitor.get(); }); EXPECT_CALL(mock_stream, GetStreamId()) .WillRepeatedly(Return(kOutgoingUniStreamId)); EXPECT_CALL(mock_session_, GetStreamById(kOutgoingUniStreamId)) .WillRepeatedly(Return(&mock_stream)); EXPECT_CALL(mock_stream, Writev(_, _)).WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*track, GetCachedObject(FullSequence(5, 0))).WillRepeatedly([] { return PublishedObject{FullSequence(5, 0), MoqtObjectStatus::kNormal, MemSliceFromString("deadbeef")}; }); EXPECT_CALL(*track, GetCachedObject(FullSequence(5, 1))).WillRepeatedly([] { return std::optional<PublishedObject>(); }); session_.OnCanCreateNewOutgoingUnidirectionalStream(); } TEST_F(MoqtSessionTest, OutgoingStreamDisappears) { FullTrackName ftn("foo", "bar"); auto track = SetupPublisher(ftn, MoqtForwardingPreference::kSubgroup, FullSequence(4, 2)); MoqtObjectListener* subscription = MoqtSessionPeer::AddSubscription(&session_, track, 0, 2, 5, 0); EXPECT_CALL(mock_session_, CanOpenNextOutgoingUnidirectionalStream()) .WillOnce(Return(true)); webtransport::test::MockStream mock_stream; EXPECT_CALL(mock_stream, CanWrite()).WillRepeatedly(Return(true)); EXPECT_CALL(mock_session_, OpenOutgoingUnidirectionalStream()) .WillOnce(Return(&mock_stream)); std::unique_ptr<webtransport::StreamVisitor> stream_visitor; EXPECT_CALL(mock_stream, SetVisitor(_)) .WillOnce([&](std::unique_ptr<webtransport::StreamVisitor> visitor) { stream_visitor = std::move(visitor); }); EXPECT_CALL(mock_stream, visitor()).WillRepeatedly([&] { return stream_visitor.get(); }); EXPECT_CALL(mock_stream, GetStreamId()) .WillRepeatedly(Return(kOutgoingUniStreamId)); EXPECT_CALL(mock_session_, GetStreamById(kOutgoingUniStreamId)) .WillRepeatedly(Return(&mock_stream)); EXPECT_CALL(mock_stream, Writev(_, _)).WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*track, GetCachedObject(FullSequence(5, 0))).WillRepeatedly([] { return PublishedObject{FullSequence(5, 0), MoqtObjectStatus::kNormal, MemSliceFromString("deadbeef")}; }); EXPECT_CALL(*track, GetCachedObject(FullSequence(5, 1))).WillOnce([] { return std::optional<PublishedObject>(); }); subscription->OnNewObjectAvailable(FullSequence(5, 0)); EXPECT_CALL(mock_session_, GetStreamById(kOutgoingUniStreamId)) .WillRepeatedly(Return(nullptr)); EXPECT_CALL(*track, GetCachedObject(FullSequence(5, 1))).Times(0); subscription->OnNewObjectAvailable(FullSequence(5, 1)); } TEST_F(MoqtSessionTest, OneBidirectionalStreamClient) { webtransport::test::MockStream mock_stream; EXPECT_CALL(mock_session_, OpenOutgoingBidirectionalStream()) .WillOnce(Return(&mock_stream)); std::unique_ptr<webtransport::StreamVisitor> visitor; EXPECT_CALL(mock_stream, SetVisitor(_)) .WillOnce([&](std::unique_ptr<webtransport::StreamVisitor> new_visitor) { visitor = std::move(new_visitor); }); EXPECT_CALL(mock_stream, GetStreamId()) .WillOnce(Return(webtransport::StreamId(4))); EXPECT_CALL(mock_session_, GetStreamById(4)).WillOnce(Return(&mock_stream)); bool correct_message = false; EXPECT_CALL(mock_stream, visitor()).WillOnce([&] { return visitor.get(); }); EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kClientSetup); return absl::OkStatus(); }); session_.OnSessionReady(); EXPECT_TRUE(correct_message); bool reported_error = false; EXPECT_CALL(mock_session_, AcceptIncomingBidirectionalStream()) .WillOnce(Return(&mock_stream)); EXPECT_CALL(mock_session_, CloseSession(static_cast<uint64_t>(MoqtError::kProtocolViolation), "Bidirectional stream already open")) .Times(1); EXPECT_CALL(session_callbacks_.session_terminated_callback, Call(_)) .WillOnce([&](absl::string_view error_message) { reported_error = (error_message == "Bidirectional stream already open"); }); session_.OnIncomingBidirectionalStreamAvailable(); EXPECT_TRUE(reported_error); } TEST_F(MoqtSessionTest, OneBidirectionalStreamServer) { MoqtSession server_session( &mock_session_, MoqtSessionParameters(quic::Perspective::IS_SERVER), session_callbacks_.AsSessionCallbacks()); webtransport::test::MockStream mock_stream; std::unique_ptr<MoqtControlParserVisitor> stream_input = MoqtSessionPeer::CreateControlStream(&server_session, &mock_stream); MoqtClientSetup setup = { {kDefaultMoqtVersion}, MoqtRole::kPubSub, std::nullopt, }; bool correct_message = false; EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kServerSetup); return absl::OkStatus(); }); EXPECT_CALL(mock_stream, GetStreamId()).WillOnce(Return(0)); EXPECT_CALL(session_callbacks_.session_established_callback, Call()).Times(1); stream_input->OnClientSetupMessage(setup); bool reported_error = false; EXPECT_CALL(mock_session_, AcceptIncomingBidirectionalStream()) .WillOnce(Return(&mock_stream)); EXPECT_CALL(mock_session_, CloseSession(static_cast<uint64_t>(MoqtError::kProtocolViolation), "Bidirectional stream already open")) .Times(1); EXPECT_CALL(session_callbacks_.session_terminated_callback, Call(_)) .WillOnce([&](absl::string_view error_message) { reported_error = (error_message == "Bidirectional stream already open"); }); server_session.OnIncomingBidirectionalStreamAvailable(); EXPECT_TRUE(reported_error); } TEST_F(MoqtSessionTest, ReceiveUnsubscribe) { FullTrackName ftn("foo", "bar"); auto track = SetupPublisher(ftn, MoqtForwardingPreference::kTrack, FullSequence(4, 2)); MoqtSessionPeer::AddSubscription(&session_, track, 0, 1, 3, 4); webtransport::test::MockStream mock_stream; std::unique_ptr<MoqtControlParserVisitor> stream_input = MoqtSessionPeer::CreateControlStream(&session_, &mock_stream); MoqtUnsubscribe unsubscribe = { 0, }; EXPECT_CALL(mock_session_, GetStreamById(4)).WillOnce(Return(&mock_stream)); bool correct_message = false; EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kSubscribeDone); return absl::OkStatus(); }); stream_input->OnUnsubscribeMessage(unsubscribe); EXPECT_TRUE(correct_message); } TEST_F(MoqtSessionTest, SendDatagram) { FullTrackName ftn("foo", "bar"); std::shared_ptr<MockTrackPublisher> track_publisher = SetupPublisher( ftn, MoqtForwardingPreference::kDatagram, FullSequence{4, 0}); MoqtObjectListener* listener = MoqtSessionPeer::AddSubscription(&session_, track_publisher, 0, 2, 5, 0); bool correct_message = false; uint8_t kExpectedMessage[] = { 0x01, 0x00, 0x02, 0x05, 0x00, 0x00, 0x08, 0x64, 0x65, 0x61, 0x64, 0x62, 0x65, 0x65, 0x66, }; EXPECT_CALL(mock_session_, SendOrQueueDatagram(_)) .WillOnce([&](absl::string_view datagram) { if (datagram.size() == sizeof(kExpectedMessage)) { correct_message = (0 == memcmp(datagram.data(), kExpectedMessage, sizeof(kExpectedMessage))); } return webtransport::DatagramStatus( webtransport::DatagramStatusCode::kSuccess, ""); }); EXPECT_CALL(*track_publisher, GetCachedObject(FullSequence{5, 0})) .WillRepeatedly([] { return PublishedObject{FullSequence{5, 0}, MoqtObjectStatus::kNormal, MemSliceFromString("deadbeef")}; }); listener->OnNewObjectAvailable(FullSequence(5, 0)); EXPECT_TRUE(correct_message); } TEST_F(MoqtSessionTest, ReceiveDatagram) { MockRemoteTrackVisitor visitor_; FullTrackName ftn("foo", "bar"); std::string payload = "deadbeef"; MoqtSessionPeer::CreateRemoteTrack(&session_, ftn, &visitor_, 2); MoqtObject object = { 1, 2, 0, 0, 0, MoqtObjectStatus::kNormal, MoqtForwardingPreference::kDatagram, std::nullopt, 8, }; char datagram[] = {0x01, 0x01, 0x02, 0x00, 0x00, 0x00, 0x08, 0x64, 0x65, 0x61, 0x64, 0x62, 0x65, 0x65, 0x66}; EXPECT_CALL(visitor_, OnObjectFragment(ftn, object.group_id, object.object_id, object.publisher_priority, object.object_status, object.forwarding_preference, payload, true)) .Times(1); session_.OnDatagramReceived(absl::string_view(datagram, sizeof(datagram))); } TEST_F(MoqtSessionTest, ForwardingPreferenceMismatch) { MockRemoteTrackVisitor visitor_; FullTrackName ftn("foo", "bar"); std::string payload = "deadbeef"; MoqtSessionPeer::CreateRemoteTrack(&session_, ftn, &visitor_, 2); MoqtObject object = { 1, 2, 0, 0, 0, MoqtObjectStatus::kNormal, MoqtForwardingPreference::kSubgroup, 0, 8, }; webtransport::test::MockStream mock_stream; std::unique_ptr<MoqtDataParserVisitor> object_stream = MoqtSessionPeer::CreateIncomingDataStream(&session_, &mock_stream); EXPECT_CALL(visitor_, OnObjectFragment(_, _, _, _, _, _, _, _)).Times(1); EXPECT_CALL(mock_stream, GetStreamId()) .WillRepeatedly(Return(kIncomingUniStreamId)); object_stream->OnObjectMessage(object, payload, true); ++object.object_id; object.forwarding_preference = MoqtForwardingPreference::kTrack; EXPECT_CALL(mock_session_, CloseSession(static_cast<uint64_t>(MoqtError::kProtocolViolation), "Forwarding preference changes mid-track")) .Times(1); object_stream->OnObjectMessage(object, payload, true); } TEST_F(MoqtSessionTest, AnnounceToPublisher) { MoqtSessionPeer::set_peer_role(&session_, MoqtRole::kPublisher); testing::MockFunction<void( FullTrackName track_namespace, std::optional<MoqtAnnounceErrorReason> error_message)> announce_resolved_callback; EXPECT_CALL(announce_resolved_callback, Call(_, _)).Times(1); session_.Announce(FullTrackName{"foo"}, announce_resolved_callback.AsStdFunction()); } TEST_F(MoqtSessionTest, SubscribeFromPublisher) { MoqtSessionPeer::set_peer_role(&session_, MoqtRole::kPublisher); MoqtSubscribe request = { 1, 2, FullTrackName({"foo", "bar"}), 0x80, std::nullopt, 0, 0, std::nullopt, std::nullopt, MoqtSubscribeParameters(), }; webtransport::test::MockStream mock_stream; std::unique_ptr<MoqtControlParserVisitor> stream_input = MoqtSessionPeer::CreateControlStream(&session_, &mock_stream); EXPECT_CALL(mock_session_, CloseSession(static_cast<uint64_t>(MoqtError::kProtocolViolation), "Received SUBSCRIBE from publisher")) .Times(1); EXPECT_CALL(session_callbacks_.session_terminated_callback, Call(_)).Times(1); stream_input->OnSubscribeMessage(request); } TEST_F(MoqtSessionTest, AnnounceFromSubscriber) { MoqtSessionPeer::set_peer_role(&session_, MoqtRole::kSubscriber); webtransport::test::MockStream mock_stream; std::unique_ptr<MoqtControlParserVisitor> stream_input = MoqtSessionPeer::CreateControlStream(&session_, &mock_stream); MoqtAnnounce announce = { FullTrackName{"foo"}, }; EXPECT_CALL(mock_session_, CloseSession(static_cast<uint64_t>(MoqtError::kProtocolViolation), "Received ANNOUNCE from Subscriber")) .Times(1); EXPECT_CALL(session_callbacks_.session_terminated_callback, Call(_)).Times(1); stream_input->OnAnnounceMessage(announce); } TEST_F(MoqtSessionTest, QueuedStreamsOpenedInOrder) { FullTrackName ftn("foo", "bar"); auto track = SetupPublisher(ftn, MoqtForwardingPreference::kSubgroup, FullSequence(0, 0)); EXPECT_CALL(*track, GetTrackStatus()) .WillRepeatedly(Return(MoqtTrackStatusCode::kNotYetBegun)); MoqtObjectListener* subscription = MoqtSessionPeer::AddSubscription(&session_, track, 0, 14, 0, 0); EXPECT_CALL(mock_session_, CanOpenNextOutgoingUnidirectionalStream()) .WillOnce(Return(false)) .WillOnce(Return(false)) .WillOnce(Return(false)); EXPECT_CALL(*track, GetTrackStatus()) .WillRepeatedly(Return(MoqtTrackStatusCode::kInProgress)); subscription->OnNewObjectAvailable(FullSequence(1, 0)); subscription->OnNewObjectAvailable(FullSequence(0, 0)); subscription->OnNewObjectAvailable(FullSequence(2, 0)); EXPECT_CALL(mock_session_, CanOpenNextOutgoingUnidirectionalStream()) .WillRepeatedly(Return(true)); webtransport::test::MockStream mock_stream0, mock_stream1, mock_stream2; EXPECT_CALL(mock_session_, OpenOutgoingUnidirectionalStream()) .WillOnce(Return(&mock_stream0)) .WillOnce(Return(&mock_stream1)) .WillOnce(Return(&mock_stream2)); std::unique_ptr<webtransport::StreamVisitor> stream_visitor[3]; EXPECT_CALL(mock_stream0, SetVisitor(_)) .WillOnce([&](std::unique_ptr<webtransport::StreamVisitor> visitor) { stream_visitor[0] = std::move(visitor); }); EXPECT_CALL(mock_stream1, SetVisitor(_)) .WillOnce([&](std::unique_ptr<webtransport::StreamVisitor> visitor) { stream_visitor[1] = std::move(visitor); }); EXPECT_CALL(mock_stream2, SetVisitor(_)) .WillOnce([&](std::unique_ptr<webtransport::StreamVisitor> visitor) { stream_visitor[2] = std::move(visitor); }); EXPECT_CALL(mock_stream0, GetStreamId()).WillRepeatedly(Return(0)); EXPECT_CALL(mock_stream1, GetStreamId()).WillRepeatedly(Return(1)); EXPECT_CALL(mock_stream2, GetStreamId()).WillRepeatedly(Return(2)); EXPECT_CALL(mock_stream0, visitor()).WillOnce([&]() { return stream_visitor[0].get(); }); EXPECT_CALL(mock_stream1, visitor()).WillOnce([&]() { return stream_visitor[1].get(); }); EXPECT_CALL(mock_stream2, visitor()).WillOnce([&]() { return stream_visitor[2].get(); }); EXPECT_CALL(*track, GetCachedObject(FullSequence(0, 0))) .WillOnce( Return(PublishedObject{FullSequence(0, 0), MoqtObjectStatus::kNormal, MemSliceFromString("deadbeef")})); EXPECT_CALL(*track, GetCachedObject(FullSequence(0, 1))) .WillOnce(Return(std::nullopt)); EXPECT_CALL(*track, GetCachedObject(FullSequence(1, 0))) .WillOnce( Return(PublishedObject{FullSequence(1, 0), MoqtObjectStatus::kNormal, MemSliceFromString("deadbeef")})); EXPECT_CALL(*track, GetCachedObject(FullSequence(1, 1))) .WillOnce(Return(std::nullopt)); EXPECT_CALL(*track, GetCachedObject(FullSequence(2, 0))) .WillOnce( Return(PublishedObject{FullSequence(2, 0), MoqtObjectStatus::kNormal, MemSliceFromString("deadbeef")})); EXPECT_CALL(*track, GetCachedObject(FullSequence(2, 1))) .WillOnce(Return(std::nullopt)); EXPECT_CALL(mock_stream0, CanWrite()).WillRepeatedly(Return(true)); EXPECT_CALL(mock_stream1, CanWrite()).WillRepeatedly(Return(true)); EXPECT_CALL(mock_stream2, CanWrite()).WillRepeatedly(Return(true)); EXPECT_CALL(mock_stream0, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { EXPECT_EQ(static_cast<const uint8_t>(data[0][4]), 0); return absl::OkStatus(); }); EXPECT_CALL(mock_stream1, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { EXPECT_EQ(static_cast<const uint8_t>(data[0][3]), 1); return absl::OkStatus(); }); EXPECT_CALL(mock_stream2, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { EXPECT_EQ(static_cast<const uint8_t>(data[0][3]), 2); return absl::OkStatus(); }); session_.OnCanCreateNewOutgoingUnidirectionalStream(); } TEST_F(MoqtSessionTest, StreamQueuedForSubscriptionThatDoesntExist) { FullTrackName ftn("foo", "bar"); auto track = SetupPublisher(ftn, MoqtForwardingPreference::kSubgroup, FullSequence(0, 0)); EXPECT_CALL(*track, GetTrackStatus()) .WillRepeatedly(Return(MoqtTrackStatusCode::kNotYetBegun)); MoqtObjectListener* subscription = MoqtSessionPeer::AddSubscription(&session_, track, 0, 14, 0, 0); EXPECT_CALL(mock_session_, CanOpenNextOutgoingUnidirectionalStream()) .WillOnce(Return(false)); EXPECT_CALL(*track, GetTrackStatus()) .WillRepeatedly(Return(MoqtTrackStatusCode::kInProgress)); subscription->OnNewObjectAvailable(FullSequence(0, 0)); MoqtSessionPeer::DeleteSubscription(&session_, 0); EXPECT_CALL(mock_session_, CanOpenNextOutgoingUnidirectionalStream()) .WillRepeatedly(Return(true)); EXPECT_CALL(mock_session_, OpenOutgoingUnidirectionalStream()).Times(0); session_.OnCanCreateNewOutgoingUnidirectionalStream(); } TEST_F(MoqtSessionTest, QueuedStreamPriorityChanged) { FullTrackName ftn("foo", "bar"); auto track = SetupPublisher(ftn, MoqtForwardingPreference::kSubgroup, FullSequence(0, 0)); EXPECT_CALL(*track, GetTrackStatus()) .WillRepeatedly(Return(MoqtTrackStatusCode::kNotYetBegun)); MoqtObjectListener* subscription0 = MoqtSessionPeer::AddSubscription(&session_, track, 0, 14, 0, 0); MoqtObjectListener* subscription1 = MoqtSessionPeer::AddSubscription(&session_, track, 1, 14, 0, 0); MoqtSessionPeer::UpdateSubscriberPriority(&session_, 0, 1); MoqtSessionPeer::UpdateSubscriberPriority(&session_, 1, 2); EXPECT_CALL(mock_session_, CanOpenNextOutgoingUnidirectionalStream()) .WillOnce(Return(false)) .WillOnce(Return(false)) .WillOnce(Return(false)) .WillOnce(Return(false)); EXPECT_CALL(*track, GetTrackStatus()) .WillRepeatedly(Return(MoqtTrackStatusCode::kInProgress)); subscription0->OnNewObjectAvailable(FullSequence(0, 0)); subscription1->OnNewObjectAvailable(FullSequence(0, 0)); subscription0->OnNewObjectAvailable(FullSequence(1, 0)); subscription1->OnNewObjectAvailable(FullSequence(1, 0)); EXPECT_CALL(mock_session_, CanOpenNextOutgoingUnidirectionalStream()) .WillOnce(Return(true)) .WillOnce(Return(false)); webtransport::test::MockStream mock_stream0; EXPECT_CALL(mock_session_, OpenOutgoingUnidirectionalStream()) .WillOnce(Return(&mock_stream0)); std::unique_ptr<webtransport::StreamVisitor> stream_visitor0; EXPECT_CALL(mock_stream0, SetVisitor(_)) .WillOnce([&](std::unique_ptr<webtransport::StreamVisitor> visitor) { stream_visitor0 = std::move(visitor); }); EXPECT_CALL(mock_stream0, GetStreamId()).WillRepeatedly(Return(0)); EXPECT_CALL(mock_stream0, visitor()).WillOnce([&]() { return stream_visitor0.get(); }); EXPECT_CALL(*track, GetCachedObject(FullSequence(0, 0))) .WillOnce( Return(PublishedObject{FullSequence(0, 0), MoqtObjectStatus::kNormal, MemSliceFromString("deadbeef")})); EXPECT_CALL(*track, GetCachedObject(FullSequence(0, 1))) .WillOnce(Return(std::nullopt)); EXPECT_CALL(mock_stream0, CanWrite()).WillRepeatedly(Return(true)); EXPECT_CALL(mock_stream0, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { EXPECT_EQ(static_cast<const uint8_t>(data[0][1]), 0); EXPECT_EQ(static_cast<const uint8_t>(data[0][3]), 0); return absl::OkStatus(); }); session_.OnCanCreateNewOutgoingUnidirectionalStream(); MoqtSessionPeer::UpdateSubscriberPriority(&session_, 1, 0); EXPECT_CALL(mock_session_, CanOpenNextOutgoingUnidirectionalStream()) .WillOnce(Return(true)) .WillRepeatedly(Return(false)); webtransport::test::MockStream mock_stream1; EXPECT_CALL(mock_session_, OpenOutgoingUnidirectionalStream()) .WillOnce(Return(&mock_stream1)); std::unique_ptr<webtransport::StreamVisitor> stream_visitor1; EXPECT_CALL(mock_stream1, SetVisitor(_)) .WillOnce([&](std::unique_ptr<webtransport::StreamVisitor> visitor) { stream_visitor1 = std::move(visitor); }); EXPECT_CALL(mock_stream1, GetStreamId()).WillRepeatedly(Return(1)); EXPECT_CALL(mock_stream1, visitor()).WillOnce([&]() { return stream_visitor1.get(); }); EXPECT_CALL(*track, GetCachedObject(FullSequence(0, 0))) .WillOnce( Return(PublishedObject{FullSequence(0, 0), MoqtObjectStatus::kNormal, MemSliceFromString("deadbeef")})); EXPECT_CALL(*track, GetCachedObject(FullSequence(0, 1))) .WillOnce(Return(std::nullopt)); EXPECT_CALL(mock_stream1, CanWrite()).WillRepeatedly(Return(true)); EXPECT_CALL(mock_stream1, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { EXPECT_EQ(static_cast<const uint8_t>(data[0][1]), 1); EXPECT_EQ(static_cast<const uint8_t>(data[0][3]), 0); return absl::OkStatus(); }); session_.OnCanCreateNewOutgoingUnidirectionalStream(); } #if 0 TEST_F(MoqtSessionTest, SubscribeUpdateClosesSubscription) { MoqtSessionPeer::set_peer_role(&session_, MoqtRole::kSubscriber); FullTrackName ftn("foo", "bar"); MockLocalTrackVisitor track_visitor; session_.AddLocalTrack(ftn, MoqtForwardingPreference::kTrack, &track_visitor); MoqtSessionPeer::AddSubscription(&session_, ftn, 0, 2, 5, 0); LocalTrack* track = MoqtSessionPeer::local_track(&session_, ftn); track->GetWindow(0)->OnObjectSent(FullSequence(7, 3), MoqtObjectStatus::kNormal); MoqtSubscribeUpdate update = { 0, 5, 0, 7, 3, }; webtransport::test::MockStream mock_stream; std::unique_ptr<MoqtParserVisitor> stream_input = MoqtSessionPeer::CreateControlStream(&session_, &mock_stream); EXPECT_CALL(mock_session_, GetStreamById(4)).WillOnce(Return(&mock_stream)); bool correct_message = false; EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kSubscribeDone); return absl::OkStatus(); }); stream_input->OnSubscribeUpdateMessage(update); EXPECT_TRUE(correct_message); EXPECT_FALSE(session_.HasSubscribers(ftn)); } #endif } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/moqt/moqt_session.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/moqt/moqt_session_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
425fa5d4-497e-4204-bc74-7cc44ccb33de
cpp
google/quiche
moqt_track
quiche/quic/moqt/moqt_track.cc
quiche/quic/moqt/moqt_track_test.cc
#include "quiche/quic/moqt/moqt_track.h" #include <cstdint> #include "quiche/quic/moqt/moqt_messages.h" namespace moqt { bool RemoteTrack::CheckForwardingPreference( MoqtForwardingPreference preference) { if (forwarding_preference_.has_value()) { return forwarding_preference_.value() == preference; } forwarding_preference_ = preference; return true; } }
#include "quiche/quic/moqt/moqt_track.h" #include "quiche/quic/moqt/tools/moqt_mock_visitor.h" #include "quiche/quic/platform/api/quic_test.h" namespace moqt { namespace test { class RemoteTrackTest : public quic::test::QuicTest { public: RemoteTrackTest() : track_(FullTrackName("foo", "bar"), 5, &visitor_) {} RemoteTrack track_; MockRemoteTrackVisitor visitor_; }; TEST_F(RemoteTrackTest, Queries) { EXPECT_EQ(track_.full_track_name(), FullTrackName("foo", "bar")); EXPECT_EQ(track_.track_alias(), 5); EXPECT_EQ(track_.visitor(), &visitor_); } TEST_F(RemoteTrackTest, UpdateForwardingPreference) { EXPECT_TRUE( track_.CheckForwardingPreference(MoqtForwardingPreference::kSubgroup)); EXPECT_TRUE( track_.CheckForwardingPreference(MoqtForwardingPreference::kSubgroup)); EXPECT_FALSE( track_.CheckForwardingPreference(MoqtForwardingPreference::kDatagram)); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/moqt/moqt_track.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/moqt/moqt_track_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
06490826-6436-4241-9bda-1a6e2a05efe0
cpp
google/quiche
moqt_live_relay_queue
quiche/quic/moqt/moqt_live_relay_queue.cc
quiche/quic/moqt/moqt_live_relay_queue_test.cc
#include "quiche/quic/moqt/moqt_live_relay_queue.h" #include <cstdint> #include <memory> #include <optional> #include <tuple> #include <vector> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "quiche/quic/moqt/moqt_cached_object.h" #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/quic/moqt/moqt_publisher.h" #include "quiche/quic/moqt/moqt_subscribe_windows.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_mem_slice.h" #include "quiche/common/quiche_buffer_allocator.h" #include "quiche/common/simple_buffer_allocator.h" namespace moqt { bool MoqtLiveRelayQueue::AddObject(uint64_t group_id, uint64_t object_id, MoqtObjectStatus status, absl::string_view object) { if (queue_.size() == kMaxQueuedGroups) { if (queue_.begin()->first > group_id) { QUICHE_DLOG(INFO) << "Skipping object from group " << group_id << " because it is too old."; return true; } if (queue_.find(group_id) == queue_.end()) { queue_.erase(queue_.begin()); } } QUICHE_CHECK(status == MoqtObjectStatus::kNormal || object.empty()); return AddRawObject(FullSequence{group_id, object_id}, status, object); } std::tuple<uint64_t, bool> MoqtLiveRelayQueue::NextObject(Group& group) const { auto it = group.rbegin(); if (it == group.rend()) { return std::tuple<uint64_t, bool>(0, false); } return std::tuple<uint64_t, bool>( it->second.sequence.object + 1, (it->second.status == MoqtObjectStatus::kEndOfGroup || it->second.status == MoqtObjectStatus::kGroupDoesNotExist || it->second.status == MoqtObjectStatus::kEndOfTrack)); } bool MoqtLiveRelayQueue::AddRawObject(FullSequence sequence, MoqtObjectStatus status, absl::string_view payload) { if (end_of_track_.has_value() && sequence > *end_of_track_) { QUICHE_DLOG(INFO) << "Skipping object because it is after the end of the " << "track"; return false; } if (status == MoqtObjectStatus::kEndOfTrack) { if (sequence < next_sequence_) { QUICHE_DLOG(INFO) << "EndOfTrack is too early."; return false; } end_of_track_ = sequence; } if (status == MoqtObjectStatus::kGroupDoesNotExist && sequence.object > 0) { QUICHE_DLOG(INFO) << "GroupDoesNotExist is not the last object in the " << "group"; return false; } auto group_it = queue_.try_emplace(sequence.group); if (!group_it.second) { auto [next_object_id, is_the_end] = NextObject(group_it.first->second); if (next_object_id <= sequence.object && is_the_end) { QUICHE_DLOG(INFO) << "Skipping object because it is after the end of the " << "group"; return false; } if (status == MoqtObjectStatus::kEndOfGroup && sequence.object < next_object_id) { QUICHE_DLOG(INFO) << "Skipping EndOfGroup because it is not the last " << "object in the group."; return false; } } if (next_sequence_ <= sequence) { next_sequence_ = FullSequence{sequence.group, sequence.object + 1}; } std::shared_ptr<quiche::QuicheMemSlice> slice = payload.empty() ? nullptr : std::make_shared<quiche::QuicheMemSlice>(quiche::QuicheBuffer::Copy( quiche::SimpleBufferAllocator::Get(), payload)); auto object_it = group_it.first->second.try_emplace(sequence.object, sequence, status, slice); if (!object_it.second) { QUICHE_DLOG(ERROR) << "Sender is overwriting an existing object."; return false; } for (MoqtObjectListener* listener : listeners_) { listener->OnNewObjectAvailable(sequence); } return true; } std::optional<PublishedObject> MoqtLiveRelayQueue::GetCachedObject( FullSequence sequence) const { auto group_it = queue_.find(sequence.group); if (group_it == queue_.end()) { return std::nullopt; } auto object_it = group_it->second.find(sequence.object); if (object_it == group_it->second.end()) { return std::nullopt; } return CachedObjectToPublishedObject(object_it->second); } std::vector<FullSequence> MoqtLiveRelayQueue::GetCachedObjectsInRange( FullSequence start, FullSequence end) const { std::vector<FullSequence> sequences; SubscribeWindow window(start, end); for (auto& group_it : queue_) { for (auto& object_it : group_it.second) { if (window.InWindow(object_it.second.sequence)) { sequences.push_back(object_it.second.sequence); } } } return sequences; } absl::StatusOr<MoqtTrackStatusCode> MoqtLiveRelayQueue::GetTrackStatus() const { if (end_of_track_.has_value()) { return MoqtTrackStatusCode::kFinished; } if (queue_.empty()) { return MoqtTrackStatusCode::kNotYetBegun; } return MoqtTrackStatusCode::kInProgress; } FullSequence MoqtLiveRelayQueue::GetLargestSequence() const { return FullSequence{next_sequence_.group, next_sequence_.object - 1}; } }
#include "quiche/quic/moqt/moqt_live_relay_queue.h" #include <cstdint> #include <optional> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/quic/moqt/moqt_publisher.h" #include "quiche/quic/moqt/moqt_subscribe_windows.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" namespace moqt::test { namespace { class TestMoqtLiveRelayQueue : public MoqtLiveRelayQueue, public MoqtObjectListener { public: TestMoqtLiveRelayQueue() : MoqtLiveRelayQueue(FullTrackName{"test", "track"}, MoqtForwardingPreference::kSubgroup) { AddObjectListener(this); } void OnNewObjectAvailable(FullSequence sequence) { std::optional<PublishedObject> object = GetCachedObject(sequence); QUICHE_CHECK(object.has_value()); switch (object->status) { case MoqtObjectStatus::kNormal: PublishObject(object->sequence.group, object->sequence.object, object->payload.AsStringView()); break; case MoqtObjectStatus::kObjectDoesNotExist: SkipObject(object->sequence.group, object->sequence.object); break; case MoqtObjectStatus::kGroupDoesNotExist: SkipGroup(object->sequence.group); break; case MoqtObjectStatus::kEndOfGroup: CloseStreamForGroup(object->sequence.group); break; case MoqtObjectStatus::kEndOfTrack: CloseTrack(); break; default: EXPECT_TRUE(false); } } void CallSubscribeForPast(const SubscribeWindow& window) { std::vector<FullSequence> objects = GetCachedObjectsInRange(FullSequence(0, 0), GetLargestSequence()); for (FullSequence object : objects) { if (window.InWindow(object)) { OnNewObjectAvailable(object); } } } MOCK_METHOD(void, CloseStreamForGroup, (uint64_t group_id), ()); MOCK_METHOD(void, PublishObject, (uint64_t group_id, uint64_t object_id, absl::string_view payload), ()); MOCK_METHOD(void, SkipObject, (uint64_t group_id, uint64_t object_id), ()); MOCK_METHOD(void, SkipGroup, (uint64_t group_id), ()); MOCK_METHOD(void, CloseTrack, (), ()); }; TEST(MoqtLiveRelayQueue, SingleGroup) { TestMoqtLiveRelayQueue queue; { testing::InSequence seq; EXPECT_CALL(queue, PublishObject(0, 0, "a")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, PublishObject(0, 2, "c")); EXPECT_CALL(queue, CloseStreamForGroup(0)); } EXPECT_TRUE(queue.AddObject(0, 0, MoqtObjectStatus::kNormal, "a")); EXPECT_TRUE(queue.AddObject(0, 1, MoqtObjectStatus::kNormal, "b")); EXPECT_TRUE(queue.AddObject(0, 2, MoqtObjectStatus::kNormal, "c")); EXPECT_TRUE(queue.AddObject(0, 3, MoqtObjectStatus::kEndOfGroup, "")); } TEST(MoqtLiveRelayQueue, SingleGroupPastSubscribeFromZero) { TestMoqtLiveRelayQueue queue; { testing::InSequence seq; EXPECT_CALL(queue, PublishObject(0, 0, "a")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, PublishObject(0, 2, "c")); EXPECT_CALL(queue, PublishObject(0, 0, "a")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, PublishObject(0, 2, "c")); } EXPECT_TRUE(queue.AddObject(0, 0, MoqtObjectStatus::kNormal, "a")); EXPECT_TRUE(queue.AddObject(0, 1, MoqtObjectStatus::kNormal, "b")); EXPECT_TRUE(queue.AddObject(0, 2, MoqtObjectStatus::kNormal, "c")); queue.CallSubscribeForPast(SubscribeWindow(0, 0)); } TEST(MoqtLiveRelayQueue, SingleGroupPastSubscribeFromMidGroup) { TestMoqtLiveRelayQueue queue; { testing::InSequence seq; EXPECT_CALL(queue, PublishObject(0, 0, "a")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, PublishObject(0, 2, "c")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, PublishObject(0, 2, "c")); } EXPECT_TRUE(queue.AddObject(0, 0, MoqtObjectStatus::kNormal, "a")); EXPECT_TRUE(queue.AddObject(0, 1, MoqtObjectStatus::kNormal, "b")); EXPECT_TRUE(queue.AddObject(0, 2, MoqtObjectStatus::kNormal, "c")); queue.CallSubscribeForPast(SubscribeWindow(0, 1)); } TEST(MoqtLiveRelayQueue, TwoGroups) { TestMoqtLiveRelayQueue queue; { testing::InSequence seq; EXPECT_CALL(queue, PublishObject(0, 0, "a")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, PublishObject(0, 2, "c")); EXPECT_CALL(queue, CloseStreamForGroup(0)); EXPECT_CALL(queue, PublishObject(1, 0, "d")); EXPECT_CALL(queue, PublishObject(1, 1, "e")); EXPECT_CALL(queue, PublishObject(1, 2, "f")); } EXPECT_TRUE(queue.AddObject(0, 0, MoqtObjectStatus::kNormal, "a")); EXPECT_TRUE(queue.AddObject(0, 1, MoqtObjectStatus::kNormal, "b")); EXPECT_TRUE(queue.AddObject(0, 2, MoqtObjectStatus::kNormal, "c")); EXPECT_TRUE(queue.AddObject(0, 3, MoqtObjectStatus::kEndOfGroup, "")); EXPECT_TRUE(queue.AddObject(1, 0, MoqtObjectStatus::kNormal, "d")); EXPECT_TRUE(queue.AddObject(1, 1, MoqtObjectStatus::kNormal, "e")); EXPECT_TRUE(queue.AddObject(1, 2, MoqtObjectStatus::kNormal, "f")); } TEST(MoqtLiveRelayQueue, TwoGroupsPastSubscribe) { TestMoqtLiveRelayQueue queue; { testing::InSequence seq; EXPECT_CALL(queue, PublishObject(0, 0, "a")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, PublishObject(0, 2, "c")); EXPECT_CALL(queue, CloseStreamForGroup(0)); EXPECT_CALL(queue, PublishObject(1, 0, "d")); EXPECT_CALL(queue, PublishObject(1, 1, "e")); EXPECT_CALL(queue, PublishObject(1, 2, "f")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, PublishObject(0, 2, "c")); EXPECT_CALL(queue, CloseStreamForGroup(0)); EXPECT_CALL(queue, PublishObject(1, 0, "d")); EXPECT_CALL(queue, PublishObject(1, 1, "e")); EXPECT_CALL(queue, PublishObject(1, 2, "f")); } EXPECT_TRUE(queue.AddObject(0, 0, MoqtObjectStatus::kNormal, "a")); EXPECT_TRUE(queue.AddObject(0, 1, MoqtObjectStatus::kNormal, "b")); EXPECT_TRUE(queue.AddObject(0, 2, MoqtObjectStatus::kNormal, "c")); EXPECT_TRUE(queue.AddObject(0, 3, MoqtObjectStatus::kEndOfGroup, "")); EXPECT_TRUE(queue.AddObject(1, 0, MoqtObjectStatus::kNormal, "d")); EXPECT_TRUE(queue.AddObject(1, 1, MoqtObjectStatus::kNormal, "e")); EXPECT_TRUE(queue.AddObject(1, 2, MoqtObjectStatus::kNormal, "f")); queue.CallSubscribeForPast(SubscribeWindow(0, 1)); } TEST(MoqtLiveRelayQueue, FiveGroups) { TestMoqtLiveRelayQueue queue; ; { testing::InSequence seq; EXPECT_CALL(queue, PublishObject(0, 0, "a")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, CloseStreamForGroup(0)); EXPECT_CALL(queue, PublishObject(1, 0, "c")); EXPECT_CALL(queue, PublishObject(1, 1, "d")); EXPECT_CALL(queue, CloseStreamForGroup(1)); EXPECT_CALL(queue, PublishObject(2, 0, "e")); EXPECT_CALL(queue, PublishObject(2, 1, "f")); EXPECT_CALL(queue, CloseStreamForGroup(2)); EXPECT_CALL(queue, PublishObject(3, 0, "g")); EXPECT_CALL(queue, PublishObject(3, 1, "h")); EXPECT_CALL(queue, CloseStreamForGroup(3)); EXPECT_CALL(queue, PublishObject(4, 0, "i")); EXPECT_CALL(queue, PublishObject(4, 1, "j")); } EXPECT_TRUE(queue.AddObject(0, 0, MoqtObjectStatus::kNormal, "a")); EXPECT_TRUE(queue.AddObject(0, 1, MoqtObjectStatus::kNormal, "b")); EXPECT_TRUE(queue.AddObject(0, 2, MoqtObjectStatus::kEndOfGroup, "")); EXPECT_TRUE(queue.AddObject(1, 0, MoqtObjectStatus::kNormal, "c")); EXPECT_TRUE(queue.AddObject(1, 1, MoqtObjectStatus::kNormal, "d")); EXPECT_TRUE(queue.AddObject(1, 2, MoqtObjectStatus::kEndOfGroup, "")); EXPECT_TRUE(queue.AddObject(2, 0, MoqtObjectStatus::kNormal, "e")); EXPECT_TRUE(queue.AddObject(2, 1, MoqtObjectStatus::kNormal, "f")); EXPECT_TRUE(queue.AddObject(2, 2, MoqtObjectStatus::kEndOfGroup, "")); EXPECT_TRUE(queue.AddObject(3, 0, MoqtObjectStatus::kNormal, "g")); EXPECT_TRUE(queue.AddObject(3, 1, MoqtObjectStatus::kNormal, "h")); EXPECT_TRUE(queue.AddObject(3, 2, MoqtObjectStatus::kEndOfGroup, "")); EXPECT_TRUE(queue.AddObject(4, 0, MoqtObjectStatus::kNormal, "i")); EXPECT_TRUE(queue.AddObject(4, 1, MoqtObjectStatus::kNormal, "j")); } TEST(MoqtLiveRelayQueue, FiveGroupsPastSubscribe) { TestMoqtLiveRelayQueue queue; { testing::InSequence seq; EXPECT_CALL(queue, PublishObject(0, 0, "a")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, CloseStreamForGroup(0)); EXPECT_CALL(queue, PublishObject(1, 0, "c")); EXPECT_CALL(queue, PublishObject(1, 1, "d")); EXPECT_CALL(queue, CloseStreamForGroup(1)); EXPECT_CALL(queue, PublishObject(2, 0, "e")); EXPECT_CALL(queue, PublishObject(2, 1, "f")); EXPECT_CALL(queue, CloseStreamForGroup(2)); EXPECT_CALL(queue, PublishObject(3, 0, "g")); EXPECT_CALL(queue, PublishObject(3, 1, "h")); EXPECT_CALL(queue, CloseStreamForGroup(3)); EXPECT_CALL(queue, PublishObject(4, 0, "i")); EXPECT_CALL(queue, PublishObject(4, 1, "j")); EXPECT_CALL(queue, PublishObject(2, 0, "e")); EXPECT_CALL(queue, PublishObject(2, 1, "f")); EXPECT_CALL(queue, CloseStreamForGroup(2)); EXPECT_CALL(queue, PublishObject(3, 0, "g")); EXPECT_CALL(queue, PublishObject(3, 1, "h")); EXPECT_CALL(queue, CloseStreamForGroup(3)); EXPECT_CALL(queue, PublishObject(4, 0, "i")); EXPECT_CALL(queue, PublishObject(4, 1, "j")); } EXPECT_TRUE(queue.AddObject(0, 0, MoqtObjectStatus::kNormal, "a")); EXPECT_TRUE(queue.AddObject(0, 1, MoqtObjectStatus::kNormal, "b")); EXPECT_TRUE(queue.AddObject(0, 2, MoqtObjectStatus::kEndOfGroup, "")); EXPECT_TRUE(queue.AddObject(1, 0, MoqtObjectStatus::kNormal, "c")); EXPECT_TRUE(queue.AddObject(1, 1, MoqtObjectStatus::kNormal, "d")); EXPECT_TRUE(queue.AddObject(1, 2, MoqtObjectStatus::kEndOfGroup, "")); EXPECT_TRUE(queue.AddObject(2, 0, MoqtObjectStatus::kNormal, "e")); EXPECT_TRUE(queue.AddObject(2, 1, MoqtObjectStatus::kNormal, "f")); EXPECT_TRUE(queue.AddObject(2, 2, MoqtObjectStatus::kEndOfGroup, "")); EXPECT_TRUE(queue.AddObject(3, 0, MoqtObjectStatus::kNormal, "g")); EXPECT_TRUE(queue.AddObject(3, 1, MoqtObjectStatus::kNormal, "h")); EXPECT_TRUE(queue.AddObject(3, 2, MoqtObjectStatus::kEndOfGroup, "")); EXPECT_TRUE(queue.AddObject(4, 0, MoqtObjectStatus::kNormal, "i")); EXPECT_TRUE(queue.AddObject(4, 1, MoqtObjectStatus::kNormal, "j")); queue.CallSubscribeForPast(SubscribeWindow(0, 0)); } TEST(MoqtLiveRelayQueue, FiveGroupsPastSubscribeFromMidGroup) { TestMoqtLiveRelayQueue queue; { testing::InSequence seq; EXPECT_CALL(queue, PublishObject(0, 0, "a")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, PublishObject(1, 0, "c")); EXPECT_CALL(queue, PublishObject(1, 1, "d")); EXPECT_CALL(queue, CloseStreamForGroup(1)); EXPECT_CALL(queue, PublishObject(2, 0, "e")); EXPECT_CALL(queue, PublishObject(2, 1, "f")); EXPECT_CALL(queue, CloseStreamForGroup(2)); EXPECT_CALL(queue, PublishObject(3, 0, "g")); EXPECT_CALL(queue, PublishObject(3, 1, "h")); EXPECT_CALL(queue, CloseStreamForGroup(3)); EXPECT_CALL(queue, PublishObject(4, 0, "i")); EXPECT_CALL(queue, PublishObject(4, 1, "j")); } EXPECT_TRUE(queue.AddObject(0, 0, MoqtObjectStatus::kNormal, "a")); EXPECT_TRUE(queue.AddObject(0, 1, MoqtObjectStatus::kNormal, "b")); EXPECT_TRUE(queue.AddObject(1, 0, MoqtObjectStatus::kNormal, "c")); EXPECT_TRUE(queue.AddObject(1, 1, MoqtObjectStatus::kNormal, "d")); EXPECT_TRUE(queue.AddObject(1, 2, MoqtObjectStatus::kEndOfGroup, "")); EXPECT_TRUE(queue.AddObject(2, 0, MoqtObjectStatus::kNormal, "e")); EXPECT_TRUE(queue.AddObject(2, 1, MoqtObjectStatus::kNormal, "f")); EXPECT_TRUE(queue.AddObject(2, 2, MoqtObjectStatus::kEndOfGroup, "")); EXPECT_TRUE(queue.AddObject(3, 0, MoqtObjectStatus::kNormal, "g")); EXPECT_TRUE(queue.AddObject(3, 1, MoqtObjectStatus::kNormal, "h")); EXPECT_TRUE(queue.AddObject(3, 2, MoqtObjectStatus::kEndOfGroup, "")); EXPECT_TRUE(queue.AddObject(4, 0, MoqtObjectStatus::kNormal, "i")); EXPECT_TRUE(queue.AddObject(4, 1, MoqtObjectStatus::kNormal, "j")); EXPECT_TRUE(queue.AddObject(0, 2, MoqtObjectStatus::kEndOfGroup, "")); } TEST(MoqtLiveRelayQueue, EndOfTrack) { TestMoqtLiveRelayQueue queue; { testing::InSequence seq; EXPECT_CALL(queue, PublishObject(0, 0, "a")); EXPECT_CALL(queue, PublishObject(0, 2, "c")); EXPECT_CALL(queue, CloseTrack()); } EXPECT_TRUE(queue.AddObject(0, 0, MoqtObjectStatus::kNormal, "a")); EXPECT_TRUE(queue.AddObject(0, 2, MoqtObjectStatus::kNormal, "c")); EXPECT_FALSE(queue.AddObject(0, 1, MoqtObjectStatus::kEndOfTrack, "")); EXPECT_TRUE(queue.AddObject(0, 3, MoqtObjectStatus::kEndOfTrack, "")); } TEST(MoqtLiveRelayQueue, EndOfGroup) { TestMoqtLiveRelayQueue queue; { testing::InSequence seq; EXPECT_CALL(queue, PublishObject(0, 0, "a")); EXPECT_CALL(queue, PublishObject(0, 2, "c")); EXPECT_CALL(queue, CloseStreamForGroup(0)); } EXPECT_TRUE(queue.AddObject(0, 0, MoqtObjectStatus::kNormal, "a")); EXPECT_TRUE(queue.AddObject(0, 2, MoqtObjectStatus::kNormal, "c")); EXPECT_FALSE(queue.AddObject(0, 1, MoqtObjectStatus::kEndOfGroup, "")); EXPECT_TRUE(queue.AddObject(0, 3, MoqtObjectStatus::kEndOfGroup, "")); EXPECT_FALSE(queue.AddObject(0, 4, MoqtObjectStatus::kNormal, "e")); } TEST(MoqtLiveRelayQueue, GroupDoesNotExist) { TestMoqtLiveRelayQueue queue; { testing::InSequence seq; EXPECT_CALL(queue, SkipGroup(0)); } EXPECT_FALSE(queue.AddObject(0, 1, MoqtObjectStatus::kGroupDoesNotExist, "")); EXPECT_TRUE(queue.AddObject(0, 0, MoqtObjectStatus::kGroupDoesNotExist, "")); } TEST(MoqtLiveRelayQueue, OverwriteObject) { TestMoqtLiveRelayQueue queue; { testing::InSequence seq; EXPECT_CALL(queue, PublishObject(0, 0, "a")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, PublishObject(0, 2, "c")); } EXPECT_TRUE(queue.AddObject(0, 0, MoqtObjectStatus::kNormal, "a")); EXPECT_TRUE(queue.AddObject(0, 1, MoqtObjectStatus::kNormal, "b")); EXPECT_TRUE(queue.AddObject(0, 2, MoqtObjectStatus::kNormal, "c")); EXPECT_TRUE(queue.AddObject(0, 3, MoqtObjectStatus::kEndOfGroup, "")); EXPECT_FALSE(queue.AddObject(0, 1, MoqtObjectStatus::kNormal, "invalid")); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/moqt/moqt_live_relay_queue.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/moqt/moqt_live_relay_queue_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
a89dbaf3-8d69-492f-b61a-85d389447364
cpp
google/quiche
moqt_parser
quiche/quic/moqt/moqt_parser.cc
quiche/quic/moqt/moqt_parser_test.cc
#include "quiche/quic/moqt/moqt_parser.h" #include <array> #include <cstddef> #include <cstdint> #include <cstring> #include <optional> #include <string> #include "absl/cleanup/cleanup.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_data_reader.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/quic/moqt/moqt_priority.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" namespace moqt { namespace { bool ParseDeliveryOrder(uint8_t raw_value, std::optional<MoqtDeliveryOrder>& output) { switch (raw_value) { case 0x00: output = std::nullopt; return true; case 0x01: output = MoqtDeliveryOrder::kAscending; return true; case 0x02: output = MoqtDeliveryOrder::kDescending; return true; default: return false; } } uint64_t SignedVarintUnserializedForm(uint64_t value) { if (value & 0x01) { return -(value >> 1); } return value >> 1; } bool IsAllowedStreamType(uint64_t value) { constexpr std::array kAllowedStreamTypes = { MoqtDataStreamType::kStreamHeaderSubgroup, MoqtDataStreamType::kStreamHeaderTrack, MoqtDataStreamType::kPadding}; for (MoqtDataStreamType type : kAllowedStreamTypes) { if (static_cast<uint64_t>(type) == value) { return true; } } return false; } size_t ParseObjectHeader(quic::QuicDataReader& reader, MoqtObject& object, MoqtDataStreamType type) { if (!reader.ReadVarInt62(&object.subscribe_id) || !reader.ReadVarInt62(&object.track_alias)) { return 0; } if (type != MoqtDataStreamType::kStreamHeaderTrack && !reader.ReadVarInt62(&object.group_id)) { return 0; } if (type == MoqtDataStreamType::kStreamHeaderSubgroup) { uint64_t subgroup_id; if (!reader.ReadVarInt62(&subgroup_id)) { return 0; } object.subgroup_id = subgroup_id; } if (type == MoqtDataStreamType::kObjectDatagram && !reader.ReadVarInt62(&object.object_id)) { return 0; } if (!reader.ReadUInt8(&object.publisher_priority)) { return 0; } uint64_t status = static_cast<uint64_t>(MoqtObjectStatus::kNormal); if (type == MoqtDataStreamType::kObjectDatagram && (!reader.ReadVarInt62(&object.payload_length) || (object.payload_length == 0 && !reader.ReadVarInt62(&status)))) { return 0; } object.object_status = IntegerToObjectStatus(status); object.forwarding_preference = GetForwardingPreference(type); return reader.PreviouslyReadPayload().size(); } size_t ParseObjectSubheader(quic::QuicDataReader& reader, MoqtObject& object, MoqtDataStreamType type) { switch (type) { case MoqtDataStreamType::kStreamHeaderTrack: if (!reader.ReadVarInt62(&object.group_id)) { return 0; } [[fallthrough]]; case MoqtDataStreamType::kStreamHeaderSubgroup: { if (!reader.ReadVarInt62(&object.object_id) || !reader.ReadVarInt62(&object.payload_length)) { return 0; } uint64_t status = static_cast<uint64_t>(MoqtObjectStatus::kNormal); if (object.payload_length == 0 && !reader.ReadVarInt62(&status)) { return 0; } object.object_status = IntegerToObjectStatus(status); return reader.PreviouslyReadPayload().size(); } default: QUICHE_NOTREACHED(); return 0; } } } void MoqtControlParser::ProcessData(absl::string_view data, bool fin) { if (no_more_data_) { ParseError("Data after end of stream"); } if (processing_) { return; } processing_ = true; auto on_return = absl::MakeCleanup([&] { processing_ = false; }); if (fin) { no_more_data_ = true; if (!buffered_message_.empty() && data.empty()) { ParseError("End of stream before complete message"); return; } } std::optional<quic::QuicDataReader> reader = std::nullopt; size_t original_buffer_size = buffered_message_.size(); if (!buffered_message_.empty()) { absl::StrAppend(&buffered_message_, data); reader.emplace(buffered_message_); } else { reader.emplace(data); } size_t total_processed = 0; while (!reader->IsDoneReading()) { size_t message_len = ProcessMessage(reader->PeekRemainingPayload()); if (message_len == 0) { if (reader->BytesRemaining() > kMaxMessageHeaderSize) { ParseError(MoqtError::kInternalError, "Cannot parse non-OBJECT messages > 2KB"); return; } if (fin) { ParseError("FIN after incomplete message"); return; } if (buffered_message_.empty()) { absl::StrAppend(&buffered_message_, reader->PeekRemainingPayload()); } break; } total_processed += message_len; reader->Seek(message_len); } if (original_buffer_size > 0) { buffered_message_.erase(0, total_processed); } } size_t MoqtControlParser::ProcessMessage(absl::string_view data) { uint64_t value; quic::QuicDataReader reader(data); if (!reader.ReadVarInt62(&value)) { return 0; } auto type = static_cast<MoqtMessageType>(value); switch (type) { case MoqtMessageType::kClientSetup: return ProcessClientSetup(reader); case MoqtMessageType::kServerSetup: return ProcessServerSetup(reader); case MoqtMessageType::kSubscribe: return ProcessSubscribe(reader); case MoqtMessageType::kSubscribeOk: return ProcessSubscribeOk(reader); case MoqtMessageType::kSubscribeError: return ProcessSubscribeError(reader); case MoqtMessageType::kUnsubscribe: return ProcessUnsubscribe(reader); case MoqtMessageType::kSubscribeDone: return ProcessSubscribeDone(reader); case MoqtMessageType::kSubscribeUpdate: return ProcessSubscribeUpdate(reader); case MoqtMessageType::kAnnounce: return ProcessAnnounce(reader); case MoqtMessageType::kAnnounceOk: return ProcessAnnounceOk(reader); case MoqtMessageType::kAnnounceError: return ProcessAnnounceError(reader); case MoqtMessageType::kAnnounceCancel: return ProcessAnnounceCancel(reader); case MoqtMessageType::kTrackStatusRequest: return ProcessTrackStatusRequest(reader); case MoqtMessageType::kUnannounce: return ProcessUnannounce(reader); case MoqtMessageType::kTrackStatus: return ProcessTrackStatus(reader); case MoqtMessageType::kGoAway: return ProcessGoAway(reader); case MoqtMessageType::kSubscribeNamespace: return ProcessSubscribeNamespace(reader); case MoqtMessageType::kSubscribeNamespaceOk: return ProcessSubscribeNamespaceOk(reader); case MoqtMessageType::kSubscribeNamespaceError: return ProcessSubscribeNamespaceError(reader); case MoqtMessageType::kUnsubscribeNamespace: return ProcessUnsubscribeNamespace(reader); case MoqtMessageType::kMaxSubscribeId: return ProcessMaxSubscribeId(reader); case moqt::MoqtMessageType::kObjectAck: return ProcessObjectAck(reader); default: ParseError("Unknown message type"); } return 0; } size_t MoqtControlParser::ProcessClientSetup(quic::QuicDataReader& reader) { MoqtClientSetup setup; uint64_t number_of_supported_versions; if (!reader.ReadVarInt62(&number_of_supported_versions)) { return 0; } uint64_t version; for (uint64_t i = 0; i < number_of_supported_versions; ++i) { if (!reader.ReadVarInt62(&version)) { return 0; } setup.supported_versions.push_back(static_cast<MoqtVersion>(version)); } uint64_t num_params; if (!reader.ReadVarInt62(&num_params)) { return 0; } for (uint64_t i = 0; i < num_params; ++i) { uint64_t type; absl::string_view value; if (!ReadParameter(reader, type, value)) { return 0; } auto key = static_cast<MoqtSetupParameter>(type); switch (key) { case MoqtSetupParameter::kRole: if (setup.role.has_value()) { ParseError("ROLE parameter appears twice in SETUP"); return 0; } uint64_t index; if (!StringViewToVarInt(value, index)) { return 0; } if (index > static_cast<uint64_t>(MoqtRole::kRoleMax)) { ParseError("Invalid ROLE parameter"); return 0; } setup.role = static_cast<MoqtRole>(index); break; case MoqtSetupParameter::kPath: if (uses_web_transport_) { ParseError( "WebTransport connection is using PATH parameter in SETUP"); return 0; } if (setup.path.has_value()) { ParseError("PATH parameter appears twice in CLIENT_SETUP"); return 0; } setup.path = value; break; case MoqtSetupParameter::kMaxSubscribeId: if (setup.max_subscribe_id.has_value()) { ParseError("MAX_SUBSCRIBE_ID parameter appears twice in SETUP"); return 0; } uint64_t max_id; if (!StringViewToVarInt(value, max_id)) { ParseError("MAX_SUBSCRIBE_ID parameter is not a valid varint"); return 0; } setup.max_subscribe_id = max_id; break; case MoqtSetupParameter::kSupportObjectAcks: uint64_t flag; if (!StringViewToVarInt(value, flag) || flag > 1) { ParseError("Invalid kSupportObjectAcks value"); return 0; } setup.supports_object_ack = static_cast<bool>(flag); break; default: break; } } if (!setup.role.has_value()) { ParseError("ROLE parameter missing from CLIENT_SETUP message"); return 0; } if (!uses_web_transport_ && !setup.path.has_value()) { ParseError("PATH SETUP parameter missing from Client message over QUIC"); return 0; } visitor_.OnClientSetupMessage(setup); return reader.PreviouslyReadPayload().length(); } size_t MoqtControlParser::ProcessServerSetup(quic::QuicDataReader& reader) { MoqtServerSetup setup; uint64_t version; if (!reader.ReadVarInt62(&version)) { return 0; } setup.selected_version = static_cast<MoqtVersion>(version); uint64_t num_params; if (!reader.ReadVarInt62(&num_params)) { return 0; } for (uint64_t i = 0; i < num_params; ++i) { uint64_t type; absl::string_view value; if (!ReadParameter(reader, type, value)) { return 0; } auto key = static_cast<MoqtSetupParameter>(type); switch (key) { case MoqtSetupParameter::kRole: if (setup.role.has_value()) { ParseError("ROLE parameter appears twice in SETUP"); return 0; } uint64_t index; if (!StringViewToVarInt(value, index)) { return 0; } if (index > static_cast<uint64_t>(MoqtRole::kRoleMax)) { ParseError("Invalid ROLE parameter"); return 0; } setup.role = static_cast<MoqtRole>(index); break; case MoqtSetupParameter::kPath: ParseError("PATH parameter in SERVER_SETUP"); return 0; case MoqtSetupParameter::kMaxSubscribeId: if (setup.max_subscribe_id.has_value()) { ParseError("MAX_SUBSCRIBE_ID parameter appears twice in SETUP"); return 0; } uint64_t max_id; if (!StringViewToVarInt(value, max_id)) { ParseError("MAX_SUBSCRIBE_ID parameter is not a valid varint"); return 0; } setup.max_subscribe_id = max_id; break; case MoqtSetupParameter::kSupportObjectAcks: uint64_t flag; if (!StringViewToVarInt(value, flag) || flag > 1) { ParseError("Invalid kSupportObjectAcks value"); return 0; } setup.supports_object_ack = static_cast<bool>(flag); break; default: break; } } if (!setup.role.has_value()) { ParseError("ROLE parameter missing from SERVER_SETUP message"); return 0; } visitor_.OnServerSetupMessage(setup); return reader.PreviouslyReadPayload().length(); } size_t MoqtControlParser::ProcessSubscribe(quic::QuicDataReader& reader) { MoqtSubscribe subscribe_request; uint64_t filter, group, object; uint8_t group_order; absl::string_view track_name; if (!reader.ReadVarInt62(&subscribe_request.subscribe_id) || !reader.ReadVarInt62(&subscribe_request.track_alias) || !ReadTrackNamespace(reader, subscribe_request.full_track_name) || !reader.ReadStringPieceVarInt62(&track_name) || !reader.ReadUInt8(&subscribe_request.subscriber_priority) || !reader.ReadUInt8(&group_order) || !reader.ReadVarInt62(&filter)) { return 0; } subscribe_request.full_track_name.AddElement(track_name); if (!ParseDeliveryOrder(group_order, subscribe_request.group_order)) { ParseError("Invalid group order value in SUBSCRIBE message"); return 0; } MoqtFilterType filter_type = static_cast<MoqtFilterType>(filter); switch (filter_type) { case MoqtFilterType::kLatestGroup: subscribe_request.start_object = 0; break; case MoqtFilterType::kLatestObject: break; case MoqtFilterType::kAbsoluteStart: case MoqtFilterType::kAbsoluteRange: if (!reader.ReadVarInt62(&group) || !reader.ReadVarInt62(&object)) { return 0; } subscribe_request.start_group = group; subscribe_request.start_object = object; if (filter_type == MoqtFilterType::kAbsoluteStart) { break; } if (!reader.ReadVarInt62(&group) || !reader.ReadVarInt62(&object)) { return 0; } subscribe_request.end_group = group; if (subscribe_request.end_group < subscribe_request.start_group) { ParseError("End group is less than start group"); return 0; } if (object == 0) { subscribe_request.end_object = std::nullopt; } else { subscribe_request.end_object = object - 1; if (subscribe_request.start_group == subscribe_request.end_group && subscribe_request.end_object < subscribe_request.start_object) { ParseError("End object comes before start object"); return 0; } } break; default: ParseError("Invalid filter type"); return 0; } if (!ReadSubscribeParameters(reader, subscribe_request.parameters)) { return 0; } visitor_.OnSubscribeMessage(subscribe_request); return reader.PreviouslyReadPayload().length(); } size_t MoqtControlParser::ProcessSubscribeOk(quic::QuicDataReader& reader) { MoqtSubscribeOk subscribe_ok; uint64_t milliseconds; uint8_t group_order; uint8_t content_exists; if (!reader.ReadVarInt62(&subscribe_ok.subscribe_id) || !reader.ReadVarInt62(&milliseconds) || !reader.ReadUInt8(&group_order) || !reader.ReadUInt8(&content_exists)) { return 0; } if (content_exists > 1) { ParseError("SUBSCRIBE_OK ContentExists has invalid value"); return 0; } if (group_order != 0x01 && group_order != 0x02) { ParseError("Invalid group order value in SUBSCRIBE_OK"); return 0; } subscribe_ok.expires = quic::QuicTimeDelta::FromMilliseconds(milliseconds); subscribe_ok.group_order = static_cast<MoqtDeliveryOrder>(group_order); if (content_exists) { subscribe_ok.largest_id = FullSequence(); if (!reader.ReadVarInt62(&subscribe_ok.largest_id->group) || !reader.ReadVarInt62(&subscribe_ok.largest_id->object)) { return 0; } } if (!ReadSubscribeParameters(reader, subscribe_ok.parameters)) { return 0; } if (subscribe_ok.parameters.authorization_info.has_value()) { ParseError("SUBSCRIBE_OK has authorization info"); return 0; } visitor_.OnSubscribeOkMessage(subscribe_ok); return reader.PreviouslyReadPayload().length(); } size_t MoqtControlParser::ProcessSubscribeError(quic::QuicDataReader& reader) { MoqtSubscribeError subscribe_error; uint64_t error_code; if (!reader.ReadVarInt62(&subscribe_error.subscribe_id) || !reader.ReadVarInt62(&error_code) || !reader.ReadStringVarInt62(subscribe_error.reason_phrase) || !reader.ReadVarInt62(&subscribe_error.track_alias)) { return 0; } subscribe_error.error_code = static_cast<SubscribeErrorCode>(error_code); visitor_.OnSubscribeErrorMessage(subscribe_error); return reader.PreviouslyReadPayload().length(); } size_t MoqtControlParser::ProcessUnsubscribe(quic::QuicDataReader& reader) { MoqtUnsubscribe unsubscribe; if (!reader.ReadVarInt62(&unsubscribe.subscribe_id)) { return 0; } visitor_.OnUnsubscribeMessage(unsubscribe); return reader.PreviouslyReadPayload().length(); } size_t MoqtControlParser::ProcessSubscribeDone(quic::QuicDataReader& reader) { MoqtSubscribeDone subscribe_done; uint8_t content_exists; uint64_t value; if (!reader.ReadVarInt62(&subscribe_done.subscribe_id) || !reader.ReadVarInt62(&value) || !reader.ReadStringVarInt62(subscribe_done.reason_phrase) || !reader.ReadUInt8(&content_exists)) { return 0; } subscribe_done.status_code = static_cast<SubscribeDoneCode>(value); if (content_exists > 1) { ParseError("SUBSCRIBE_DONE ContentExists has invalid value"); return 0; } if (content_exists == 1) { subscribe_done.final_id = FullSequence(); if (!reader.ReadVarInt62(&subscribe_done.final_id->group) || !reader.ReadVarInt62(&subscribe_done.final_id->object)) { return 0; } } visitor_.OnSubscribeDoneMessage(subscribe_done); return reader.PreviouslyReadPayload().length(); } size_t MoqtControlParser::ProcessSubscribeUpdate(quic::QuicDataReader& reader) { MoqtSubscribeUpdate subscribe_update; uint64_t end_group, end_object; if (!reader.ReadVarInt62(&subscribe_update.subscribe_id) || !reader.ReadVarInt62(&subscribe_update.start_group) || !reader.ReadVarInt62(&subscribe_update.start_object) || !reader.ReadVarInt62(&end_group) || !reader.ReadVarInt62(&end_object) || !reader.ReadUInt8(&subscribe_update.subscriber_priority)) { return 0; } if (!ReadSubscribeParameters(reader, subscribe_update.parameters)) { return 0; } if (end_group == 0) { if (end_object > 0) { ParseError("SUBSCRIBE_UPDATE has end_object but no end_group"); return 0; } } else { subscribe_update.end_group = end_group - 1; if (subscribe_update.end_group < subscribe_update.start_group) { ParseError("End group is less than start group"); return 0; } } if (end_object > 0) { subscribe_update.end_object = end_object - 1; if (subscribe_update.end_object.has_value() && subscribe_update.start_group == *subscribe_update.end_group && *subscribe_update.end_object < subscribe_update.start_object) { ParseError("End object comes before start object"); return 0; } } else { subscribe_update.end_object = std::nullopt; } if (subscribe_update.parameters.authorization_info.has_value()) { ParseError("SUBSCRIBE_UPDATE has authorization info"); return 0; } visitor_.OnSubscribeUpdateMessage(subscribe_update); return reader.PreviouslyReadPayload().length(); } size_t MoqtControlParser::ProcessAnnounce(quic::QuicDataReader& reader) { MoqtAnnounce announce; if (!ReadTrackNamespace(reader, announce.track_namespace)) { return 0; } if (!ReadSubscribeParameters(reader, announce.parameters)) { return 0; } if (announce.parameters.delivery_timeout.has_value()) { ParseError("ANNOUNCE has delivery timeout"); return 0; } visitor_.OnAnnounceMessage(announce); return reader.PreviouslyReadPayload().length(); } size_t MoqtControlParser::ProcessAnnounceOk(quic::QuicDataReader& reader) { MoqtAnnounceOk announce_ok; if (!ReadTrackNamespace(reader, announce_ok.track_namespace)) { return 0; } visitor_.OnAnnounceOkMessage(announce_ok); return reader.PreviouslyReadPayload().length(); } size_t MoqtControlParser::ProcessAnnounceError(quic::QuicDataReader& reader) { MoqtAnnounceError announce_error; if (!ReadTrackNamespace(reader, announce_error.track_namespace)) { return 0; } uint64_t error_code; if (!reader.ReadVarInt62(&error_code)) { return 0; } announce_error.error_code = static_cast<MoqtAnnounceErrorCode>(error_code); if (!reader.ReadStringVarInt62(announce_error.reason_phrase)) { return 0; } visitor_.OnAnnounceErrorMessage(announce_error); return reader.PreviouslyReadPayload().length(); } size_t MoqtControlParser::ProcessAnnounceCancel(quic::QuicDataReader& reader) { MoqtAnnounceCancel announce_cancel; if (!ReadTrackNamespace(reader, announce_cancel.track_namespace)) { return 0; } if (!reader.ReadVarInt62(&announce_cancel.error_code) || !reader.ReadStringVarInt62(announce_cancel.reason_phrase)) { return 0; } visitor_.OnAnnounceCancelMessage(announce_cancel); return reader.PreviouslyReadPayload().length(); } size_t MoqtControlParser::ProcessTrackStatusRequest( quic::QuicDataReader& reader) { MoqtTrackStatusRequest track_status_request; if (!ReadTrackNamespace(reader, track_status_request.full_track_name)) { return 0; } absl::string_view name; if (!reader.ReadStringPieceVarInt62(&name)) { return 0; } track_status_request.full_track_name.AddElement(name); visitor_.OnTrackStatusRequestMessage(track_status_request); return reader.PreviouslyReadPayload().length(); } size_t MoqtControlParser::ProcessUnannounce(quic::QuicDataReader& reader) { MoqtUnannounce unannounce; if (!ReadTrackNamespace(reader, unannounce.track_namespace)) { return 0; } visitor_.OnUnannounceMessage(unannounce); return reader.PreviouslyReadPayload().length(); } size_t MoqtControlParser::ProcessTrackStatus(quic::QuicDataReader& reader) { MoqtTrackStatus track_status; if (!ReadTrackNamespace(reader, track_status.full_track_name)) { return 0; } absl::string_view name; if (!reader.ReadStringPieceVarInt62(&name)) { return 0; } track_status.full_track_name.AddElement(name); uint64_t value; if (!reader.ReadVarInt62(&value) || !reader.ReadVarInt62(&track_status.last_group) || !reader.ReadVarInt62(&track_status.last_object)) { return 0; } track_status.status_code = static_cast<MoqtTrackStatusCode>(value); visitor_.OnTrackStatusMessage(track_status); return reader.PreviouslyReadPayload().length(); } size_t MoqtControlParser::ProcessGoAway(quic::QuicDataReader& reader) { MoqtGoAway goaway; if (!reader.ReadStringVarInt62(goaway.new_session_uri)) { return 0; } visitor_.OnGoAwayMessage(goaway); return reader.PreviouslyReadPayload().length(); } size_t MoqtControlParser::ProcessSubscribeNamespace( quic::QuicDataReader& reader) { MoqtSubscribeNamespace subscribe_namespace; if (!ReadTrackNamespace(reader, subscribe_namespace.track_namespace)) { return 0; } if (!ReadSubscribeParameters(reader, subscribe_namespace.parameters)) { return 0; } visitor_.OnSubscribeNamespaceMessage(subscribe_namespace); return reader.PreviouslyReadPayload().length(); } size_t MoqtControlParser::ProcessSubscribeNamespaceOk( quic::QuicDataReader& reader) { MoqtSubscribeNamespaceOk subscribe_namespace_ok; if (!ReadTrackNamespace(reader, subscribe_namespace_ok.track_namespace)) { return 0; } visitor_.OnSubscribeNamespaceOkMessage(subscribe_namespace_ok); return reader.PreviouslyReadPayload().length(); } size_t MoqtControlParser::ProcessSubscribeNamespaceError( quic::QuicDataReader& reader) { MoqtSubscribeNamespaceError subscribe_namespace_error; uint64_t error_code; if (!ReadTrackNamespace(reader, subscribe_namespace_error.track_namespace) || !reader.ReadVarInt62(&error_code) || !reader.ReadStringVarInt62(subscribe_namespace_error.reason_phrase)) { return 0; } subscribe_namespace_error.error_code = static_cast<MoqtAnnounceErrorCode>(error_code); visitor_.OnSubscribeNamespaceErrorMessage(subscribe_namespace_error); return reader.PreviouslyReadPayload().length(); } size_t MoqtControlParser::ProcessUnsubscribeNamespace( quic::QuicDataReader& reader) { MoqtUnsubscribeNamespace unsubscribe_namespace; if (!ReadTrackNamespace(reader, unsubscribe_namespace.track_namespace)) { return 0; } visitor_.OnUnsubscribeNamespaceMessage(unsubscribe_namespace); return reader.PreviouslyReadPayload().length(); } size_t MoqtControlParser::ProcessMaxSubscribeId(quic::QuicDataReader& reader) { MoqtMaxSubscribeId max_subscribe_id; if (!reader.ReadVarInt62(&max_subscribe_id.max_subscribe_id)) { return 0; } visitor_.OnMaxSubscribeIdMessage(max_subscribe_id); return reader.PreviouslyReadPayload().length(); } size_t MoqtControlParser::ProcessObjectAck(quic::QuicDataReader& reader) { MoqtObjectAck object_ack; uint64_t raw_delta; if (!reader.ReadVarInt62(&object_ack.subscribe_id) || !reader.ReadVarInt62(&object_ack.group_id) || !reader.ReadVarInt62(&object_ack.object_id) || !reader.ReadVarInt62(&raw_delta)) { return 0; } object_ack.delta_from_deadline = quic::QuicTimeDelta::FromMicroseconds( SignedVarintUnserializedForm(raw_delta)); visitor_.OnObjectAckMessage(object_ack); return reader.PreviouslyReadPayload().length(); } void MoqtControlParser::ParseError(absl::string_view reason) { ParseError(MoqtError::kProtocolViolation, reason); } void MoqtControlParser::ParseError(MoqtError error_code, absl::string_view reason) { if (parsing_error_) { return; } no_more_data_ = true; parsing_error_ = true; visitor_.OnParsingError(error_code, reason); } bool MoqtControlParser::ReadVarIntPieceVarInt62(quic::QuicDataReader& reader, uint64_t& result) { uint64_t length; if (!reader.ReadVarInt62(&length)) { return false; } uint64_t actual_length = static_cast<uint64_t>(reader.PeekVarInt62Length()); if (length != actual_length) { ParseError("Parameter VarInt has length field mismatch"); return false; } if (!reader.ReadVarInt62(&result)) { return false; } return true; } bool MoqtControlParser::ReadParameter(quic::QuicDataReader& reader, uint64_t& type, absl::string_view& value) { if (!reader.ReadVarInt62(&type)) { return false; } return reader.ReadStringPieceVarInt62(&value); } bool MoqtControlParser::ReadSubscribeParameters( quic::QuicDataReader& reader, MoqtSubscribeParameters& params) { uint64_t num_params; if (!reader.ReadVarInt62(&num_params)) { return false; } for (uint64_t i = 0; i < num_params; ++i) { uint64_t type; absl::string_view value; if (!ReadParameter(reader, type, value)) { return false; } uint64_t raw_value; auto key = static_cast<MoqtTrackRequestParameter>(type); switch (key) { case MoqtTrackRequestParameter::kAuthorizationInfo: if (params.authorization_info.has_value()) { ParseError("AUTHORIZATION_INFO parameter appears twice"); return false; } params.authorization_info = value; break; case moqt::MoqtTrackRequestParameter::kDeliveryTimeout: if (params.delivery_timeout.has_value()) { ParseError("DELIVERY_TIMEOUT parameter appears twice"); return false; } if (!StringViewToVarInt(value, raw_value)) { return false; } params.delivery_timeout = quic::QuicTimeDelta::FromMilliseconds(raw_value); break; case moqt::MoqtTrackRequestParameter::kMaxCacheDuration: if (params.max_cache_duration.has_value()) { ParseError("MAX_CACHE_DURATION parameter appears twice"); return false; } if (!StringViewToVarInt(value, raw_value)) { return false; } params.max_cache_duration = quic::QuicTimeDelta::FromMilliseconds(raw_value); break; case MoqtTrackRequestParameter::kOackWindowSize: { if (params.object_ack_window.has_value()) { ParseError("OACK_WINDOW_SIZE parameter appears twice in SUBSCRIBE"); return false; } if (!StringViewToVarInt(value, raw_value)) { ParseError("OACK_WINDOW_SIZE parameter is not a valid varint"); return false; } params.object_ack_window = quic::QuicTimeDelta::FromMicroseconds(raw_value); break; } default: break; } } return true; } bool MoqtControlParser::StringViewToVarInt(absl::string_view& sv, uint64_t& vi) { quic::QuicDataReader reader(sv); if (static_cast<size_t>(reader.PeekVarInt62Length()) != sv.length()) { ParseError(MoqtError::kParameterLengthMismatch, "Parameter length does not match varint encoding"); return false; } reader.ReadVarInt62(&vi); return true; } bool MoqtControlParser::ReadTrackNamespace(quic::QuicDataReader& reader, FullTrackName& full_track_name) { QUICHE_DCHECK(full_track_name.empty()); uint64_t num_elements; if (!reader.ReadVarInt62(&num_elements)) { return 0; } for (uint64_t i = 0; i < num_elements; ++i) { absl::string_view element; if (!reader.ReadStringPieceVarInt62(&element)) { return false; } full_track_name.AddElement(element); } return true; } void MoqtDataParser::ParseError(absl::string_view reason) { if (parsing_error_) { return; } no_more_data_ = true; parsing_error_ = true; visitor_.OnParsingError(MoqtError::kProtocolViolation, reason); } absl::string_view ParseDatagram(absl::string_view data, MoqtObject& object_metadata) { uint64_t value; quic::QuicDataReader reader(data); if (!reader.ReadVarInt62(&value)) { return absl::string_view(); } if (static_cast<MoqtDataStreamType>(value) != MoqtDataStreamType::kObjectDatagram) { return absl::string_view(); } size_t processed_data = ParseObjectHeader( reader, object_metadata, MoqtDataStreamType::kObjectDatagram); if (processed_data == 0) { return absl::string_view(); } return reader.PeekRemainingPayload(); } void MoqtDataParser::ProcessData(absl::string_view data, bool fin) { if (processing_) { QUICHE_BUG(MoqtDataParser_reentry) << "Calling ProcessData() when ProcessData() is already in progress."; return; } processing_ = true; auto on_return = absl::MakeCleanup([&] { processing_ = false; }); if (no_more_data_) { ParseError("Data after end of stream"); return; } while (!buffered_message_.empty() && !data.empty()) { absl::string_view chunk = data.substr(0, chunk_size_); absl::StrAppend(&buffered_message_, chunk); absl::string_view unprocessed = ProcessDataInner(buffered_message_); if (unprocessed.size() >= chunk.size()) { data.remove_prefix(chunk.size()); } else { buffered_message_.clear(); data.remove_prefix(chunk.size() - unprocessed.size()); } } if (buffered_message_.empty() && !data.empty()) { buffered_message_.assign(ProcessDataInner(data)); } if (fin) { if (!buffered_message_.empty() || !metadata_.has_value() || payload_length_remaining_ > 0) { ParseError("FIN received at an unexpected point in the stream"); return; } no_more_data_ = true; } } absl::string_view MoqtDataParser::ProcessDataInner(absl::string_view data) { quic::QuicDataReader reader(data); while (!reader.IsDoneReading()) { absl::string_view remainder = reader.PeekRemainingPayload(); switch (GetNextInput()) { case kStreamType: { uint64_t value; if (!reader.ReadVarInt62(&value)) { return remainder; } if (!IsAllowedStreamType(value)) { ParseError(absl::StrCat("Unknown stream type: ", value)); return ""; } type_ = static_cast<MoqtDataStreamType>(value); continue; } case kHeader: { MoqtObject header; size_t bytes_read = ParseObjectHeader(reader, header, *type_); if (bytes_read == 0) { return remainder; } metadata_ = header; continue; } case kSubheader: { size_t bytes_read = ParseObjectSubheader(reader, *metadata_, *type_); if (bytes_read == 0) { return remainder; } if (metadata_->object_status == MoqtObjectStatus::kInvalidObjectStatus) { ParseError("Invalid object status provided"); return ""; } payload_length_remaining_ = metadata_->payload_length; if (payload_length_remaining_ == 0) { visitor_.OnObjectMessage(*metadata_, "", true); } continue; } case kData: { absl::string_view payload = reader.ReadAtMost(payload_length_remaining_); visitor_.OnObjectMessage(*metadata_, payload, payload.size() == payload_length_remaining_); payload_length_remaining_ -= payload.size(); continue; } case kPadding: return ""; } } return ""; } }
#include "quiche/quic/moqt/moqt_parser.h" #include <array> #include <cstddef> #include <cstdint> #include <cstring> #include <memory> #include <optional> #include <string> #include <vector> #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/variant.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/quic/moqt/test_tools/moqt_test_message.h" #include "quiche/quic/platform/api/quic_test.h" namespace moqt::test { namespace { using ::testing::AnyOf; using ::testing::HasSubstr; using ::testing::Optional; constexpr std::array kMessageTypes{ MoqtMessageType::kSubscribe, MoqtMessageType::kSubscribeOk, MoqtMessageType::kSubscribeError, MoqtMessageType::kSubscribeUpdate, MoqtMessageType::kUnsubscribe, MoqtMessageType::kSubscribeDone, MoqtMessageType::kAnnounceCancel, MoqtMessageType::kTrackStatusRequest, MoqtMessageType::kTrackStatus, MoqtMessageType::kAnnounce, MoqtMessageType::kAnnounceOk, MoqtMessageType::kAnnounceError, MoqtMessageType::kUnannounce, MoqtMessageType::kClientSetup, MoqtMessageType::kServerSetup, MoqtMessageType::kGoAway, MoqtMessageType::kSubscribeNamespace, MoqtMessageType::kSubscribeNamespaceOk, MoqtMessageType::kSubscribeNamespaceError, MoqtMessageType::kUnsubscribeNamespace, MoqtMessageType::kMaxSubscribeId, MoqtMessageType::kObjectAck, }; constexpr std::array kDataStreamTypes{ MoqtDataStreamType::kStreamHeaderTrack, MoqtDataStreamType::kStreamHeaderSubgroup}; using GeneralizedMessageType = absl::variant<MoqtMessageType, MoqtDataStreamType>; } struct MoqtParserTestParams { MoqtParserTestParams(MoqtMessageType message_type, bool uses_web_transport) : message_type(message_type), uses_web_transport(uses_web_transport) {} explicit MoqtParserTestParams(MoqtDataStreamType message_type) : message_type(message_type), uses_web_transport(true) {} GeneralizedMessageType message_type; bool uses_web_transport; }; std::vector<MoqtParserTestParams> GetMoqtParserTestParams() { std::vector<MoqtParserTestParams> params; for (MoqtMessageType message_type : kMessageTypes) { if (message_type == MoqtMessageType::kClientSetup) { for (const bool uses_web_transport : {false, true}) { params.push_back( MoqtParserTestParams(message_type, uses_web_transport)); } } else { params.push_back(MoqtParserTestParams(message_type, true)); } } for (MoqtDataStreamType type : kDataStreamTypes) { params.push_back(MoqtParserTestParams(type)); } return params; } std::string TypeFormatter(MoqtMessageType type) { return MoqtMessageTypeToString(type); } std::string TypeFormatter(MoqtDataStreamType type) { return MoqtDataStreamTypeToString(type); } std::string ParamNameFormatter( const testing::TestParamInfo<MoqtParserTestParams>& info) { return absl::visit([](auto x) { return TypeFormatter(x); }, info.param.message_type) + "_" + (info.param.uses_web_transport ? "WebTransport" : "QUIC"); } class MoqtParserTestVisitor : public MoqtControlParserVisitor, public MoqtDataParserVisitor { public: ~MoqtParserTestVisitor() = default; void OnObjectMessage(const MoqtObject& message, absl::string_view payload, bool end_of_message) override { MoqtObject object = message; object_payloads_.push_back(std::string(payload)); end_of_message_ = end_of_message; if (end_of_message) { ++messages_received_; } last_message_ = TestMessageBase::MessageStructuredData(object); } template <typename Message> void OnControlMessage(const Message& message) { end_of_message_ = true; ++messages_received_; last_message_ = TestMessageBase::MessageStructuredData(message); } void OnClientSetupMessage(const MoqtClientSetup& message) override { OnControlMessage(message); } void OnServerSetupMessage(const MoqtServerSetup& message) override { OnControlMessage(message); } void OnSubscribeMessage(const MoqtSubscribe& message) override { OnControlMessage(message); } void OnSubscribeOkMessage(const MoqtSubscribeOk& message) override { OnControlMessage(message); } void OnSubscribeErrorMessage(const MoqtSubscribeError& message) override { OnControlMessage(message); } void OnSubscribeUpdateMessage(const MoqtSubscribeUpdate& message) override { OnControlMessage(message); } void OnUnsubscribeMessage(const MoqtUnsubscribe& message) override { OnControlMessage(message); } void OnSubscribeDoneMessage(const MoqtSubscribeDone& message) override { OnControlMessage(message); } void OnAnnounceMessage(const MoqtAnnounce& message) override { OnControlMessage(message); } void OnAnnounceOkMessage(const MoqtAnnounceOk& message) override { OnControlMessage(message); } void OnAnnounceErrorMessage(const MoqtAnnounceError& message) override { OnControlMessage(message); } void OnAnnounceCancelMessage(const MoqtAnnounceCancel& message) override { OnControlMessage(message); } void OnTrackStatusRequestMessage( const MoqtTrackStatusRequest& message) override { OnControlMessage(message); } void OnUnannounceMessage(const MoqtUnannounce& message) override { OnControlMessage(message); } void OnTrackStatusMessage(const MoqtTrackStatus& message) override { OnControlMessage(message); } void OnGoAwayMessage(const MoqtGoAway& message) override { OnControlMessage(message); } void OnSubscribeNamespaceMessage( const MoqtSubscribeNamespace& message) override { OnControlMessage(message); } void OnSubscribeNamespaceOkMessage( const MoqtSubscribeNamespaceOk& message) override { OnControlMessage(message); } void OnSubscribeNamespaceErrorMessage( const MoqtSubscribeNamespaceError& message) override { OnControlMessage(message); } void OnUnsubscribeNamespaceMessage( const MoqtUnsubscribeNamespace& message) override { OnControlMessage(message); } void OnMaxSubscribeIdMessage(const MoqtMaxSubscribeId& message) override { OnControlMessage(message); } void OnObjectAckMessage(const MoqtObjectAck& message) override { OnControlMessage(message); } void OnParsingError(MoqtError code, absl::string_view reason) override { QUIC_LOG(INFO) << "Parsing error: " << reason; parsing_error_ = reason; parsing_error_code_ = code; } std::string object_payload() { return absl::StrJoin(object_payloads_, ""); } std::vector<std::string> object_payloads_; bool end_of_message_ = false; std::optional<std::string> parsing_error_; MoqtError parsing_error_code_; uint64_t messages_received_ = 0; std::optional<TestMessageBase::MessageStructuredData> last_message_; }; class MoqtParserTest : public quic::test::QuicTestWithParam<MoqtParserTestParams> { public: MoqtParserTest() : message_type_(GetParam().message_type), webtrans_(GetParam().uses_web_transport), control_parser_(GetParam().uses_web_transport, visitor_), data_parser_(&visitor_) {} bool IsDataStream() { return absl::holds_alternative<MoqtDataStreamType>(message_type_); } std::unique_ptr<TestMessageBase> MakeMessage() { if (IsDataStream()) { return CreateTestDataStream(absl::get<MoqtDataStreamType>(message_type_)); } else { return CreateTestMessage(absl::get<MoqtMessageType>(message_type_), webtrans_); } } void ProcessData(absl::string_view data, bool fin) { if (IsDataStream()) { data_parser_.ProcessData(data, fin); } else { control_parser_.ProcessData(data, fin); } } protected: MoqtParserTestVisitor visitor_; GeneralizedMessageType message_type_; bool webtrans_; MoqtControlParser control_parser_; MoqtDataParser data_parser_; }; INSTANTIATE_TEST_SUITE_P(MoqtParserTests, MoqtParserTest, testing::ValuesIn(GetMoqtParserTestParams()), ParamNameFormatter); TEST_P(MoqtParserTest, OneMessage) { std::unique_ptr<TestMessageBase> message = MakeMessage(); ProcessData(message->PacketSample(), true); EXPECT_EQ(visitor_.messages_received_, 1); EXPECT_TRUE(message->EqualFieldValues(*visitor_.last_message_)); EXPECT_TRUE(visitor_.end_of_message_); if (IsDataStream()) { EXPECT_EQ(visitor_.object_payload(), "foo"); } } TEST_P(MoqtParserTest, OneMessageWithLongVarints) { std::unique_ptr<TestMessageBase> message = MakeMessage(); message->ExpandVarints(); ProcessData(message->PacketSample(), true); EXPECT_EQ(visitor_.messages_received_, 1); EXPECT_TRUE(message->EqualFieldValues(*visitor_.last_message_)); EXPECT_TRUE(visitor_.end_of_message_); EXPECT_FALSE(visitor_.parsing_error_.has_value()); if (IsDataStream()) { EXPECT_EQ(visitor_.object_payload(), "foo"); } } TEST_P(MoqtParserTest, TwoPartMessage) { std::unique_ptr<TestMessageBase> message = MakeMessage(); size_t first_data_size = message->total_message_size() / 2; ProcessData(message->PacketSample().substr(0, first_data_size), false); EXPECT_EQ(visitor_.messages_received_, 0); ProcessData( message->PacketSample().substr( first_data_size, message->total_message_size() - first_data_size), true); EXPECT_EQ(visitor_.messages_received_, 1); EXPECT_TRUE(message->EqualFieldValues(*visitor_.last_message_)); EXPECT_TRUE(visitor_.end_of_message_); EXPECT_FALSE(visitor_.parsing_error_.has_value()); if (IsDataStream()) { EXPECT_EQ(visitor_.object_payload(), "foo"); } } TEST_P(MoqtParserTest, OneByteAtATime) { std::unique_ptr<TestMessageBase> message = MakeMessage(); for (size_t i = 0; i < message->total_message_size(); ++i) { EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_FALSE(visitor_.end_of_message_); bool last = i == (message->total_message_size() - 1); ProcessData(message->PacketSample().substr(i, 1), last); } EXPECT_EQ(visitor_.messages_received_, 1); EXPECT_TRUE(message->EqualFieldValues(*visitor_.last_message_)); EXPECT_TRUE(visitor_.end_of_message_); EXPECT_FALSE(visitor_.parsing_error_.has_value()); if (IsDataStream()) { EXPECT_EQ(visitor_.object_payload(), "foo"); } } TEST_P(MoqtParserTest, OneByteAtATimeLongerVarints) { std::unique_ptr<TestMessageBase> message = MakeMessage(); message->ExpandVarints(); for (size_t i = 0; i < message->total_message_size(); ++i) { EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_FALSE(visitor_.end_of_message_); bool last = i == (message->total_message_size() - 1); ProcessData(message->PacketSample().substr(i, 1), last); } EXPECT_EQ(visitor_.messages_received_, 1); EXPECT_TRUE(message->EqualFieldValues(*visitor_.last_message_)); EXPECT_TRUE(visitor_.end_of_message_); EXPECT_FALSE(visitor_.parsing_error_.has_value()); if (IsDataStream()) { EXPECT_EQ(visitor_.object_payload(), "foo"); } } TEST_P(MoqtParserTest, TwoBytesAtATime) { std::unique_ptr<TestMessageBase> message = MakeMessage(); data_parser_.set_chunk_size(1); for (size_t i = 0; i < message->total_message_size(); i += 3) { EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_FALSE(visitor_.end_of_message_); bool last = (i + 2) >= message->total_message_size(); ProcessData(message->PacketSample().substr(i, 3), last); } EXPECT_EQ(visitor_.messages_received_, 1); EXPECT_TRUE(message->EqualFieldValues(*visitor_.last_message_)); EXPECT_TRUE(visitor_.end_of_message_); EXPECT_FALSE(visitor_.parsing_error_.has_value()); if (IsDataStream()) { EXPECT_EQ(visitor_.object_payload(), "foo"); } } TEST_P(MoqtParserTest, EarlyFin) { std::unique_ptr<TestMessageBase> message = MakeMessage(); size_t first_data_size = message->total_message_size() - 1; ProcessData(message->PacketSample().substr(0, first_data_size), true); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_THAT(visitor_.parsing_error_, AnyOf("FIN after incomplete message", "FIN received at an unexpected point in the stream")); } TEST_P(MoqtParserTest, SeparateEarlyFin) { std::unique_ptr<TestMessageBase> message = MakeMessage(); size_t first_data_size = message->total_message_size() - 1; ProcessData(message->PacketSample().substr(0, first_data_size), false); ProcessData(absl::string_view(), true); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_THAT(visitor_.parsing_error_, AnyOf("End of stream before complete message", "FIN received at an unexpected point in the stream")); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } class MoqtMessageSpecificTest : public quic::test::QuicTest { public: MoqtMessageSpecificTest() {} MoqtParserTestVisitor visitor_; static constexpr bool kWebTrans = true; static constexpr bool kRawQuic = false; }; TEST_F(MoqtMessageSpecificTest, ThreePartObject) { MoqtDataParser parser(&visitor_); auto message = std::make_unique<StreamHeaderSubgroupMessage>(); EXPECT_TRUE(message->SetPayloadLength(14)); parser.ProcessData(message->PacketSample(), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(message->EqualFieldValues(*visitor_.last_message_)); EXPECT_FALSE(visitor_.end_of_message_); EXPECT_EQ(visitor_.object_payload(), "foo"); parser.ProcessData("bar", false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(message->EqualFieldValues(*visitor_.last_message_)); EXPECT_FALSE(visitor_.end_of_message_); EXPECT_EQ(visitor_.object_payload(), "foobar"); parser.ProcessData("deadbeef", true); EXPECT_EQ(visitor_.messages_received_, 1); EXPECT_TRUE(message->EqualFieldValues(*visitor_.last_message_)); EXPECT_TRUE(visitor_.end_of_message_); EXPECT_EQ(visitor_.object_payload(), "foobardeadbeef"); EXPECT_FALSE(visitor_.parsing_error_.has_value()); } TEST_F(MoqtMessageSpecificTest, ThreePartObjectFirstIncomplete) { MoqtDataParser parser(&visitor_); auto message = std::make_unique<StreamHeaderSubgroupMessage>(); EXPECT_TRUE(message->SetPayloadLength(50)); parser.ProcessData(message->PacketSample().substr(0, 4), false); EXPECT_EQ(visitor_.messages_received_, 0); message->set_wire_image_size(55); parser.ProcessData( message->PacketSample().substr(4, message->total_message_size() - 4), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(message->EqualFieldValues(*visitor_.last_message_)); EXPECT_FALSE(visitor_.end_of_message_); EXPECT_EQ(visitor_.object_payload().length(), 47); parser.ProcessData("bar", true); EXPECT_EQ(visitor_.messages_received_, 1); EXPECT_TRUE(message->EqualFieldValues(*visitor_.last_message_)); EXPECT_TRUE(visitor_.end_of_message_); EXPECT_EQ(*visitor_.object_payloads_.crbegin(), "bar"); EXPECT_FALSE(visitor_.parsing_error_.has_value()); } TEST_F(MoqtMessageSpecificTest, StreamHeaderSubgroupFollowOn) { MoqtDataParser parser(&visitor_); auto message1 = std::make_unique<StreamHeaderSubgroupMessage>(); parser.ProcessData(message1->PacketSample(), false); EXPECT_EQ(visitor_.messages_received_, 1); EXPECT_TRUE(message1->EqualFieldValues(*visitor_.last_message_)); EXPECT_TRUE(visitor_.end_of_message_); EXPECT_EQ(visitor_.object_payload(), "foo"); EXPECT_FALSE(visitor_.parsing_error_.has_value()); visitor_.object_payloads_.clear(); auto message2 = std::make_unique<StreamMiddlerSubgroupMessage>(); parser.ProcessData(message2->PacketSample(), false); EXPECT_EQ(visitor_.messages_received_, 2); EXPECT_TRUE(message2->EqualFieldValues(*visitor_.last_message_)); EXPECT_TRUE(visitor_.end_of_message_); EXPECT_EQ(visitor_.object_payload(), "bar"); EXPECT_FALSE(visitor_.parsing_error_.has_value()); } TEST_F(MoqtMessageSpecificTest, StreamHeaderTrackFollowOn) { MoqtDataParser parser(&visitor_); auto message1 = std::make_unique<StreamHeaderTrackMessage>(); parser.ProcessData(message1->PacketSample(), false); EXPECT_EQ(visitor_.messages_received_, 1); EXPECT_TRUE(message1->EqualFieldValues(*visitor_.last_message_)); EXPECT_TRUE(visitor_.end_of_message_); EXPECT_EQ(visitor_.object_payload(), "foo"); EXPECT_FALSE(visitor_.parsing_error_.has_value()); visitor_.object_payloads_.clear(); auto message2 = std::make_unique<StreamMiddlerTrackMessage>(); parser.ProcessData(message2->PacketSample(), false); EXPECT_EQ(visitor_.messages_received_, 2); EXPECT_TRUE(message2->EqualFieldValues(*visitor_.last_message_)); EXPECT_TRUE(visitor_.end_of_message_); EXPECT_EQ(visitor_.object_payload(), "bar"); EXPECT_FALSE(visitor_.parsing_error_.has_value()); } TEST_F(MoqtMessageSpecificTest, ClientSetupRoleIsInvalid) { MoqtControlParser parser(kRawQuic, visitor_); char setup[] = { 0x40, 0x40, 0x02, 0x01, 0x02, 0x03, 0x00, 0x01, 0x04, 0x01, 0x03, 0x66, 0x6f, 0x6f }; parser.ProcessData(absl::string_view(setup, sizeof(setup)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "Invalid ROLE parameter"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, ServerSetupRoleIsInvalid) { MoqtControlParser parser(kRawQuic, visitor_); char setup[] = { 0x40, 0x41, 0x01, 0x01, 0x00, 0x01, 0x04, 0x01, 0x03, 0x66, 0x6f, 0x6f }; parser.ProcessData(absl::string_view(setup, sizeof(setup)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "Invalid ROLE parameter"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, SetupRoleAppearsTwice) { MoqtControlParser parser(kRawQuic, visitor_); char setup[] = { 0x40, 0x40, 0x02, 0x01, 0x02, 0x03, 0x00, 0x01, 0x03, 0x00, 0x01, 0x03, 0x01, 0x03, 0x66, 0x6f, 0x6f }; parser.ProcessData(absl::string_view(setup, sizeof(setup)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "ROLE parameter appears twice in SETUP"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, ClientSetupRoleIsMissing) { MoqtControlParser parser(kRawQuic, visitor_); char setup[] = { 0x40, 0x40, 0x02, 0x01, 0x02, 0x01, 0x01, 0x03, 0x66, 0x6f, 0x6f, }; parser.ProcessData(absl::string_view(setup, sizeof(setup)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "ROLE parameter missing from CLIENT_SETUP message"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, ClientSetupMaxSubscribeIdAppearsTwice) { MoqtControlParser parser(kRawQuic, visitor_); char setup[] = { 0x40, 0x40, 0x02, 0x01, 0x02, 0x04, 0x00, 0x01, 0x03, 0x01, 0x03, 0x66, 0x6f, 0x6f, 0x02, 0x01, 0x32, 0x02, 0x01, 0x32, }; parser.ProcessData(absl::string_view(setup, sizeof(setup)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "MAX_SUBSCRIBE_ID parameter appears twice in SETUP"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, ServerSetupRoleIsMissing) { MoqtControlParser parser(kRawQuic, visitor_); char setup[] = { 0x40, 0x41, 0x01, 0x00, }; parser.ProcessData(absl::string_view(setup, sizeof(setup)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "ROLE parameter missing from SERVER_SETUP message"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, SetupRoleVarintLengthIsWrong) { MoqtControlParser parser(kRawQuic, visitor_); char setup[] = { 0x40, 0x40, 0x02, 0x01, 0x02, 0x02, 0x00, 0x02, 0x03, 0x01, 0x03, 0x66, 0x6f, 0x6f }; parser.ProcessData(absl::string_view(setup, sizeof(setup)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "Parameter length does not match varint encoding"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kParameterLengthMismatch); } TEST_F(MoqtMessageSpecificTest, SetupPathFromServer) { MoqtControlParser parser(kRawQuic, visitor_); char setup[] = { 0x40, 0x41, 0x01, 0x01, 0x01, 0x03, 0x66, 0x6f, 0x6f, }; parser.ProcessData(absl::string_view(setup, sizeof(setup)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "PATH parameter in SERVER_SETUP"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, SetupPathAppearsTwice) { MoqtControlParser parser(kRawQuic, visitor_); char setup[] = { 0x40, 0x40, 0x02, 0x01, 0x02, 0x03, 0x00, 0x01, 0x03, 0x01, 0x03, 0x66, 0x6f, 0x6f, 0x01, 0x03, 0x66, 0x6f, 0x6f, }; parser.ProcessData(absl::string_view(setup, sizeof(setup)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "PATH parameter appears twice in CLIENT_SETUP"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, SetupPathOverWebtrans) { MoqtControlParser parser(kWebTrans, visitor_); char setup[] = { 0x40, 0x40, 0x02, 0x01, 0x02, 0x02, 0x00, 0x01, 0x03, 0x01, 0x03, 0x66, 0x6f, 0x6f, }; parser.ProcessData(absl::string_view(setup, sizeof(setup)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "WebTransport connection is using PATH parameter in SETUP"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, SetupPathMissing) { MoqtControlParser parser(kRawQuic, visitor_); char setup[] = { 0x40, 0x40, 0x02, 0x01, 0x02, 0x01, 0x00, 0x01, 0x03, }; parser.ProcessData(absl::string_view(setup, sizeof(setup)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "PATH SETUP parameter missing from Client message over QUIC"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, ServerSetupMaxSubscribeIdAppearsTwice) { MoqtControlParser parser(kRawQuic, visitor_); char setup[] = { 0x40, 0x40, 0x02, 0x01, 0x02, 0x04, 0x00, 0x01, 0x03, 0x01, 0x03, 0x66, 0x6f, 0x6f, 0x02, 0x01, 0x32, 0x02, 0x01, 0x32, }; parser.ProcessData(absl::string_view(setup, sizeof(setup)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "MAX_SUBSCRIBE_ID parameter appears twice in SETUP"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, SubscribeAuthorizationInfoTwice) { MoqtControlParser parser(kWebTrans, visitor_); char subscribe[] = { 0x03, 0x01, 0x02, 0x01, 0x03, 0x66, 0x6f, 0x6f, 0x04, 0x61, 0x62, 0x63, 0x64, 0x20, 0x02, 0x02, 0x02, 0x02, 0x03, 0x62, 0x61, 0x72, 0x02, 0x03, 0x62, 0x61, 0x72, }; parser.ProcessData(absl::string_view(subscribe, sizeof(subscribe)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_EQ(visitor_.parsing_error_, "AUTHORIZATION_INFO parameter appears twice"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, SubscribeDeliveryTimeoutTwice) { MoqtControlParser parser(kRawQuic, visitor_); char subscribe[] = { 0x03, 0x01, 0x02, 0x01, 0x03, 0x66, 0x6f, 0x6f, 0x04, 0x61, 0x62, 0x63, 0x64, 0x20, 0x02, 0x02, 0x02, 0x03, 0x02, 0x67, 0x10, 0x03, 0x02, 0x67, 0x10, }; parser.ProcessData(absl::string_view(subscribe, sizeof(subscribe)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_EQ(visitor_.parsing_error_, "DELIVERY_TIMEOUT parameter appears twice"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, SubscribeDeliveryTimeoutMalformed) { MoqtControlParser parser(kRawQuic, visitor_); char subscribe[] = { 0x03, 0x01, 0x02, 0x01, 0x03, 0x66, 0x6f, 0x6f, 0x04, 0x61, 0x62, 0x63, 0x64, 0x20, 0x02, 0x02, 0x01, 0x03, 0x01, 0x67, 0x10, }; parser.ProcessData(absl::string_view(subscribe, sizeof(subscribe)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_EQ(visitor_.parsing_error_, "Parameter length does not match varint encoding"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kParameterLengthMismatch); } TEST_F(MoqtMessageSpecificTest, SubscribeMaxCacheDurationTwice) { MoqtControlParser parser(kRawQuic, visitor_); char subscribe[] = { 0x03, 0x01, 0x02, 0x01, 0x03, 0x66, 0x6f, 0x6f, 0x04, 0x61, 0x62, 0x63, 0x64, 0x20, 0x02, 0x02, 0x02, 0x04, 0x02, 0x67, 0x10, 0x04, 0x02, 0x67, 0x10, }; parser.ProcessData(absl::string_view(subscribe, sizeof(subscribe)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_EQ(visitor_.parsing_error_, "MAX_CACHE_DURATION parameter appears twice"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, SubscribeMaxCacheDurationMalformed) { MoqtControlParser parser(kRawQuic, visitor_); char subscribe[] = { 0x03, 0x01, 0x02, 0x01, 0x03, 0x66, 0x6f, 0x6f, 0x04, 0x61, 0x62, 0x63, 0x64, 0x20, 0x02, 0x02, 0x01, 0x04, 0x01, 0x67, 0x10, }; parser.ProcessData(absl::string_view(subscribe, sizeof(subscribe)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_EQ(visitor_.parsing_error_, "Parameter length does not match varint encoding"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kParameterLengthMismatch); } TEST_F(MoqtMessageSpecificTest, SubscribeOkHasAuthorizationInfo) { MoqtControlParser parser(kWebTrans, visitor_); char subscribe_ok[] = { 0x04, 0x01, 0x03, 0x02, 0x01, 0x0c, 0x14, 0x02, 0x03, 0x02, 0x67, 0x10, 0x02, 0x03, 0x62, 0x61, 0x72, }; parser.ProcessData(absl::string_view(subscribe_ok, sizeof(subscribe_ok)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_EQ(visitor_.parsing_error_, "SUBSCRIBE_OK has authorization info"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, SubscribeUpdateHasAuthorizationInfo) { MoqtControlParser parser(kWebTrans, visitor_); char subscribe_update[] = { 0x02, 0x02, 0x03, 0x01, 0x05, 0x06, 0xaa, 0x01, 0x02, 0x03, 0x62, 0x61, 0x72, }; parser.ProcessData( absl::string_view(subscribe_update, sizeof(subscribe_update)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_EQ(visitor_.parsing_error_, "SUBSCRIBE_UPDATE has authorization info"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, AnnounceAuthorizationInfoTwice) { MoqtControlParser parser(kWebTrans, visitor_); char announce[] = { 0x06, 0x01, 0x03, 0x66, 0x6f, 0x6f, 0x02, 0x02, 0x03, 0x62, 0x61, 0x72, 0x02, 0x03, 0x62, 0x61, 0x72, }; parser.ProcessData(absl::string_view(announce, sizeof(announce)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "AUTHORIZATION_INFO parameter appears twice"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, AnnounceHasDeliveryTimeout) { MoqtControlParser parser(kWebTrans, visitor_); char announce[] = { 0x06, 0x01, 0x03, 0x66, 0x6f, 0x6f, 0x02, 0x02, 0x03, 0x62, 0x61, 0x72, 0x03, 0x02, 0x67, 0x10, }; parser.ProcessData(absl::string_view(announce, sizeof(announce)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "ANNOUNCE has delivery timeout"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, FinMidPayload) { MoqtDataParser parser(&visitor_); auto message = std::make_unique<StreamHeaderSubgroupMessage>(); parser.ProcessData( message->PacketSample().substr(0, message->total_message_size() - 1), true); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_EQ(visitor_.parsing_error_, "FIN received at an unexpected point in the stream"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, PartialPayloadThenFin) { MoqtDataParser parser(&visitor_); auto message = std::make_unique<StreamHeaderTrackMessage>(); parser.ProcessData( message->PacketSample().substr(0, message->total_message_size() - 1), false); parser.ProcessData(absl::string_view(), true); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_EQ(visitor_.parsing_error_, "FIN received at an unexpected point in the stream"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, DataAfterFin) { MoqtControlParser parser(kRawQuic, visitor_); parser.ProcessData(absl::string_view(), true); parser.ProcessData("foo", false); EXPECT_EQ(visitor_.parsing_error_, "Data after end of stream"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, InvalidObjectStatus) { MoqtDataParser parser(&visitor_); char stream_header_subgroup[] = { 0x04, 0x03, 0x04, 0x05, 0x08, 0x07, 0x06, 0x00, 0x0f, }; parser.ProcessData( absl::string_view(stream_header_subgroup, sizeof(stream_header_subgroup)), false); EXPECT_EQ(visitor_.parsing_error_, "Invalid object status provided"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, Setup2KB) { MoqtControlParser parser(kRawQuic, visitor_); char big_message[2 * kMaxMessageHeaderSize]; quic::QuicDataWriter writer(sizeof(big_message), big_message); writer.WriteVarInt62(static_cast<uint64_t>(MoqtMessageType::kServerSetup)); writer.WriteVarInt62(0x1); writer.WriteVarInt62(0x1); writer.WriteVarInt62(0xbeef); writer.WriteVarInt62(kMaxMessageHeaderSize); writer.WriteRepeatedByte(0x04, kMaxMessageHeaderSize); parser.ProcessData(absl::string_view(big_message, writer.length() - 1), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "Cannot parse non-OBJECT messages > 2KB"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kInternalError); } TEST_F(MoqtMessageSpecificTest, UnknownMessageType) { MoqtControlParser parser(kRawQuic, visitor_); char message[4]; quic::QuicDataWriter writer(sizeof(message), message); writer.WriteVarInt62(0xbeef); parser.ProcessData(absl::string_view(message, writer.length()), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "Unknown message type"); } TEST_F(MoqtMessageSpecificTest, LatestGroup) { MoqtControlParser parser(kRawQuic, visitor_); char subscribe[] = { 0x03, 0x01, 0x02, 0x01, 0x03, 0x66, 0x6f, 0x6f, 0x04, 0x61, 0x62, 0x63, 0x64, 0x20, 0x02, 0x01, 0x01, 0x02, 0x03, 0x62, 0x61, 0x72, }; parser.ProcessData(absl::string_view(subscribe, sizeof(subscribe)), false); EXPECT_EQ(visitor_.messages_received_, 1); ASSERT_TRUE(visitor_.last_message_.has_value()); MoqtSubscribe message = std::get<MoqtSubscribe>(visitor_.last_message_.value()); EXPECT_FALSE(message.start_group.has_value()); EXPECT_EQ(message.start_object, 0); EXPECT_FALSE(message.end_group.has_value()); EXPECT_FALSE(message.end_object.has_value()); } TEST_F(MoqtMessageSpecificTest, LatestObject) { MoqtControlParser parser(kRawQuic, visitor_); char subscribe[] = { 0x03, 0x01, 0x02, 0x01, 0x03, 0x66, 0x6f, 0x6f, 0x04, 0x61, 0x62, 0x63, 0x64, 0x20, 0x02, 0x02, 0x01, 0x02, 0x03, 0x62, 0x61, 0x72, }; parser.ProcessData(absl::string_view(subscribe, sizeof(subscribe)), false); EXPECT_EQ(visitor_.messages_received_, 1); EXPECT_FALSE(visitor_.parsing_error_.has_value()); MoqtSubscribe message = std::get<MoqtSubscribe>(visitor_.last_message_.value()); EXPECT_FALSE(message.start_group.has_value()); EXPECT_FALSE(message.start_object.has_value()); EXPECT_FALSE(message.end_group.has_value()); EXPECT_FALSE(message.end_object.has_value()); } TEST_F(MoqtMessageSpecificTest, InvalidDeliveryOrder) { MoqtControlParser parser(kRawQuic, visitor_); char subscribe[] = { 0x03, 0x01, 0x02, 0x01, 0x03, 0x66, 0x6f, 0x6f, 0x04, 0x61, 0x62, 0x63, 0x64, 0x20, 0x08, 0x01, 0x01, 0x02, 0x03, 0x62, 0x61, 0x72, }; parser.ProcessData(absl::string_view(subscribe, sizeof(subscribe)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_THAT(visitor_.parsing_error_, Optional(HasSubstr("group order"))); } TEST_F(MoqtMessageSpecificTest, AbsoluteStart) { MoqtControlParser parser(kRawQuic, visitor_); char subscribe[] = { 0x03, 0x01, 0x02, 0x01, 0x03, 0x66, 0x6f, 0x6f, 0x04, 0x61, 0x62, 0x63, 0x64, 0x20, 0x02, 0x03, 0x04, 0x01, 0x01, 0x02, 0x03, 0x62, 0x61, 0x72, }; parser.ProcessData(absl::string_view(subscribe, sizeof(subscribe)), false); EXPECT_EQ(visitor_.messages_received_, 1); EXPECT_FALSE(visitor_.parsing_error_.has_value()); MoqtSubscribe message = std::get<MoqtSubscribe>(visitor_.last_message_.value()); EXPECT_EQ(message.start_group.value(), 4); EXPECT_EQ(message.start_object.value(), 1); EXPECT_FALSE(message.end_group.has_value()); EXPECT_FALSE(message.end_object.has_value()); } TEST_F(MoqtMessageSpecificTest, AbsoluteRangeExplicitEndObject) { MoqtControlParser parser(kRawQuic, visitor_); char subscribe[] = { 0x03, 0x01, 0x02, 0x01, 0x03, 0x66, 0x6f, 0x6f, 0x04, 0x61, 0x62, 0x63, 0x64, 0x20, 0x02, 0x04, 0x04, 0x01, 0x07, 0x03, 0x01, 0x02, 0x03, 0x62, 0x61, 0x72, }; parser.ProcessData(absl::string_view(subscribe, sizeof(subscribe)), false); EXPECT_EQ(visitor_.messages_received_, 1); EXPECT_FALSE(visitor_.parsing_error_.has_value()); MoqtSubscribe message = std::get<MoqtSubscribe>(visitor_.last_message_.value()); EXPECT_EQ(message.start_group.value(), 4); EXPECT_EQ(message.start_object.value(), 1); EXPECT_EQ(message.end_group.value(), 7); EXPECT_EQ(message.end_object.value(), 2); } TEST_F(MoqtMessageSpecificTest, AbsoluteRangeWholeEndGroup) { MoqtControlParser parser(kRawQuic, visitor_); char subscribe[] = { 0x03, 0x01, 0x02, 0x01, 0x03, 0x66, 0x6f, 0x6f, 0x04, 0x61, 0x62, 0x63, 0x64, 0x20, 0x02, 0x04, 0x04, 0x01, 0x07, 0x00, 0x01, 0x02, 0x03, 0x62, 0x61, 0x72, }; parser.ProcessData(absl::string_view(subscribe, sizeof(subscribe)), false); EXPECT_EQ(visitor_.messages_received_, 1); EXPECT_FALSE(visitor_.parsing_error_.has_value()); MoqtSubscribe message = std::get<MoqtSubscribe>(visitor_.last_message_.value()); EXPECT_EQ(message.start_group.value(), 4); EXPECT_EQ(message.start_object.value(), 1); EXPECT_EQ(message.end_group.value(), 7); EXPECT_FALSE(message.end_object.has_value()); } TEST_F(MoqtMessageSpecificTest, AbsoluteRangeEndGroupTooLow) { MoqtControlParser parser(kRawQuic, visitor_); char subscribe[] = { 0x03, 0x01, 0x02, 0x01, 0x03, 0x66, 0x6f, 0x6f, 0x04, 0x61, 0x62, 0x63, 0x64, 0x20, 0x02, 0x04, 0x04, 0x01, 0x03, 0x00, 0x01, 0x02, 0x03, 0x62, 0x61, 0x72, }; parser.ProcessData(absl::string_view(subscribe, sizeof(subscribe)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "End group is less than start group"); } TEST_F(MoqtMessageSpecificTest, AbsoluteRangeExactlyOneObject) { MoqtControlParser parser(kRawQuic, visitor_); char subscribe[] = { 0x03, 0x01, 0x02, 0x01, 0x03, 0x66, 0x6f, 0x6f, 0x04, 0x61, 0x62, 0x63, 0x64, 0x20, 0x02, 0x04, 0x04, 0x01, 0x04, 0x02, 0x00, }; parser.ProcessData(absl::string_view(subscribe, sizeof(subscribe)), false); EXPECT_EQ(visitor_.messages_received_, 1); } TEST_F(MoqtMessageSpecificTest, SubscribeUpdateExactlyOneObject) { MoqtControlParser parser(kRawQuic, visitor_); char subscribe_update[] = { 0x02, 0x02, 0x03, 0x01, 0x04, 0x07, 0x20, 0x00, }; parser.ProcessData( absl::string_view(subscribe_update, sizeof(subscribe_update)), false); EXPECT_EQ(visitor_.messages_received_, 1); } TEST_F(MoqtMessageSpecificTest, SubscribeUpdateEndGroupTooLow) { MoqtControlParser parser(kRawQuic, visitor_); char subscribe_update[] = { 0x02, 0x02, 0x03, 0x01, 0x03, 0x06, 0x20, 0x01, 0x02, 0x03, 0x62, 0x61, 0x72, }; parser.ProcessData( absl::string_view(subscribe_update, sizeof(subscribe_update)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "End group is less than start group"); } TEST_F(MoqtMessageSpecificTest, AbsoluteRangeEndObjectTooLow) { MoqtControlParser parser(kRawQuic, visitor_); char subscribe[] = { 0x03, 0x01, 0x02, 0x01, 0x03, 0x66, 0x6f, 0x6f, 0x04, 0x61, 0x62, 0x63, 0x64, 0x20, 0x02, 0x04, 0x04, 0x01, 0x04, 0x01, 0x01, 0x02, 0x03, 0x62, 0x61, 0x72, }; parser.ProcessData(absl::string_view(subscribe, sizeof(subscribe)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "End object comes before start object"); } TEST_F(MoqtMessageSpecificTest, SubscribeUpdateEndObjectTooLow) { MoqtControlParser parser(kRawQuic, visitor_); char subscribe_update[] = { 0x02, 0x02, 0x03, 0x02, 0x04, 0x01, 0xf0, 0x00, }; parser.ProcessData( absl::string_view(subscribe_update, sizeof(subscribe_update)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "End object comes before start object"); } TEST_F(MoqtMessageSpecificTest, SubscribeUpdateNoEndGroup) { MoqtControlParser parser(kRawQuic, visitor_); char subscribe_update[] = { 0x02, 0x02, 0x03, 0x02, 0x00, 0x01, 0x20, 0x00, }; parser.ProcessData( absl::string_view(subscribe_update, sizeof(subscribe_update)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "SUBSCRIBE_UPDATE has end_object but no end_group"); } TEST_F(MoqtMessageSpecificTest, ObjectAckNegativeDelta) { MoqtControlParser parser(kRawQuic, visitor_); char object_ack[] = { 0x71, 0x84, 0x01, 0x10, 0x20, 0x40, 0x81, }; parser.ProcessData(absl::string_view(object_ack, sizeof(object_ack)), false); EXPECT_EQ(visitor_.parsing_error_, std::nullopt); ASSERT_EQ(visitor_.messages_received_, 1); MoqtObjectAck message = std::get<MoqtObjectAck>(visitor_.last_message_.value()); EXPECT_EQ(message.subscribe_id, 0x01); EXPECT_EQ(message.group_id, 0x10); EXPECT_EQ(message.object_id, 0x20); EXPECT_EQ(message.delta_from_deadline, quic::QuicTimeDelta::FromMicroseconds(-0x40)); } TEST_F(MoqtMessageSpecificTest, AllMessagesTogether) { char buffer[5000]; MoqtControlParser parser(kRawQuic, visitor_); size_t write = 0; size_t read = 0; int fully_received = 0; std::unique_ptr<TestMessageBase> prev_message = nullptr; for (MoqtMessageType type : kMessageTypes) { std::unique_ptr<TestMessageBase> message = CreateTestMessage(type, kRawQuic); memcpy(buffer + write, message->PacketSample().data(), message->total_message_size()); size_t new_read = write + message->total_message_size() / 2; parser.ProcessData(absl::string_view(buffer + read, new_read - read), false); EXPECT_EQ(visitor_.messages_received_, fully_received); if (prev_message != nullptr) { EXPECT_TRUE(prev_message->EqualFieldValues(*visitor_.last_message_)); } fully_received++; read = new_read; write += message->total_message_size(); prev_message = std::move(message); } parser.ProcessData(absl::string_view(buffer + read, write - read), true); EXPECT_EQ(visitor_.messages_received_, fully_received); EXPECT_TRUE(prev_message->EqualFieldValues(*visitor_.last_message_)); EXPECT_FALSE(visitor_.parsing_error_.has_value()); } TEST_F(MoqtMessageSpecificTest, DatagramSuccessful) { ObjectDatagramMessage message; MoqtObject object; absl::string_view payload = ParseDatagram(message.PacketSample(), object); TestMessageBase::MessageStructuredData object_metadata = TestMessageBase::MessageStructuredData(object); EXPECT_TRUE(message.EqualFieldValues(object_metadata)); EXPECT_EQ(payload, "foo"); } TEST_F(MoqtMessageSpecificTest, WrongMessageInDatagram) { StreamHeaderSubgroupMessage message; MoqtObject object; absl::string_view payload = ParseDatagram(message.PacketSample(), object); EXPECT_TRUE(payload.empty()); } TEST_F(MoqtMessageSpecificTest, TruncatedDatagram) { ObjectDatagramMessage message; message.set_wire_image_size(4); MoqtObject object; absl::string_view payload = ParseDatagram(message.PacketSample(), object); EXPECT_TRUE(payload.empty()); } TEST_F(MoqtMessageSpecificTest, VeryTruncatedDatagram) { char message = 0x40; MoqtObject object; absl::string_view payload = ParseDatagram(absl::string_view(&message, sizeof(message)), object); EXPECT_TRUE(payload.empty()); } TEST_F(MoqtMessageSpecificTest, SubscribeOkInvalidContentExists) { MoqtControlParser parser(kRawQuic, visitor_); SubscribeOkMessage subscribe_ok; subscribe_ok.SetInvalidContentExists(); parser.ProcessData(subscribe_ok.PacketSample(), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "SUBSCRIBE_OK ContentExists has invalid value"); } TEST_F(MoqtMessageSpecificTest, SubscribeOkInvalidDeliveryOrder) { MoqtControlParser parser(kRawQuic, visitor_); SubscribeOkMessage subscribe_ok; subscribe_ok.SetInvalidDeliveryOrder(); parser.ProcessData(subscribe_ok.PacketSample(), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "Invalid group order value in SUBSCRIBE_OK"); } TEST_F(MoqtMessageSpecificTest, SubscribeDoneInvalidContentExists) { MoqtControlParser parser(kRawQuic, visitor_); SubscribeDoneMessage subscribe_done; subscribe_done.SetInvalidContentExists(); parser.ProcessData(subscribe_done.PacketSample(), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "SUBSCRIBE_DONE ContentExists has invalid value"); } TEST_F(MoqtMessageSpecificTest, PaddingStream) { MoqtDataParser parser(&visitor_); std::string buffer(32, '\0'); quic::QuicDataWriter writer(buffer.size(), buffer.data()); ASSERT_TRUE(writer.WriteVarInt62( static_cast<uint64_t>(MoqtDataStreamType::kPadding))); for (int i = 0; i < 100; ++i) { parser.ProcessData(buffer, false); ASSERT_EQ(visitor_.messages_received_, 0); ASSERT_EQ(visitor_.parsing_error_, std::nullopt); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/moqt/moqt_parser.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/moqt/moqt_parser_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
d64bcc05-1b16-4b31-85e6-3afedbba556f
cpp
google/quiche
moqt_framer
quiche/quic/moqt/moqt_framer.cc
quiche/quic/moqt/moqt_framer_test.cc
#include "quiche/quic/moqt/moqt_framer.h" #include <cstddef> #include <cstdint> #include <cstdlib> #include <optional> #include <string> #include <type_traits> #include <utility> #include "absl/container/inlined_vector.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/quic/moqt/moqt_priority.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_buffer_allocator.h" #include "quiche/common/quiche_data_writer.h" #include "quiche/common/simple_buffer_allocator.h" #include "quiche/common/wire_serialization.h" namespace moqt { namespace { using ::quiche::QuicheBuffer; using ::quiche::WireBytes; using ::quiche::WireOptional; using ::quiche::WireSpan; using ::quiche::WireStringWithVarInt62Length; using ::quiche::WireUint8; using ::quiche::WireVarInt62; struct StringParameter { template <typename Enum> StringParameter(Enum type, absl::string_view data) : type(static_cast<uint64_t>(type)), data(data) { static_assert(std::is_enum_v<Enum>); } uint64_t type; absl::string_view data; }; class WireStringParameter { public: using DataType = StringParameter; explicit WireStringParameter(const StringParameter& parameter) : parameter_(parameter) {} size_t GetLengthOnWire() { return quiche::ComputeLengthOnWire( WireVarInt62(parameter_.type), WireStringWithVarInt62Length(parameter_.data)); } absl::Status SerializeIntoWriter(quiche::QuicheDataWriter& writer) { return quiche::SerializeIntoWriter( writer, WireVarInt62(parameter_.type), WireStringWithVarInt62Length(parameter_.data)); } private: const StringParameter& parameter_; }; struct IntParameter { template <typename Enum, typename Param> IntParameter(Enum type, Param value) : type(static_cast<uint64_t>(type)), value(static_cast<uint64_t>(value)) { static_assert(std::is_enum_v<Enum>); static_assert(std::is_enum_v<Param> || std::is_unsigned_v<Param>); } uint64_t type; uint64_t value; }; class WireIntParameter { public: using DataType = IntParameter; explicit WireIntParameter(const IntParameter& parameter) : parameter_(parameter) {} size_t GetLengthOnWire() { return quiche::ComputeLengthOnWire( WireVarInt62(parameter_.type), WireVarInt62(NeededVarIntLen(parameter_.value)), WireVarInt62(parameter_.value)); } absl::Status SerializeIntoWriter(quiche::QuicheDataWriter& writer) { return quiche::SerializeIntoWriter( writer, WireVarInt62(parameter_.type), WireVarInt62(NeededVarIntLen(parameter_.value)), WireVarInt62(parameter_.value)); } private: size_t NeededVarIntLen(const uint64_t value) { return static_cast<size_t>(quic::QuicDataWriter::GetVarInt62Len(value)); } const IntParameter& parameter_; }; class WireSubscribeParameterList { public: explicit WireSubscribeParameterList(const MoqtSubscribeParameters& list) : list_(list) {} size_t GetLengthOnWire() { auto string_parameters = StringParameters(); auto int_parameters = IntParameters(); return quiche::ComputeLengthOnWire( WireVarInt62(string_parameters.size() + int_parameters.size()), WireSpan<WireStringParameter>(string_parameters), WireSpan<WireIntParameter>(int_parameters)); } absl::Status SerializeIntoWriter(quiche::QuicheDataWriter& writer) { auto string_parameters = StringParameters(); auto int_parameters = IntParameters(); return quiche::SerializeIntoWriter( writer, WireVarInt62(string_parameters.size() + int_parameters.size()), WireSpan<WireStringParameter>(string_parameters), WireSpan<WireIntParameter>(int_parameters)); } private: absl::InlinedVector<StringParameter, 1> StringParameters() const { absl::InlinedVector<StringParameter, 1> result; if (list_.authorization_info.has_value()) { result.push_back( StringParameter(MoqtTrackRequestParameter::kAuthorizationInfo, *list_.authorization_info)); } return result; } absl::InlinedVector<IntParameter, 3> IntParameters() const { absl::InlinedVector<IntParameter, 3> result; if (list_.delivery_timeout.has_value()) { QUICHE_DCHECK_GE(*list_.delivery_timeout, quic::QuicTimeDelta::Zero()); result.push_back(IntParameter( MoqtTrackRequestParameter::kDeliveryTimeout, static_cast<uint64_t>(list_.delivery_timeout->ToMilliseconds()))); } if (list_.max_cache_duration.has_value()) { QUICHE_DCHECK_GE(*list_.max_cache_duration, quic::QuicTimeDelta::Zero()); result.push_back(IntParameter( MoqtTrackRequestParameter::kMaxCacheDuration, static_cast<uint64_t>(list_.max_cache_duration->ToMilliseconds()))); } if (list_.object_ack_window.has_value()) { QUICHE_DCHECK_GE(*list_.object_ack_window, quic::QuicTimeDelta::Zero()); result.push_back(IntParameter( MoqtTrackRequestParameter::kOackWindowSize, static_cast<uint64_t>(list_.object_ack_window->ToMicroseconds()))); } return result; } const MoqtSubscribeParameters& list_; }; class WireFullTrackName { public: using DataType = FullTrackName; WireFullTrackName(const FullTrackName& name, bool includes_name) : name_(name), includes_name_(includes_name) {} size_t GetLengthOnWire() { return quiche::ComputeLengthOnWire( WireVarInt62(num_elements()), WireSpan<WireStringWithVarInt62Length, std::string>(name_.tuple())); } absl::Status SerializeIntoWriter(quiche::QuicheDataWriter& writer) { return quiche::SerializeIntoWriter( writer, WireVarInt62(num_elements()), WireSpan<WireStringWithVarInt62Length, std::string>(name_.tuple())); } private: size_t num_elements() const { return includes_name_ ? (name_.tuple().size() - 1) : name_.tuple().size(); } const FullTrackName& name_; const bool includes_name_; }; template <typename... Ts> QuicheBuffer Serialize(Ts... data) { absl::StatusOr<QuicheBuffer> buffer = quiche::SerializeIntoBuffer( quiche::SimpleBufferAllocator::Get(), data...); if (!buffer.ok()) { QUICHE_BUG(moqt_failed_serialization) << "Failed to serialize MoQT frame: " << buffer.status(); return QuicheBuffer(); } return *std::move(buffer); } WireUint8 WireDeliveryOrder(std::optional<MoqtDeliveryOrder> delivery_order) { if (!delivery_order.has_value()) { return WireUint8(0x00); } switch (*delivery_order) { case MoqtDeliveryOrder::kAscending: return WireUint8(0x01); case MoqtDeliveryOrder::kDescending: return WireUint8(0x02); } QUICHE_NOTREACHED(); return WireUint8(0xff); } uint64_t SignedVarintSerializedForm(int64_t value) { if (value < 0) { return ((-value) << 1) | 0x01; } return value << 1; } } quiche::QuicheBuffer MoqtFramer::SerializeObjectHeader( const MoqtObject& message, bool is_first_in_stream) { if (!ValidateObjectMetadata(message)) { QUIC_BUG(quic_bug_serialize_object_header_01) << "Object metadata is invalid"; return quiche::QuicheBuffer(); } if (message.forwarding_preference == MoqtForwardingPreference::kDatagram) { QUIC_BUG(quic_bug_serialize_object_header_02) << "Datagrams use SerializeObjectDatagram()"; return quiche::QuicheBuffer(); } if (!is_first_in_stream) { switch (message.forwarding_preference) { case MoqtForwardingPreference::kTrack: return (message.payload_length == 0) ? Serialize(WireVarInt62(message.group_id), WireVarInt62(message.object_id), WireVarInt62(message.payload_length), WireVarInt62(message.object_status)) : Serialize(WireVarInt62(message.group_id), WireVarInt62(message.object_id), WireVarInt62(message.payload_length)); case MoqtForwardingPreference::kSubgroup: return (message.payload_length == 0) ? Serialize(WireVarInt62(message.object_id), WireVarInt62(message.payload_length), WireVarInt62(static_cast<uint64_t>( message.object_status))) : Serialize(WireVarInt62(message.object_id), WireVarInt62(message.payload_length)); default: QUICHE_NOTREACHED(); return quiche::QuicheBuffer(); } } MoqtDataStreamType message_type = GetMessageTypeForForwardingPreference(message.forwarding_preference); switch (message.forwarding_preference) { case MoqtForwardingPreference::kTrack: return (message.payload_length == 0) ? Serialize(WireVarInt62(message_type), WireVarInt62(message.subscribe_id), WireVarInt62(message.track_alias), WireUint8(message.publisher_priority), WireVarInt62(message.group_id), WireVarInt62(message.object_id), WireVarInt62(message.payload_length), WireVarInt62(message.object_status)) : Serialize(WireVarInt62(message_type), WireVarInt62(message.subscribe_id), WireVarInt62(message.track_alias), WireUint8(message.publisher_priority), WireVarInt62(message.group_id), WireVarInt62(message.object_id), WireVarInt62(message.payload_length)); case MoqtForwardingPreference::kSubgroup: return (message.payload_length == 0) ? Serialize(WireVarInt62(message_type), WireVarInt62(message.subscribe_id), WireVarInt62(message.track_alias), WireVarInt62(message.group_id), WireVarInt62(*message.subgroup_id), WireUint8(message.publisher_priority), WireVarInt62(message.object_id), WireVarInt62(message.payload_length), WireVarInt62(message.object_status)) : Serialize(WireVarInt62(message_type), WireVarInt62(message.subscribe_id), WireVarInt62(message.track_alias), WireVarInt62(message.group_id), WireVarInt62(*message.subgroup_id), WireUint8(message.publisher_priority), WireVarInt62(message.object_id), WireVarInt62(message.payload_length)); case MoqtForwardingPreference::kDatagram: QUICHE_NOTREACHED(); return quiche::QuicheBuffer(); } } quiche::QuicheBuffer MoqtFramer::SerializeObjectDatagram( const MoqtObject& message, absl::string_view payload) { if (!ValidateObjectMetadata(message)) { QUIC_BUG(quic_bug_serialize_object_datagram_01) << "Object metadata is invalid"; return quiche::QuicheBuffer(); } if (message.forwarding_preference != MoqtForwardingPreference::kDatagram) { QUIC_BUG(quic_bug_serialize_object_datagram_02) << "Only datagrams use SerializeObjectDatagram()"; return quiche::QuicheBuffer(); } if (message.payload_length != payload.length()) { QUIC_BUG(quic_bug_serialize_object_datagram_03) << "Payload length does not match payload"; return quiche::QuicheBuffer(); } if (message.payload_length == 0) { return Serialize( WireVarInt62(MoqtDataStreamType::kObjectDatagram), WireVarInt62(message.subscribe_id), WireVarInt62(message.track_alias), WireVarInt62(message.group_id), WireVarInt62(message.object_id), WireUint8(message.publisher_priority), WireVarInt62(message.payload_length), WireVarInt62(message.object_status)); } return Serialize( WireVarInt62(MoqtDataStreamType::kObjectDatagram), WireVarInt62(message.subscribe_id), WireVarInt62(message.track_alias), WireVarInt62(message.group_id), WireVarInt62(message.object_id), WireUint8(message.publisher_priority), WireVarInt62(message.payload_length), WireBytes(payload)); } quiche::QuicheBuffer MoqtFramer::SerializeClientSetup( const MoqtClientSetup& message) { absl::InlinedVector<IntParameter, 1> int_parameters; absl::InlinedVector<StringParameter, 1> string_parameters; if (message.role.has_value()) { int_parameters.push_back( IntParameter(MoqtSetupParameter::kRole, *message.role)); } if (message.max_subscribe_id.has_value()) { int_parameters.push_back(IntParameter(MoqtSetupParameter::kMaxSubscribeId, *message.max_subscribe_id)); } if (message.supports_object_ack) { int_parameters.push_back( IntParameter(MoqtSetupParameter::kSupportObjectAcks, 1u)); } if (!using_webtrans_ && message.path.has_value()) { string_parameters.push_back( StringParameter(MoqtSetupParameter::kPath, *message.path)); } return Serialize( WireVarInt62(MoqtMessageType::kClientSetup), WireVarInt62(message.supported_versions.size()), WireSpan<WireVarInt62, MoqtVersion>(message.supported_versions), WireVarInt62(string_parameters.size() + int_parameters.size()), WireSpan<WireIntParameter>(int_parameters), WireSpan<WireStringParameter>(string_parameters)); } quiche::QuicheBuffer MoqtFramer::SerializeServerSetup( const MoqtServerSetup& message) { absl::InlinedVector<IntParameter, 1> int_parameters; if (message.role.has_value()) { int_parameters.push_back( IntParameter(MoqtSetupParameter::kRole, *message.role)); } if (message.max_subscribe_id.has_value()) { int_parameters.push_back(IntParameter(MoqtSetupParameter::kMaxSubscribeId, *message.max_subscribe_id)); } if (message.supports_object_ack) { int_parameters.push_back( IntParameter(MoqtSetupParameter::kSupportObjectAcks, 1u)); } return Serialize(WireVarInt62(MoqtMessageType::kServerSetup), WireVarInt62(message.selected_version), WireVarInt62(int_parameters.size()), WireSpan<WireIntParameter>(int_parameters)); } quiche::QuicheBuffer MoqtFramer::SerializeSubscribe( const MoqtSubscribe& message) { MoqtFilterType filter_type = GetFilterType(message); if (filter_type == MoqtFilterType::kNone) { QUICHE_BUG(MoqtFramer_invalid_subscribe) << "Invalid object range"; return quiche::QuicheBuffer(); } switch (filter_type) { case MoqtFilterType::kLatestGroup: case MoqtFilterType::kLatestObject: return Serialize( WireVarInt62(MoqtMessageType::kSubscribe), WireVarInt62(message.subscribe_id), WireVarInt62(message.track_alias), WireFullTrackName(message.full_track_name, true), WireUint8(message.subscriber_priority), WireDeliveryOrder(message.group_order), WireVarInt62(filter_type), WireSubscribeParameterList(message.parameters)); case MoqtFilterType::kAbsoluteStart: return Serialize( WireVarInt62(MoqtMessageType::kSubscribe), WireVarInt62(message.subscribe_id), WireVarInt62(message.track_alias), WireFullTrackName(message.full_track_name, true), WireUint8(message.subscriber_priority), WireDeliveryOrder(message.group_order), WireVarInt62(filter_type), WireVarInt62(*message.start_group), WireVarInt62(*message.start_object), WireSubscribeParameterList(message.parameters)); case MoqtFilterType::kAbsoluteRange: return Serialize( WireVarInt62(MoqtMessageType::kSubscribe), WireVarInt62(message.subscribe_id), WireVarInt62(message.track_alias), WireFullTrackName(message.full_track_name, true), WireUint8(message.subscriber_priority), WireDeliveryOrder(message.group_order), WireVarInt62(filter_type), WireVarInt62(*message.start_group), WireVarInt62(*message.start_object), WireVarInt62(*message.end_group), WireVarInt62(message.end_object.has_value() ? *message.end_object + 1 : 0), WireSubscribeParameterList(message.parameters)); default: QUICHE_BUG(MoqtFramer_end_group_missing) << "Subscribe framing error."; return quiche::QuicheBuffer(); } } quiche::QuicheBuffer MoqtFramer::SerializeSubscribeOk( const MoqtSubscribeOk& message) { if (message.parameters.authorization_info.has_value()) { QUICHE_BUG(MoqtFramer_invalid_subscribe_ok) << "SUBSCRIBE_OK with delivery timeout"; } if (message.largest_id.has_value()) { return Serialize(WireVarInt62(MoqtMessageType::kSubscribeOk), WireVarInt62(message.subscribe_id), WireVarInt62(message.expires.ToMilliseconds()), WireDeliveryOrder(message.group_order), WireUint8(1), WireVarInt62(message.largest_id->group), WireVarInt62(message.largest_id->object), WireSubscribeParameterList(message.parameters)); } return Serialize(WireVarInt62(MoqtMessageType::kSubscribeOk), WireVarInt62(message.subscribe_id), WireVarInt62(message.expires.ToMilliseconds()), WireDeliveryOrder(message.group_order), WireUint8(0), WireSubscribeParameterList(message.parameters)); } quiche::QuicheBuffer MoqtFramer::SerializeSubscribeError( const MoqtSubscribeError& message) { return Serialize(WireVarInt62(MoqtMessageType::kSubscribeError), WireVarInt62(message.subscribe_id), WireVarInt62(message.error_code), WireStringWithVarInt62Length(message.reason_phrase), WireVarInt62(message.track_alias)); } quiche::QuicheBuffer MoqtFramer::SerializeUnsubscribe( const MoqtUnsubscribe& message) { return Serialize(WireVarInt62(MoqtMessageType::kUnsubscribe), WireVarInt62(message.subscribe_id)); } quiche::QuicheBuffer MoqtFramer::SerializeSubscribeDone( const MoqtSubscribeDone& message) { if (message.final_id.has_value()) { return Serialize(WireVarInt62(MoqtMessageType::kSubscribeDone), WireVarInt62(message.subscribe_id), WireVarInt62(message.status_code), WireStringWithVarInt62Length(message.reason_phrase), WireUint8(1), WireVarInt62(message.final_id->group), WireVarInt62(message.final_id->object)); } return Serialize( WireVarInt62(MoqtMessageType::kSubscribeDone), WireVarInt62(message.subscribe_id), WireVarInt62(message.status_code), WireStringWithVarInt62Length(message.reason_phrase), WireUint8(0)); } quiche::QuicheBuffer MoqtFramer::SerializeSubscribeUpdate( const MoqtSubscribeUpdate& message) { if (message.parameters.authorization_info.has_value()) { QUICHE_BUG(MoqtFramer_invalid_subscribe_update) << "SUBSCRIBE_UPDATE with authorization info"; } uint64_t end_group = message.end_group.has_value() ? *message.end_group + 1 : 0; uint64_t end_object = message.end_object.has_value() ? *message.end_object + 1 : 0; if (end_group == 0 && end_object != 0) { QUICHE_BUG(MoqtFramer_invalid_subscribe_update) << "Invalid object range"; return quiche::QuicheBuffer(); } return Serialize( WireVarInt62(MoqtMessageType::kSubscribeUpdate), WireVarInt62(message.subscribe_id), WireVarInt62(message.start_group), WireVarInt62(message.start_object), WireVarInt62(end_group), WireVarInt62(end_object), WireUint8(message.subscriber_priority), WireSubscribeParameterList(message.parameters)); } quiche::QuicheBuffer MoqtFramer::SerializeAnnounce( const MoqtAnnounce& message) { if (message.parameters.delivery_timeout.has_value()) { QUICHE_BUG(MoqtFramer_invalid_announce) << "ANNOUNCE with delivery timeout"; } return Serialize( WireVarInt62(static_cast<uint64_t>(MoqtMessageType::kAnnounce)), WireFullTrackName(message.track_namespace, false), WireSubscribeParameterList(message.parameters)); } quiche::QuicheBuffer MoqtFramer::SerializeAnnounceOk( const MoqtAnnounceOk& message) { return Serialize(WireVarInt62(MoqtMessageType::kAnnounceOk), WireFullTrackName(message.track_namespace, false)); } quiche::QuicheBuffer MoqtFramer::SerializeAnnounceError( const MoqtAnnounceError& message) { return Serialize(WireVarInt62(MoqtMessageType::kAnnounceError), WireFullTrackName(message.track_namespace, false), WireVarInt62(message.error_code), WireStringWithVarInt62Length(message.reason_phrase)); } quiche::QuicheBuffer MoqtFramer::SerializeAnnounceCancel( const MoqtAnnounceCancel& message) { return Serialize(WireVarInt62(MoqtMessageType::kAnnounceCancel), WireFullTrackName(message.track_namespace, false), WireVarInt62(message.error_code), WireStringWithVarInt62Length(message.reason_phrase)); } quiche::QuicheBuffer MoqtFramer::SerializeTrackStatusRequest( const MoqtTrackStatusRequest& message) { return Serialize(WireVarInt62(MoqtMessageType::kTrackStatusRequest), WireFullTrackName(message.full_track_name, true)); } quiche::QuicheBuffer MoqtFramer::SerializeUnannounce( const MoqtUnannounce& message) { return Serialize(WireVarInt62(MoqtMessageType::kUnannounce), WireFullTrackName(message.track_namespace, false)); } quiche::QuicheBuffer MoqtFramer::SerializeTrackStatus( const MoqtTrackStatus& message) { return Serialize(WireVarInt62(MoqtMessageType::kTrackStatus), WireFullTrackName(message.full_track_name, true), WireVarInt62(message.status_code), WireVarInt62(message.last_group), WireVarInt62(message.last_object)); } quiche::QuicheBuffer MoqtFramer::SerializeGoAway(const MoqtGoAway& message) { return Serialize(WireVarInt62(MoqtMessageType::kGoAway), WireStringWithVarInt62Length(message.new_session_uri)); } quiche::QuicheBuffer MoqtFramer::SerializeSubscribeNamespace( const MoqtSubscribeNamespace& message) { return Serialize(WireVarInt62(MoqtMessageType::kSubscribeNamespace), WireFullTrackName(message.track_namespace, false), WireSubscribeParameterList(message.parameters)); } quiche::QuicheBuffer MoqtFramer::SerializeSubscribeNamespaceOk( const MoqtSubscribeNamespaceOk& message) { return Serialize(WireVarInt62(MoqtMessageType::kSubscribeNamespaceOk), WireFullTrackName(message.track_namespace, false)); } quiche::QuicheBuffer MoqtFramer::SerializeSubscribeNamespaceError( const MoqtSubscribeNamespaceError& message) { return Serialize(WireVarInt62(MoqtMessageType::kSubscribeNamespaceError), WireFullTrackName(message.track_namespace, false), WireVarInt62(message.error_code), WireStringWithVarInt62Length(message.reason_phrase)); } quiche::QuicheBuffer MoqtFramer::SerializeUnsubscribeNamespace( const MoqtUnsubscribeNamespace& message) { return Serialize(WireVarInt62(MoqtMessageType::kUnsubscribeNamespace), WireFullTrackName(message.track_namespace, false)); } quiche::QuicheBuffer MoqtFramer::SerializeMaxSubscribeId( const MoqtMaxSubscribeId& message) { return Serialize(WireVarInt62(MoqtMessageType::kMaxSubscribeId), WireVarInt62(message.max_subscribe_id)); } quiche::QuicheBuffer MoqtFramer::SerializeObjectAck( const MoqtObjectAck& message) { return Serialize(WireVarInt62(MoqtMessageType::kObjectAck), WireVarInt62(message.subscribe_id), WireVarInt62(message.group_id), WireVarInt62(message.object_id), WireVarInt62(SignedVarintSerializedForm( message.delta_from_deadline.ToMicroseconds()))); } bool MoqtFramer::ValidateObjectMetadata(const MoqtObject& object) { if (object.object_status != MoqtObjectStatus::kNormal && object.payload_length > 0) { return false; } if ((object.forwarding_preference == MoqtForwardingPreference::kSubgroup) != object.subgroup_id.has_value()) { return false; } return true; } }
#include "quiche/quic/moqt/moqt_framer.h" #include <cstddef> #include <cstdint> #include <memory> #include <optional> #include <string> #include <vector> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/quic/moqt/test_tools/moqt_test_message.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/common/quiche_buffer_allocator.h" #include "quiche/common/simple_buffer_allocator.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace moqt::test { struct MoqtFramerTestParams { MoqtFramerTestParams(MoqtMessageType message_type, bool uses_web_transport) : message_type(message_type), uses_web_transport(uses_web_transport) {} MoqtMessageType message_type; bool uses_web_transport; }; std::vector<MoqtFramerTestParams> GetMoqtFramerTestParams() { std::vector<MoqtFramerTestParams> params; std::vector<MoqtMessageType> message_types = { MoqtMessageType::kSubscribe, MoqtMessageType::kSubscribeOk, MoqtMessageType::kSubscribeError, MoqtMessageType::kUnsubscribe, MoqtMessageType::kSubscribeDone, MoqtMessageType::kAnnounceCancel, MoqtMessageType::kTrackStatusRequest, MoqtMessageType::kTrackStatus, MoqtMessageType::kAnnounce, MoqtMessageType::kAnnounceOk, MoqtMessageType::kAnnounceError, MoqtMessageType::kUnannounce, MoqtMessageType::kGoAway, MoqtMessageType::kSubscribeNamespace, MoqtMessageType::kSubscribeNamespaceOk, MoqtMessageType::kSubscribeNamespaceError, MoqtMessageType::kUnsubscribeNamespace, MoqtMessageType::kMaxSubscribeId, MoqtMessageType::kObjectAck, MoqtMessageType::kClientSetup, MoqtMessageType::kServerSetup, }; for (const MoqtMessageType message_type : message_types) { if (message_type == MoqtMessageType::kClientSetup) { for (const bool uses_web_transport : {false, true}) { params.push_back( MoqtFramerTestParams(message_type, uses_web_transport)); } } else { params.push_back(MoqtFramerTestParams(message_type, true)); } } return params; } std::string ParamNameFormatter( const testing::TestParamInfo<MoqtFramerTestParams>& info) { return MoqtMessageTypeToString(info.param.message_type) + "_" + (info.param.uses_web_transport ? "WebTransport" : "QUIC"); } quiche::QuicheBuffer SerializeObject(MoqtFramer& framer, const MoqtObject& message, absl::string_view payload, bool is_first_in_stream) { MoqtObject adjusted_message = message; adjusted_message.payload_length = payload.size(); quiche::QuicheBuffer header = (message.forwarding_preference == MoqtForwardingPreference::kDatagram) ? framer.SerializeObjectDatagram(adjusted_message, payload) : framer.SerializeObjectHeader(adjusted_message, is_first_in_stream); if (header.empty()) { return quiche::QuicheBuffer(); } return quiche::QuicheBuffer::Copy( quiche::SimpleBufferAllocator::Get(), absl::StrCat(header.AsStringView(), payload)); } class MoqtFramerTest : public quic::test::QuicTestWithParam<MoqtFramerTestParams> { public: MoqtFramerTest() : message_type_(GetParam().message_type), webtrans_(GetParam().uses_web_transport), buffer_allocator_(quiche::SimpleBufferAllocator::Get()), framer_(buffer_allocator_, GetParam().uses_web_transport) {} std::unique_ptr<TestMessageBase> MakeMessage(MoqtMessageType message_type) { return CreateTestMessage(message_type, webtrans_); } quiche::QuicheBuffer SerializeMessage( TestMessageBase::MessageStructuredData& structured_data) { switch (message_type_) { case MoqtMessageType::kSubscribe: { auto data = std::get<MoqtSubscribe>(structured_data); return framer_.SerializeSubscribe(data); } case MoqtMessageType::kSubscribeOk: { auto data = std::get<MoqtSubscribeOk>(structured_data); return framer_.SerializeSubscribeOk(data); } case MoqtMessageType::kSubscribeError: { auto data = std::get<MoqtSubscribeError>(structured_data); return framer_.SerializeSubscribeError(data); } case MoqtMessageType::kUnsubscribe: { auto data = std::get<MoqtUnsubscribe>(structured_data); return framer_.SerializeUnsubscribe(data); } case MoqtMessageType::kSubscribeDone: { auto data = std::get<MoqtSubscribeDone>(structured_data); return framer_.SerializeSubscribeDone(data); } case MoqtMessageType::kAnnounce: { auto data = std::get<MoqtAnnounce>(structured_data); return framer_.SerializeAnnounce(data); } case moqt::MoqtMessageType::kAnnounceOk: { auto data = std::get<MoqtAnnounceOk>(structured_data); return framer_.SerializeAnnounceOk(data); } case moqt::MoqtMessageType::kAnnounceError: { auto data = std::get<MoqtAnnounceError>(structured_data); return framer_.SerializeAnnounceError(data); } case moqt::MoqtMessageType::kAnnounceCancel: { auto data = std::get<MoqtAnnounceCancel>(structured_data); return framer_.SerializeAnnounceCancel(data); } case moqt::MoqtMessageType::kTrackStatusRequest: { auto data = std::get<MoqtTrackStatusRequest>(structured_data); return framer_.SerializeTrackStatusRequest(data); } case MoqtMessageType::kUnannounce: { auto data = std::get<MoqtUnannounce>(structured_data); return framer_.SerializeUnannounce(data); } case moqt::MoqtMessageType::kTrackStatus: { auto data = std::get<MoqtTrackStatus>(structured_data); return framer_.SerializeTrackStatus(data); } case moqt::MoqtMessageType::kGoAway: { auto data = std::get<MoqtGoAway>(structured_data); return framer_.SerializeGoAway(data); } case moqt::MoqtMessageType::kSubscribeNamespace: { auto data = std::get<MoqtSubscribeNamespace>(structured_data); return framer_.SerializeSubscribeNamespace(data); } case moqt::MoqtMessageType::kSubscribeNamespaceOk: { auto data = std::get<MoqtSubscribeNamespaceOk>(structured_data); return framer_.SerializeSubscribeNamespaceOk(data); } case moqt::MoqtMessageType::kSubscribeNamespaceError: { auto data = std::get<MoqtSubscribeNamespaceError>(structured_data); return framer_.SerializeSubscribeNamespaceError(data); } case moqt::MoqtMessageType::kUnsubscribeNamespace: { auto data = std::get<MoqtUnsubscribeNamespace>(structured_data); return framer_.SerializeUnsubscribeNamespace(data); } case moqt::MoqtMessageType::kMaxSubscribeId: { auto data = std::get<MoqtMaxSubscribeId>(structured_data); return framer_.SerializeMaxSubscribeId(data); } case moqt::MoqtMessageType::kObjectAck: { auto data = std::get<MoqtObjectAck>(structured_data); return framer_.SerializeObjectAck(data); } case MoqtMessageType::kClientSetup: { auto data = std::get<MoqtClientSetup>(structured_data); return framer_.SerializeClientSetup(data); } case MoqtMessageType::kServerSetup: { auto data = std::get<MoqtServerSetup>(structured_data); return framer_.SerializeServerSetup(data); } default: return quiche::QuicheBuffer(); } } MoqtMessageType message_type_; bool webtrans_; quiche::SimpleBufferAllocator* buffer_allocator_; MoqtFramer framer_; }; INSTANTIATE_TEST_SUITE_P(MoqtFramerTests, MoqtFramerTest, testing::ValuesIn(GetMoqtFramerTestParams()), ParamNameFormatter); TEST_P(MoqtFramerTest, OneMessage) { auto message = MakeMessage(message_type_); auto structured_data = message->structured_data(); auto buffer = SerializeMessage(structured_data); EXPECT_EQ(buffer.size(), message->total_message_size()); quiche::test::CompareCharArraysWithHexError( "frame encoding", buffer.data(), buffer.size(), message->PacketSample().data(), message->PacketSample().size()); } class MoqtFramerSimpleTest : public quic::test::QuicTest { public: MoqtFramerSimpleTest() : buffer_allocator_(quiche::SimpleBufferAllocator::Get()), framer_(buffer_allocator_, true) {} quiche::SimpleBufferAllocator* buffer_allocator_; MoqtFramer framer_; const uint8_t* BufferAtOffset(quiche::QuicheBuffer& buffer, size_t offset) { const char* data = buffer.data(); return reinterpret_cast<const uint8_t*>(data + offset); } }; TEST_F(MoqtFramerSimpleTest, GroupMiddler) { auto header = std::make_unique<StreamHeaderSubgroupMessage>(); auto buffer1 = SerializeObject( framer_, std::get<MoqtObject>(header->structured_data()), "foo", true); EXPECT_EQ(buffer1.size(), header->total_message_size()); EXPECT_EQ(buffer1.AsStringView(), header->PacketSample()); auto middler = std::make_unique<StreamMiddlerSubgroupMessage>(); auto buffer2 = SerializeObject( framer_, std::get<MoqtObject>(middler->structured_data()), "bar", false); EXPECT_EQ(buffer2.size(), middler->total_message_size()); EXPECT_EQ(buffer2.AsStringView(), middler->PacketSample()); } TEST_F(MoqtFramerSimpleTest, TrackMiddler) { auto header = std::make_unique<StreamHeaderTrackMessage>(); auto buffer1 = SerializeObject( framer_, std::get<MoqtObject>(header->structured_data()), "foo", true); EXPECT_EQ(buffer1.size(), header->total_message_size()); EXPECT_EQ(buffer1.AsStringView(), header->PacketSample()); auto middler = std::make_unique<StreamMiddlerTrackMessage>(); auto buffer2 = SerializeObject( framer_, std::get<MoqtObject>(middler->structured_data()), "bar", false); EXPECT_EQ(buffer2.size(), middler->total_message_size()); EXPECT_EQ(buffer2.AsStringView(), middler->PacketSample()); } TEST_F(MoqtFramerSimpleTest, BadObjectInput) { MoqtObject object = { 3, 4, 5, 6, 7, MoqtObjectStatus::kNormal, MoqtForwardingPreference::kSubgroup, 8, 3, }; quiche::QuicheBuffer buffer; EXPECT_QUIC_BUG(buffer = framer_.SerializeObjectDatagram(object, "foo"), "Only datagrams use SerializeObjectDatagram()"); EXPECT_TRUE(buffer.empty()); object.subgroup_id = std::nullopt; EXPECT_QUIC_BUG(buffer = framer_.SerializeObjectHeader(object, false), "Object metadata is invalid"); EXPECT_TRUE(buffer.empty()); object.subgroup_id = 8; object.forwarding_preference = MoqtForwardingPreference::kTrack; EXPECT_QUIC_BUG(buffer = framer_.SerializeObjectHeader(object, false), "Object metadata is invalid"); EXPECT_TRUE(buffer.empty()); object.forwarding_preference = MoqtForwardingPreference::kSubgroup; object.object_status = MoqtObjectStatus::kEndOfGroup; EXPECT_QUIC_BUG(buffer = framer_.SerializeObjectHeader(object, false), "Object metadata is invalid"); EXPECT_TRUE(buffer.empty()); } TEST_F(MoqtFramerSimpleTest, BadDatagramInput) { MoqtObject object = { 3, 4, 5, 6, 7, MoqtObjectStatus::kNormal, MoqtForwardingPreference::kDatagram, std::nullopt, 3, }; quiche::QuicheBuffer buffer; EXPECT_QUIC_BUG(buffer = framer_.SerializeObjectHeader(object, false), "Datagrams use SerializeObjectDatagram()") EXPECT_TRUE(buffer.empty()); object.object_status = MoqtObjectStatus::kEndOfGroup; EXPECT_QUIC_BUG(buffer = framer_.SerializeObjectDatagram(object, "foo"), "Object metadata is invalid"); EXPECT_TRUE(buffer.empty()); object.object_status = MoqtObjectStatus::kNormal; object.subgroup_id = 8; EXPECT_QUIC_BUG(buffer = framer_.SerializeObjectDatagram(object, "foo"), "Object metadata is invalid"); EXPECT_TRUE(buffer.empty()); object.subgroup_id = std::nullopt; EXPECT_QUIC_BUG(buffer = framer_.SerializeObjectDatagram(object, "foobar"), "Payload length does not match payload"); EXPECT_TRUE(buffer.empty()); } TEST_F(MoqtFramerSimpleTest, Datagram) { auto datagram = std::make_unique<ObjectDatagramMessage>(); MoqtObject object = { 3, 4, 5, 6, 7, MoqtObjectStatus::kNormal, MoqtForwardingPreference::kDatagram, std::nullopt, 3, }; std::string payload = "foo"; quiche::QuicheBuffer buffer; buffer = framer_.SerializeObjectDatagram(object, payload); EXPECT_EQ(buffer.size(), datagram->total_message_size()); EXPECT_EQ(buffer.AsStringView(), datagram->PacketSample()); } TEST_F(MoqtFramerSimpleTest, AllSubscribeInputs) { for (std::optional<uint64_t> start_group : {std::optional<uint64_t>(), std::optional<uint64_t>(4)}) { for (std::optional<uint64_t> start_object : {std::optional<uint64_t>(), std::optional<uint64_t>(0)}) { for (std::optional<uint64_t> end_group : {std::optional<uint64_t>(), std::optional<uint64_t>(7)}) { for (std::optional<uint64_t> end_object : {std::optional<uint64_t>(), std::optional<uint64_t>(3)}) { MoqtSubscribe subscribe = { 3, 4, FullTrackName({"foo", "abcd"}), 0x20, std::nullopt, start_group, start_object, end_group, end_object, MoqtSubscribeParameters{"bar", std::nullopt, std::nullopt, std::nullopt}, }; quiche::QuicheBuffer buffer; MoqtFilterType expected_filter_type = MoqtFilterType::kNone; if (!start_group.has_value() && !start_object.has_value() && !end_group.has_value() && !end_object.has_value()) { expected_filter_type = MoqtFilterType::kLatestObject; } else if (!start_group.has_value() && start_object.has_value() && *start_object == 0 && !end_group.has_value() && !end_object.has_value()) { expected_filter_type = MoqtFilterType::kLatestGroup; } else if (start_group.has_value() && start_object.has_value() && !end_group.has_value() && !end_object.has_value()) { expected_filter_type = MoqtFilterType::kAbsoluteStart; } else if (start_group.has_value() && start_object.has_value() && end_group.has_value()) { expected_filter_type = MoqtFilterType::kAbsoluteRange; } if (expected_filter_type == MoqtFilterType::kNone) { EXPECT_QUIC_BUG(buffer = framer_.SerializeSubscribe(subscribe), "Invalid object range"); EXPECT_EQ(buffer.size(), 0); continue; } buffer = framer_.SerializeSubscribe(subscribe); const uint8_t* read = BufferAtOffset(buffer, 15); EXPECT_EQ(static_cast<MoqtFilterType>(*read), expected_filter_type); EXPECT_GT(buffer.size(), 0); if (expected_filter_type == MoqtFilterType::kAbsoluteRange && end_object.has_value()) { const uint8_t* object_id = read + 4; EXPECT_EQ(*object_id, *end_object + 1); } } } } } } TEST_F(MoqtFramerSimpleTest, SubscribeEndBeforeStart) { MoqtSubscribe subscribe = { 3, 4, FullTrackName({"foo", "abcd"}), 0x20, std::nullopt, std::optional<uint64_t>(4), std::optional<uint64_t>(3), std::optional<uint64_t>(3), std::nullopt, MoqtSubscribeParameters{"bar", std::nullopt, std::nullopt, std::nullopt}, }; quiche::QuicheBuffer buffer; EXPECT_QUIC_BUG(buffer = framer_.SerializeSubscribe(subscribe), "Invalid object range"); EXPECT_EQ(buffer.size(), 0); subscribe.end_group = 4; subscribe.end_object = 1; EXPECT_QUIC_BUG(buffer = framer_.SerializeSubscribe(subscribe), "Invalid object range"); EXPECT_EQ(buffer.size(), 0); } TEST_F(MoqtFramerSimpleTest, SubscribeLatestGroupNonzeroObject) { MoqtSubscribe subscribe = { 3, 4, FullTrackName({"foo", "abcd"}), 0x20, std::nullopt, std::nullopt, std::optional<uint64_t>(3), std::nullopt, std::nullopt, MoqtSubscribeParameters{"bar", std::nullopt, std::nullopt, std::nullopt}, }; quiche::QuicheBuffer buffer; EXPECT_QUIC_BUG(buffer = framer_.SerializeSubscribe(subscribe), "Invalid object range"); EXPECT_EQ(buffer.size(), 0); } TEST_F(MoqtFramerSimpleTest, SubscribeUpdateEndGroupOnly) { MoqtSubscribeUpdate subscribe_update = { 3, 4, 3, 4, std::nullopt, 0xaa, MoqtSubscribeParameters{std::nullopt, std::nullopt, std::nullopt, std::nullopt}, }; quiche::QuicheBuffer buffer; buffer = framer_.SerializeSubscribeUpdate(subscribe_update); EXPECT_GT(buffer.size(), 0); const uint8_t* end_group = BufferAtOffset(buffer, 4); EXPECT_EQ(*end_group, 5); const uint8_t* end_object = end_group + 1; EXPECT_EQ(*end_object, 0); } TEST_F(MoqtFramerSimpleTest, SubscribeUpdateIncrementsEnd) { MoqtSubscribeUpdate subscribe_update = { 3, 4, 3, 4, 6, 0xaa, MoqtSubscribeParameters{std::nullopt, std::nullopt, std::nullopt, std::nullopt}, }; quiche::QuicheBuffer buffer; buffer = framer_.SerializeSubscribeUpdate(subscribe_update); EXPECT_GT(buffer.size(), 0); const uint8_t* end_group = BufferAtOffset(buffer, 4); EXPECT_EQ(*end_group, 5); const uint8_t* end_object = end_group + 1; EXPECT_EQ(*end_object, 7); } TEST_F(MoqtFramerSimpleTest, SubscribeUpdateInvalidRange) { MoqtSubscribeUpdate subscribe_update = { 3, 4, 3, std::nullopt, 6, 0xaa, MoqtSubscribeParameters{std::nullopt, std::nullopt, std::nullopt, std::nullopt}, }; quiche::QuicheBuffer buffer; EXPECT_QUIC_BUG(buffer = framer_.SerializeSubscribeUpdate(subscribe_update), "Invalid object range"); EXPECT_EQ(buffer.size(), 0); } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/moqt/moqt_framer.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/moqt/moqt_framer_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
30e35d91-5cf7-4732-a738-7228eeaa41a6
cpp
google/quiche
moqt_subscribe_windows
quiche/quic/moqt/moqt_subscribe_windows.cc
quiche/quic/moqt/moqt_subscribe_windows_test.cc
#include "quiche/quic/moqt/moqt_subscribe_windows.h" #include <optional> #include <vector> #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/web_transport/web_transport.h" namespace moqt { bool SubscribeWindow::InWindow(const FullSequence& seq) const { if (seq < start_) { return false; } return (!end_.has_value() || seq <= *end_); } std::optional<webtransport::StreamId> SendStreamMap::GetStreamForSequence( FullSequence sequence) const { ReducedSequenceIndex index(sequence, forwarding_preference_); auto stream_it = send_streams_.find(index); if (stream_it == send_streams_.end()) { return std::nullopt; } return stream_it->second; } void SendStreamMap::AddStream(FullSequence sequence, webtransport::StreamId stream_id) { ReducedSequenceIndex index(sequence, forwarding_preference_); if (forwarding_preference_ == MoqtForwardingPreference::kDatagram) { QUIC_BUG(quic_bug_moqt_draft_03_01) << "Adding a stream for datagram"; return; } auto [stream_it, success] = send_streams_.emplace(index, stream_id); QUIC_BUG_IF(quic_bug_moqt_draft_03_02, !success) << "Stream already added"; } void SendStreamMap::RemoveStream(FullSequence sequence, webtransport::StreamId stream_id) { ReducedSequenceIndex index(sequence, forwarding_preference_); QUICHE_DCHECK(send_streams_.contains(index) && send_streams_.find(index)->second == stream_id) << "Requested to remove a stream ID that does not match the one in the " "map"; send_streams_.erase(index); } bool SubscribeWindow::UpdateStartEnd(FullSequence start, std::optional<FullSequence> end) { if (!InWindow(start)) { return false; } if (end_.has_value() && (!end.has_value() || *end_ < *end)) { return false; } start_ = start; end_ = end; return true; } ReducedSequenceIndex::ReducedSequenceIndex( FullSequence sequence, MoqtForwardingPreference preference) { switch (preference) { case MoqtForwardingPreference::kTrack: sequence_ = FullSequence(0, 0); break; case MoqtForwardingPreference::kSubgroup: sequence_ = FullSequence(sequence.group, 0); break; case MoqtForwardingPreference::kDatagram: sequence_ = sequence; return; } } std::vector<webtransport::StreamId> SendStreamMap::GetAllStreams() const { std::vector<webtransport::StreamId> ids; for (const auto& [index, id] : send_streams_) { ids.push_back(id); } return ids; } }
#include "quiche/quic/moqt/moqt_subscribe_windows.h" #include <cstdint> #include <optional> #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/common/platform/api/quiche_export.h" namespace moqt { namespace test { class QUICHE_EXPORT SubscribeWindowTest : public quic::test::QuicTest { public: SubscribeWindowTest() {} const uint64_t subscribe_id_ = 2; const FullSequence start_{4, 0}; const FullSequence end_{5, 5}; }; TEST_F(SubscribeWindowTest, Queries) { SubscribeWindow window(start_, end_); EXPECT_TRUE(window.InWindow(FullSequence(4, 0))); EXPECT_TRUE(window.InWindow(FullSequence(5, 5))); EXPECT_FALSE(window.InWindow(FullSequence(5, 6))); EXPECT_FALSE(window.InWindow(FullSequence(6, 0))); EXPECT_FALSE(window.InWindow(FullSequence(3, 12))); } TEST_F(SubscribeWindowTest, AddQueryRemoveStreamIdTrack) { SendStreamMap stream_map(MoqtForwardingPreference::kTrack); stream_map.AddStream(FullSequence{4, 0}, 2); EXPECT_QUIC_BUG(stream_map.AddStream(FullSequence{5, 2}, 6), "Stream already added"); EXPECT_EQ(stream_map.GetStreamForSequence(FullSequence(5, 2)), 2); stream_map.RemoveStream(FullSequence{7, 2}, 2); EXPECT_EQ(stream_map.GetStreamForSequence(FullSequence(4, 0)), std::nullopt); } TEST_F(SubscribeWindowTest, AddQueryRemoveStreamIdSubgroup) { SendStreamMap stream_map(MoqtForwardingPreference::kSubgroup); stream_map.AddStream(FullSequence{4, 0}, 2); EXPECT_EQ(stream_map.GetStreamForSequence(FullSequence(5, 0)), std::nullopt); stream_map.AddStream(FullSequence{5, 2}, 6); EXPECT_QUIC_BUG(stream_map.AddStream(FullSequence{5, 3}, 6), "Stream already added"); EXPECT_EQ(stream_map.GetStreamForSequence(FullSequence(4, 1)), 2); EXPECT_EQ(stream_map.GetStreamForSequence(FullSequence(5, 0)), 6); stream_map.RemoveStream(FullSequence{5, 1}, 6); EXPECT_EQ(stream_map.GetStreamForSequence(FullSequence(5, 2)), std::nullopt); } TEST_F(SubscribeWindowTest, AddQueryRemoveStreamIdDatagram) { SendStreamMap stream_map(MoqtForwardingPreference::kDatagram); EXPECT_QUIC_BUG(stream_map.AddStream(FullSequence{4, 0}, 2), "Adding a stream for datagram"); } TEST_F(SubscribeWindowTest, UpdateStartEnd) { SubscribeWindow window(start_, end_); EXPECT_TRUE(window.UpdateStartEnd(start_.next(), FullSequence(end_.group, end_.object - 1))); EXPECT_FALSE(window.InWindow(FullSequence(start_.group, start_.object))); EXPECT_FALSE(window.InWindow(FullSequence(end_.group, end_.object))); EXPECT_FALSE( window.UpdateStartEnd(start_, FullSequence(end_.group, end_.object - 1))); EXPECT_FALSE(window.UpdateStartEnd(start_.next(), end_)); } TEST_F(SubscribeWindowTest, UpdateStartEndOpenEnded) { SubscribeWindow window(start_, std::nullopt); EXPECT_TRUE(window.UpdateStartEnd(start_, end_)); EXPECT_FALSE(window.InWindow(end_.next())); EXPECT_FALSE(window.UpdateStartEnd(start_, std::nullopt)); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/moqt/moqt_subscribe_windows.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/moqt/moqt_subscribe_windows_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
f3700489-9418-431d-a2bb-ea1b501e9fba
cpp
google/quiche
moqt_bitrate_adjuster
quiche/quic/moqt/moqt_bitrate_adjuster.cc
quiche/quic/moqt/moqt_bitrate_adjuster_test.cc
#include "quiche/quic/moqt/moqt_bitrate_adjuster.h" #include <algorithm> #include <cstdint> #include "quiche/quic/core/quic_bandwidth.h" #include "quiche/quic/core/quic_time.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/web_transport/web_transport.h" namespace moqt { namespace { using ::quic::QuicBandwidth; using ::quic::QuicTime; using ::quic::QuicTimeDelta; constexpr float kTargetBitrateMultiplier = 0.9f; constexpr float kMinTimeBetweenAdjustmentsInRtts = 40; constexpr QuicTimeDelta kMaxTimeBetweenAdjustments = QuicTimeDelta::FromSeconds(3); } void MoqtBitrateAdjuster::OnObjectAckReceived( uint64_t , uint64_t , QuicTimeDelta delta_from_deadline) { if (delta_from_deadline < QuicTimeDelta::Zero()) { AttemptAdjustingDown(); } } void MoqtBitrateAdjuster::AttemptAdjustingDown() { webtransport::SessionStats stats = session_->GetSessionStats(); QuicTimeDelta adjustment_delay = QuicTimeDelta(stats.smoothed_rtt * kMinTimeBetweenAdjustmentsInRtts); adjustment_delay = std::min(adjustment_delay, kMaxTimeBetweenAdjustments); QuicTime now = clock_->ApproximateNow(); if (now - last_adjustment_time_ < adjustment_delay) { return; } QuicBandwidth target_bandwidth = kTargetBitrateMultiplier * QuicBandwidth::FromBitsPerSecond(stats.estimated_send_rate_bps); QuicBandwidth current_bandwidth = adjustable_->GetCurrentBitrate(); if (current_bandwidth <= target_bandwidth) { return; } QUICHE_DLOG(INFO) << "Adjusting the bitrate from " << current_bandwidth << " to " << target_bandwidth; bool success = adjustable_->AdjustBitrate(target_bandwidth); if (success) { last_adjustment_time_ = now; } } void MoqtBitrateAdjuster::OnObjectAckSupportKnown(bool supported) { QUICHE_DLOG_IF(WARNING, !supported) << "OBJECT_ACK not supported; bitrate adjustments will not work."; } }
#include "quiche/quic/moqt/moqt_bitrate_adjuster.h" #include "quiche/quic/core/quic_bandwidth.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/test_tools/mock_clock.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/web_transport/test_tools/mock_web_transport.h" #include "quiche/web_transport/web_transport.h" namespace moqt::test { namespace { using ::quic::QuicBandwidth; using ::quic::QuicTimeDelta; using ::testing::_; class MockBitrateAdjustable : public BitrateAdjustable { public: explicit MockBitrateAdjustable(QuicBandwidth initial_bitrate) : bitrate_(initial_bitrate) {} QuicBandwidth GetCurrentBitrate() const override { return bitrate_; } bool AdjustBitrate(QuicBandwidth bandwidth) override { bitrate_ = bandwidth; OnBitrateAdjusted(bandwidth); return true; } MOCK_METHOD(void, OnBitrateAdjusted, (QuicBandwidth new_bitrate), ()); private: QuicBandwidth bitrate_; }; constexpr QuicBandwidth kDefaultBitrate = QuicBandwidth::FromBitsPerSecond(2000); constexpr QuicTimeDelta kDefaultRtt = QuicTimeDelta::FromMilliseconds(20); class MoqtBitrateAdjusterTest : public quiche::test::QuicheTest { protected: MoqtBitrateAdjusterTest() : adjustable_(kDefaultBitrate), adjuster_(&clock_, &session_, &adjustable_) { stats_.min_rtt = stats_.smoothed_rtt = kDefaultRtt.ToAbsl(); stats_.estimated_send_rate_bps = (1.2 * kDefaultBitrate).ToBitsPerSecond(); ON_CALL(session_, GetSessionStats()).WillByDefault([this] { return stats_; }); } MockBitrateAdjustable adjustable_; webtransport::SessionStats stats_; quic::MockClock clock_; webtransport::test::MockSession session_; MoqtBitrateAdjuster adjuster_; }; TEST_F(MoqtBitrateAdjusterTest, SteadyState) { stats_.estimated_send_rate_bps = 1; EXPECT_CALL(adjustable_, OnBitrateAdjusted(_)).Times(0); for (int i = 0; i < 250; ++i) { clock_.AdvanceTime(kDefaultRtt); for (int j = 0; j < 10; ++j) { adjuster_.OnObjectAckReceived(i, j, kDefaultRtt * 2); } } } TEST_F(MoqtBitrateAdjusterTest, AdjustDownOnce) { stats_.estimated_send_rate_bps = (0.5 * kDefaultBitrate).ToBitsPerSecond(); EXPECT_CALL(adjustable_, OnBitrateAdjusted(_)).Times(0); adjuster_.OnObjectAckReceived(0, 0, QuicTimeDelta::FromMilliseconds(-1)); clock_.AdvanceTime(100 * kDefaultRtt); EXPECT_CALL(adjustable_, OnBitrateAdjusted(_)) .WillOnce([](QuicBandwidth new_bitrate) { EXPECT_LT(new_bitrate, kDefaultBitrate); }); adjuster_.OnObjectAckReceived(0, 1, QuicTimeDelta::FromMilliseconds(-1)); } TEST_F(MoqtBitrateAdjusterTest, AdjustDownTwice) { int adjusted_times = 0; EXPECT_CALL(adjustable_, OnBitrateAdjusted(_)).WillRepeatedly([&] { ++adjusted_times; }); clock_.AdvanceTime(100 * kDefaultRtt); stats_.estimated_send_rate_bps = (0.5 * kDefaultBitrate).ToBitsPerSecond(); adjuster_.OnObjectAckReceived(0, 0, QuicTimeDelta::FromMilliseconds(-1)); EXPECT_EQ(adjusted_times, 1); clock_.AdvanceTime(100 * kDefaultRtt); stats_.estimated_send_rate_bps = (0.25 * kDefaultBitrate).ToBitsPerSecond(); adjuster_.OnObjectAckReceived(0, 1, QuicTimeDelta::FromMilliseconds(-1)); EXPECT_EQ(adjusted_times, 2); } TEST_F(MoqtBitrateAdjusterTest, AdjustDownSecondTimeIgnoredDueToTimeLimit) { int adjusted_times = 0; EXPECT_CALL(adjustable_, OnBitrateAdjusted(_)).WillRepeatedly([&] { ++adjusted_times; }); clock_.AdvanceTime(100 * kDefaultRtt); stats_.estimated_send_rate_bps = (0.5 * kDefaultBitrate).ToBitsPerSecond(); adjuster_.OnObjectAckReceived(0, 0, QuicTimeDelta::FromMilliseconds(-1)); EXPECT_EQ(adjusted_times, 1); clock_.AdvanceTime(2 * kDefaultRtt); stats_.estimated_send_rate_bps = (0.25 * kDefaultBitrate).ToBitsPerSecond(); adjuster_.OnObjectAckReceived(0, 1, QuicTimeDelta::FromMilliseconds(-1)); EXPECT_EQ(adjusted_times, 1); } TEST_F(MoqtBitrateAdjusterTest, AdjustDownIgnoredDueToHighBandwidthMeasured) { EXPECT_CALL(adjustable_, OnBitrateAdjusted(_)).Times(0); clock_.AdvanceTime(100 * kDefaultRtt); stats_.estimated_send_rate_bps = (2.0 * kDefaultBitrate).ToBitsPerSecond(); adjuster_.OnObjectAckReceived(0, 0, QuicTimeDelta::FromMilliseconds(-1)); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/moqt/moqt_bitrate_adjuster.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/moqt/moqt_bitrate_adjuster_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
5fda23d4-48b0-4d51-81c8-7f86a164d7f4
cpp
google/quiche
moqt_priority
quiche/quic/moqt/moqt_priority.cc
quiche/quic/moqt/moqt_priority_test.cc
#include "quiche/quic/moqt/moqt_priority.h" #include <cstdint> #include <limits> #include "quiche/web_transport/web_transport.h" namespace moqt { namespace { template <uint64_t NumBits> constexpr uint64_t Flip(uint64_t number) { static_assert(NumBits <= 63); return (1ull << NumBits) - 1 - number; } template <uint64_t N> constexpr uint64_t OnlyLowestNBits(uint64_t value) { static_assert(N <= 62); return value & ((1ull << (N + 1)) - 1); } } webtransport::SendOrder SendOrderForStream(MoqtPriority subscriber_priority, MoqtPriority publisher_priority, uint64_t group_id, MoqtDeliveryOrder delivery_order) { const int64_t track_bits = (Flip<8>(subscriber_priority) << 54) | (Flip<8>(publisher_priority) << 46); group_id = OnlyLowestNBits<46>(group_id); if (delivery_order == MoqtDeliveryOrder::kAscending) { group_id = Flip<46>(group_id); } return track_bits | group_id; } webtransport::SendOrder SendOrderForStream(MoqtPriority subscriber_priority, MoqtPriority publisher_priority, uint64_t group_id, uint64_t subgroup_id, MoqtDeliveryOrder delivery_order) { const int64_t track_bits = (Flip<8>(subscriber_priority) << 54) | (Flip<8>(publisher_priority) << 46); group_id = OnlyLowestNBits<26>(group_id); subgroup_id = OnlyLowestNBits<20>(subgroup_id); if (delivery_order == MoqtDeliveryOrder::kAscending) { group_id = Flip<26>(group_id); } subgroup_id = Flip<20>(subgroup_id); return track_bits | (group_id << 20) | subgroup_id; } webtransport::SendOrder UpdateSendOrderForSubscriberPriority( const webtransport::SendOrder send_order, MoqtPriority subscriber_priority) { webtransport::SendOrder new_send_order = OnlyLowestNBits<54>(send_order); const int64_t sub_bits = Flip<8>(subscriber_priority) << 54; new_send_order |= sub_bits; return new_send_order; } const webtransport::SendOrder kMoqtControlStreamSendOrder = std::numeric_limits<webtransport::SendOrder>::max(); }
#include "quiche/quic/moqt/moqt_priority.h" #include "quiche/common/platform/api/quiche_test.h" namespace moqt { namespace { TEST(MoqtPrioirtyTest, TrackPriorities) { EXPECT_GT(SendOrderForStream(0x10, 0x80, 0, MoqtDeliveryOrder::kAscending), SendOrderForStream(0x80, 0x80, 0, MoqtDeliveryOrder::kAscending)); EXPECT_GT(SendOrderForStream(0x80, 0x10, 0, MoqtDeliveryOrder::kAscending), SendOrderForStream(0x80, 0x80, 0, MoqtDeliveryOrder::kAscending)); EXPECT_GT(SendOrderForStream(0x10, 0x80, 0, MoqtDeliveryOrder::kAscending), SendOrderForStream(0x80, 0x10, 0, MoqtDeliveryOrder::kAscending)); EXPECT_GT(SendOrderForStream(0x00, 0x80, 0, MoqtDeliveryOrder::kAscending), SendOrderForStream(0xff, 0x80, 0, MoqtDeliveryOrder::kAscending)); EXPECT_GT(SendOrderForStream(0x80, 0x00, 0, MoqtDeliveryOrder::kAscending), SendOrderForStream(0x80, 0xff, 0, MoqtDeliveryOrder::kAscending)); } TEST(MoqtPrioirtyTest, ControlStream) { EXPECT_GT(kMoqtControlStreamSendOrder, SendOrderForStream(0x00, 0x00, 0, MoqtDeliveryOrder::kAscending)); } TEST(MoqtPriorityTest, StreamPerGroup) { EXPECT_GT(SendOrderForStream(0x80, 0x80, 0, MoqtDeliveryOrder::kAscending), SendOrderForStream(0x80, 0x80, 1, MoqtDeliveryOrder::kAscending)); EXPECT_GT(SendOrderForStream(0x80, 0x80, 1, MoqtDeliveryOrder::kDescending), SendOrderForStream(0x80, 0x80, 0, MoqtDeliveryOrder::kDescending)); } TEST(MoqtPriorityTest, StreamPerObject) { EXPECT_GT( SendOrderForStream(0x80, 0x80, 0, 0, MoqtDeliveryOrder::kAscending), SendOrderForStream(0x80, 0x80, 0, 1, MoqtDeliveryOrder::kAscending)); EXPECT_GT( SendOrderForStream(0x80, 0x80, 0, 0, MoqtDeliveryOrder::kDescending), SendOrderForStream(0x80, 0x80, 0, 1, MoqtDeliveryOrder::kDescending)); EXPECT_GT( SendOrderForStream(0x80, 0x80, 0, 1, MoqtDeliveryOrder::kAscending), SendOrderForStream(0x80, 0x80, 1, 0, MoqtDeliveryOrder::kAscending)); EXPECT_GT( SendOrderForStream(0x80, 0x80, 1, 1, MoqtDeliveryOrder::kDescending), SendOrderForStream(0x80, 0x80, 0, 0, MoqtDeliveryOrder::kDescending)); } TEST(MoqtPriorityTest, UpdateSendOrderForSubscriberPriority) { EXPECT_EQ( UpdateSendOrderForSubscriberPriority( SendOrderForStream(0x80, 0x80, 0, MoqtDeliveryOrder::kAscending), 0x10), SendOrderForStream(0x10, 0x80, 0, MoqtDeliveryOrder::kAscending)); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/moqt/moqt_priority.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/moqt/moqt_priority_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
d8c6f192-fbf5-4544-be2d-8bd71d36f15e
cpp
google/quiche
qbone_packet_processor
quiche/quic/qbone/qbone_packet_processor.cc
quiche/quic/qbone/qbone_packet_processor_test.cc
#include "quiche/quic/qbone/qbone_packet_processor.h" #include <netinet/icmp6.h> #include <netinet/in.h> #include <netinet/ip6.h> #include <cstdint> #include <cstring> #include <string> #include "absl/base/optimization.h" #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_ip_address_family.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/qbone/platform/icmp_packet.h" #include "quiche/quic/qbone/platform/tcp_packet.h" #include "quiche/common/quiche_endian.h" namespace { constexpr size_t kIPv6AddressSize = 16; constexpr size_t kIPv6MinPacketSize = 1280; constexpr size_t kIcmpTtl = 64; constexpr size_t kICMPv6DestinationUnreachableDueToSourcePolicy = 5; constexpr size_t kIPv6DestinationOffset = 8; } namespace quic { const QuicIpAddress QbonePacketProcessor::kInvalidIpAddress = QuicIpAddress::Any6(); QbonePacketProcessor::QbonePacketProcessor(QuicIpAddress self_ip, QuicIpAddress client_ip, size_t client_ip_subnet_length, OutputInterface* output, StatsInterface* stats) : client_ip_(client_ip), output_(output), stats_(stats), filter_(new Filter) { memcpy(self_ip_.s6_addr, self_ip.ToPackedString().data(), kIPv6AddressSize); QUICHE_DCHECK_LE(client_ip_subnet_length, kIPv6AddressSize * 8); client_ip_subnet_length_ = client_ip_subnet_length; QUICHE_DCHECK(IpAddressFamily::IP_V6 == self_ip.address_family()); QUICHE_DCHECK(IpAddressFamily::IP_V6 == client_ip.address_family()); QUICHE_DCHECK(self_ip != kInvalidIpAddress); } QbonePacketProcessor::OutputInterface::~OutputInterface() {} QbonePacketProcessor::StatsInterface::~StatsInterface() {} QbonePacketProcessor::Filter::~Filter() {} QbonePacketProcessor::ProcessingResult QbonePacketProcessor::Filter::FilterPacket(Direction direction, absl::string_view full_packet, absl::string_view payload, icmp6_hdr* icmp_header) { return ProcessingResult::OK; } void QbonePacketProcessor::ProcessPacket(std::string* packet, Direction direction) { uint8_t traffic_class = TrafficClassFromHeader(*packet); if (ABSL_PREDICT_FALSE(!IsValid())) { QUIC_BUG(quic_bug_11024_1) << "QuicPacketProcessor is invoked in an invalid state."; stats_->OnPacketDroppedSilently(direction, traffic_class); return; } stats_->RecordThroughput(packet->size(), direction, traffic_class); uint8_t transport_protocol; char* transport_data; icmp6_hdr icmp_header; memset(&icmp_header, 0, sizeof(icmp_header)); ProcessingResult result = ProcessIPv6HeaderAndFilter( packet, direction, &transport_protocol, &transport_data, &icmp_header); in6_addr dst; memcpy(&dst, &packet->data()[kIPv6DestinationOffset], kIPv6AddressSize); switch (result) { case ProcessingResult::OK: switch (direction) { case Direction::FROM_OFF_NETWORK: output_->SendPacketToNetwork(*packet); break; case Direction::FROM_NETWORK: output_->SendPacketToClient(*packet); break; } stats_->OnPacketForwarded(direction, traffic_class); break; case ProcessingResult::SILENT_DROP: stats_->OnPacketDroppedSilently(direction, traffic_class); break; case ProcessingResult::ICMP: if (icmp_header.icmp6_type == ICMP6_ECHO_REPLY) { auto icmp_body = absl::string_view(*packet).substr(sizeof(ip6_hdr) + sizeof(icmp6_hdr)); SendIcmpResponse(dst, &icmp_header, icmp_body, direction); } else { SendIcmpResponse(dst, &icmp_header, *packet, direction); } stats_->OnPacketDroppedWithIcmp(direction, traffic_class); break; case ProcessingResult::ICMP_AND_TCP_RESET: SendIcmpResponse(dst, &icmp_header, *packet, direction); stats_->OnPacketDroppedWithIcmp(direction, traffic_class); SendTcpReset(*packet, direction); stats_->OnPacketDroppedWithTcpReset(direction, traffic_class); break; case ProcessingResult::TCP_RESET: SendTcpReset(*packet, direction); stats_->OnPacketDroppedWithTcpReset(direction, traffic_class); break; } } QbonePacketProcessor::ProcessingResult QbonePacketProcessor::ProcessIPv6HeaderAndFilter(std::string* packet, Direction direction, uint8_t* transport_protocol, char** transport_data, icmp6_hdr* icmp_header) { ProcessingResult result = ProcessIPv6Header( packet, direction, transport_protocol, transport_data, icmp_header); if (result == ProcessingResult::OK) { char* packet_data = &*packet->begin(); size_t header_size = *transport_data - packet_data; if (packet_data >= *transport_data || header_size > packet->size() || header_size < kIPv6HeaderSize) { QUIC_BUG(quic_bug_11024_2) << "Invalid pointers encountered in " "QbonePacketProcessor::ProcessPacket. Dropping the packet"; return ProcessingResult::SILENT_DROP; } result = filter_->FilterPacket( direction, *packet, absl::string_view(*transport_data, packet->size() - header_size), icmp_header); } if (result == ProcessingResult::ICMP) { const uint8_t* header = reinterpret_cast<const uint8_t*>(packet->data()); constexpr size_t kIPv6NextHeaderOffset = 6; constexpr size_t kIcmpMessageTypeOffset = kIPv6HeaderSize + 0; constexpr size_t kIcmpMessageTypeMaxError = 127; if ( packet->size() >= (kIPv6HeaderSize + kICMPv6HeaderSize) && header[kIPv6NextHeaderOffset] == IPPROTO_ICMPV6 && header[kIcmpMessageTypeOffset] < kIcmpMessageTypeMaxError) { result = ProcessingResult::SILENT_DROP; } } return result; } QbonePacketProcessor::ProcessingResult QbonePacketProcessor::ProcessIPv6Header( std::string* packet, Direction direction, uint8_t* transport_protocol, char** transport_data, icmp6_hdr* icmp_header) { if (packet->size() < kIPv6HeaderSize) { QUIC_DVLOG(1) << "Dropped malformed packet: IPv6 header too short"; return ProcessingResult::SILENT_DROP; } ip6_hdr* header = reinterpret_cast<ip6_hdr*>(&*packet->begin()); if (header->ip6_vfc >> 4 != 6) { QUIC_DVLOG(1) << "Dropped malformed packet: IP version is not IPv6"; return ProcessingResult::SILENT_DROP; } const size_t declared_payload_size = quiche::QuicheEndian::NetToHost16(header->ip6_plen); const size_t actual_payload_size = packet->size() - kIPv6HeaderSize; if (declared_payload_size != actual_payload_size) { QUIC_DVLOG(1) << "Dropped malformed packet: incorrect packet length specified"; return ProcessingResult::SILENT_DROP; } QuicIpAddress address_to_check; uint8_t address_reject_code; bool ip_parse_result; switch (direction) { case Direction::FROM_OFF_NETWORK: ip_parse_result = address_to_check.FromPackedString( reinterpret_cast<const char*>(&header->ip6_src), sizeof(header->ip6_src)); address_reject_code = kICMPv6DestinationUnreachableDueToSourcePolicy; break; case Direction::FROM_NETWORK: ip_parse_result = address_to_check.FromPackedString( reinterpret_cast<const char*>(&header->ip6_dst), sizeof(header->ip6_src)); address_reject_code = ICMP6_DST_UNREACH_NOROUTE; break; } QUICHE_DCHECK(ip_parse_result); if (!client_ip_.InSameSubnet(address_to_check, client_ip_subnet_length_)) { QUIC_DVLOG(1) << "Dropped packet: source/destination address is not client's"; icmp_header->icmp6_type = ICMP6_DST_UNREACH; icmp_header->icmp6_code = address_reject_code; return ProcessingResult::ICMP; } if (header->ip6_hops <= 1) { icmp_header->icmp6_type = ICMP6_TIME_EXCEEDED; icmp_header->icmp6_code = ICMP6_TIME_EXCEED_TRANSIT; return ProcessingResult::ICMP; } header->ip6_hops--; switch (header->ip6_nxt) { case IPPROTO_TCP: case IPPROTO_UDP: case IPPROTO_ICMPV6: *transport_protocol = header->ip6_nxt; *transport_data = (&*packet->begin()) + kIPv6HeaderSize; break; default: icmp_header->icmp6_type = ICMP6_PARAM_PROB; icmp_header->icmp6_code = ICMP6_PARAMPROB_NEXTHEADER; return ProcessingResult::ICMP; } return ProcessingResult::OK; } void QbonePacketProcessor::SendIcmpResponse(in6_addr dst, icmp6_hdr* icmp_header, absl::string_view payload, Direction original_direction) { CreateIcmpPacket(self_ip_, dst, *icmp_header, payload, [this, original_direction](absl::string_view packet) { SendResponse(original_direction, packet); }); } void QbonePacketProcessor::SendTcpReset(absl::string_view original_packet, Direction original_direction) { CreateTcpResetPacket(original_packet, [this, original_direction](absl::string_view packet) { SendResponse(original_direction, packet); }); } void QbonePacketProcessor::SendResponse(Direction original_direction, absl::string_view packet) { switch (original_direction) { case Direction::FROM_OFF_NETWORK: output_->SendPacketToClient(packet); break; case Direction::FROM_NETWORK: output_->SendPacketToNetwork(packet); break; } } uint8_t QbonePacketProcessor::TrafficClassFromHeader( absl::string_view ipv6_header) { if (ipv6_header.length() < 2) { return 0; } return ipv6_header[0] << 4 | ipv6_header[1] >> 4; } }
#include "quiche/quic/qbone/qbone_packet_processor.h" #include <memory> #include <string> #include <utility> #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/qbone/qbone_packet_processor_test_tools.h" #include "quiche/common/quiche_text_utils.h" namespace quic::test { namespace { using Direction = QbonePacketProcessor::Direction; using ProcessingResult = QbonePacketProcessor::ProcessingResult; using OutputInterface = QbonePacketProcessor::OutputInterface; using ::testing::_; using ::testing::Eq; using ::testing::Invoke; using ::testing::Return; using ::testing::WithArgs; static const char kReferenceClientPacketData[] = { 0x60, 0x00, 0x00, 0x00, 0x00, 0x08, 17, 50, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x30, 0x39, 0x01, 0xbb, 0x00, 0x00, 0x00, 0x00, }; static const char kReferenceClientPacketDataAF4[] = { 0x68, 0x00, 0x00, 0x00, 0x00, 0x08, 17, 50, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x30, 0x39, 0x01, 0xbb, 0x00, 0x00, 0x00, 0x00, }; static const char kReferenceClientPacketDataAF3[] = { 0x66, 0x00, 0x00, 0x00, 0x00, 0x08, 17, 50, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x30, 0x39, 0x01, 0xbb, 0x00, 0x00, 0x00, 0x00, }; static const char kReferenceClientPacketDataAF2[] = { 0x64, 0x00, 0x00, 0x00, 0x00, 0x08, 17, 50, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x30, 0x39, 0x01, 0xbb, 0x00, 0x00, 0x00, 0x00, }; static const char kReferenceClientPacketDataAF1[] = { 0x62, 0x00, 0x00, 0x00, 0x00, 0x08, 17, 50, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x30, 0x39, 0x01, 0xbb, 0x00, 0x00, 0x00, 0x00, }; static const char kReferenceNetworkPacketData[] = { 0x60, 0x00, 0x00, 0x00, 0x00, 0x08, 17, 50, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0xbb, 0x30, 0x39, 0x00, 0x00, 0x00, 0x00, }; static const char kReferenceClientSubnetPacketData[] = { 0x60, 0x00, 0x00, 0x00, 0x00, 0x08, 17, 50, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x30, 0x39, 0x01, 0xbb, 0x00, 0x00, 0x00, 0x00, }; static const char kReferenceEchoRequestData[] = { 0x60, 0x00, 0x00, 0x00, 0x00, 64, 58, 127, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x71, 0x62, 0x6f, 0x6e, 0x6f, 128, 0, 0x00, 0x00, 0xca, 0xfe, 0x00, 0x01, 0x67, 0x37, 0x8a, 0x63, 0x00, 0x00, 0x00, 0x00, 0x96, 0x58, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, }; static const char kReferenceEchoReplyData[] = { 0x60, 0x00, 0x00, 0x00, 0x00, 64, 58, 255, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 129, 0, 0x66, 0xb6, 0xca, 0xfe, 0x00, 0x01, 0x67, 0x37, 0x8a, 0x63, 0x00, 0x00, 0x00, 0x00, 0x96, 0x58, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, }; static const absl::string_view kReferenceClientPacket( kReferenceClientPacketData, ABSL_ARRAYSIZE(kReferenceClientPacketData)); static const absl::string_view kReferenceClientPacketAF4( kReferenceClientPacketDataAF4, ABSL_ARRAYSIZE(kReferenceClientPacketDataAF4)); static const absl::string_view kReferenceClientPacketAF3( kReferenceClientPacketDataAF3, ABSL_ARRAYSIZE(kReferenceClientPacketDataAF3)); static const absl::string_view kReferenceClientPacketAF2( kReferenceClientPacketDataAF2, ABSL_ARRAYSIZE(kReferenceClientPacketDataAF2)); static const absl::string_view kReferenceClientPacketAF1( kReferenceClientPacketDataAF1, ABSL_ARRAYSIZE(kReferenceClientPacketDataAF1)); static const absl::string_view kReferenceNetworkPacket( kReferenceNetworkPacketData, ABSL_ARRAYSIZE(kReferenceNetworkPacketData)); static const absl::string_view kReferenceClientSubnetPacket( kReferenceClientSubnetPacketData, ABSL_ARRAYSIZE(kReferenceClientSubnetPacketData)); static const absl::string_view kReferenceEchoRequest( kReferenceEchoRequestData, ABSL_ARRAYSIZE(kReferenceEchoRequestData)); MATCHER_P(IsIcmpMessage, icmp_type, "Checks whether the argument is an ICMP message of supplied type") { if (arg.size() < kTotalICMPv6HeaderSize) { return false; } return arg[40] == icmp_type; } class MockPacketFilter : public QbonePacketProcessor::Filter { public: MOCK_METHOD(ProcessingResult, FilterPacket, (Direction, absl::string_view, absl::string_view, icmp6_hdr*), (override)); }; class QbonePacketProcessorTest : public QuicTest { protected: QbonePacketProcessorTest() { QUICHE_CHECK(client_ip_.FromString("fd00:0:0:1::1")); QUICHE_CHECK(self_ip_.FromString("fd00:0:0:4::1")); QUICHE_CHECK(network_ip_.FromString("fd00:0:0:5::1")); processor_ = std::make_unique<QbonePacketProcessor>( self_ip_, client_ip_, 62, &output_, &stats_); EXPECT_CALL(stats_, RecordThroughput(_, _, _)).WillRepeatedly(Return()); } void SendPacketFromClient(absl::string_view packet) { std::string packet_buffer(packet.data(), packet.size()); processor_->ProcessPacket(&packet_buffer, Direction::FROM_OFF_NETWORK); } void SendPacketFromNetwork(absl::string_view packet) { std::string packet_buffer(packet.data(), packet.size()); processor_->ProcessPacket(&packet_buffer, Direction::FROM_NETWORK); } QuicIpAddress client_ip_; QuicIpAddress self_ip_; QuicIpAddress network_ip_; std::unique_ptr<QbonePacketProcessor> processor_; testing::StrictMock<MockPacketProcessorOutput> output_; testing::StrictMock<MockPacketProcessorStats> stats_; }; TEST_F(QbonePacketProcessorTest, EmptyPacket) { EXPECT_CALL(stats_, OnPacketDroppedSilently(Direction::FROM_OFF_NETWORK, _)); EXPECT_CALL(stats_, RecordThroughput(0, Direction::FROM_OFF_NETWORK, _)); SendPacketFromClient(""); EXPECT_CALL(stats_, OnPacketDroppedSilently(Direction::FROM_NETWORK, _)); EXPECT_CALL(stats_, RecordThroughput(0, Direction::FROM_NETWORK, _)); SendPacketFromNetwork(""); } TEST_F(QbonePacketProcessorTest, RandomGarbage) { EXPECT_CALL(stats_, OnPacketDroppedSilently(Direction::FROM_OFF_NETWORK, _)); SendPacketFromClient(std::string(1280, 'a')); EXPECT_CALL(stats_, OnPacketDroppedSilently(Direction::FROM_NETWORK, _)); SendPacketFromNetwork(std::string(1280, 'a')); } TEST_F(QbonePacketProcessorTest, RandomGarbageWithCorrectLengthFields) { std::string packet(40, 'a'); packet[4] = 0; packet[5] = 0; EXPECT_CALL(stats_, OnPacketDroppedWithIcmp(Direction::FROM_OFF_NETWORK, _)); EXPECT_CALL(output_, SendPacketToClient(IsIcmpMessage(ICMP6_DST_UNREACH))); SendPacketFromClient(packet); } TEST_F(QbonePacketProcessorTest, GoodPacketFromClient) { EXPECT_CALL(stats_, OnPacketForwarded(Direction::FROM_OFF_NETWORK, _)); EXPECT_CALL(output_, SendPacketToNetwork(_)); SendPacketFromClient(kReferenceClientPacket); } TEST_F(QbonePacketProcessorTest, GoodPacketFromClientSubnet) { EXPECT_CALL(stats_, OnPacketForwarded(Direction::FROM_OFF_NETWORK, _)); EXPECT_CALL(output_, SendPacketToNetwork(_)); SendPacketFromClient(kReferenceClientSubnetPacket); } TEST_F(QbonePacketProcessorTest, GoodPacketFromNetwork) { EXPECT_CALL(stats_, OnPacketForwarded(Direction::FROM_NETWORK, _)); EXPECT_CALL(output_, SendPacketToClient(_)); SendPacketFromNetwork(kReferenceNetworkPacket); } TEST_F(QbonePacketProcessorTest, GoodPacketFromNetworkWrongDirection) { EXPECT_CALL(stats_, OnPacketDroppedWithIcmp(Direction::FROM_OFF_NETWORK, _)); EXPECT_CALL(output_, SendPacketToClient(IsIcmpMessage(ICMP6_DST_UNREACH))); SendPacketFromClient(kReferenceNetworkPacket); } TEST_F(QbonePacketProcessorTest, TtlExpired) { std::string packet(kReferenceNetworkPacket); packet[7] = 1; EXPECT_CALL(stats_, OnPacketDroppedWithIcmp(Direction::FROM_NETWORK, _)); EXPECT_CALL(output_, SendPacketToNetwork(IsIcmpMessage(ICMP6_TIME_EXCEEDED))); SendPacketFromNetwork(packet); } TEST_F(QbonePacketProcessorTest, UnknownProtocol) { std::string packet(kReferenceNetworkPacket); packet[6] = IPPROTO_SCTP; EXPECT_CALL(stats_, OnPacketDroppedWithIcmp(Direction::FROM_NETWORK, _)); EXPECT_CALL(output_, SendPacketToNetwork(IsIcmpMessage(ICMP6_PARAM_PROB))); SendPacketFromNetwork(packet); } TEST_F(QbonePacketProcessorTest, FilterFromClient) { auto filter = std::make_unique<MockPacketFilter>(); EXPECT_CALL(*filter, FilterPacket(_, _, _, _)) .WillRepeatedly(Return(ProcessingResult::SILENT_DROP)); processor_->set_filter(std::move(filter)); EXPECT_CALL(stats_, OnPacketDroppedSilently(Direction::FROM_OFF_NETWORK, _)); SendPacketFromClient(kReferenceClientPacket); } class TestFilter : public QbonePacketProcessor::Filter { public: TestFilter(QuicIpAddress client_ip, QuicIpAddress network_ip) : client_ip_(client_ip), network_ip_(network_ip) {} ProcessingResult FilterPacket(Direction direction, absl::string_view full_packet, absl::string_view payload, icmp6_hdr* icmp_header) override { EXPECT_EQ(kIPv6HeaderSize, full_packet.size() - payload.size()); EXPECT_EQ(IPPROTO_UDP, TransportProtocolFromHeader(full_packet)); EXPECT_EQ(client_ip_, SourceIpFromHeader(full_packet)); EXPECT_EQ(network_ip_, DestinationIpFromHeader(full_packet)); last_tos_ = QbonePacketProcessor::TrafficClassFromHeader(full_packet); called_++; return ProcessingResult::SILENT_DROP; } int called() const { return called_; } uint8_t last_tos() const { return last_tos_; } private: int called_ = 0; uint8_t last_tos_ = 0; QuicIpAddress client_ip_; QuicIpAddress network_ip_; }; TEST_F(QbonePacketProcessorTest, FilterHelperFunctions) { auto filter_owned = std::make_unique<TestFilter>(client_ip_, network_ip_); TestFilter* filter = filter_owned.get(); processor_->set_filter(std::move(filter_owned)); EXPECT_CALL(stats_, OnPacketDroppedSilently(Direction::FROM_OFF_NETWORK, _)); SendPacketFromClient(kReferenceClientPacket); ASSERT_EQ(1, filter->called()); } TEST_F(QbonePacketProcessorTest, FilterHelperFunctionsTOS) { auto filter_owned = std::make_unique<TestFilter>(client_ip_, network_ip_); processor_->set_filter(std::move(filter_owned)); EXPECT_CALL(stats_, OnPacketDroppedSilently(Direction::FROM_OFF_NETWORK, _)) .Times(testing::AnyNumber()); EXPECT_CALL(stats_, RecordThroughput(kReferenceClientPacket.size(), Direction::FROM_OFF_NETWORK, 0)); SendPacketFromClient(kReferenceClientPacket); EXPECT_CALL(stats_, RecordThroughput(kReferenceClientPacketAF4.size(), Direction::FROM_OFF_NETWORK, 0x80)); SendPacketFromClient(kReferenceClientPacketAF4); EXPECT_CALL(stats_, RecordThroughput(kReferenceClientPacketAF3.size(), Direction::FROM_OFF_NETWORK, 0x60)); SendPacketFromClient(kReferenceClientPacketAF3); EXPECT_CALL(stats_, RecordThroughput(kReferenceClientPacketAF2.size(), Direction::FROM_OFF_NETWORK, 0x40)); SendPacketFromClient(kReferenceClientPacketAF2); EXPECT_CALL(stats_, RecordThroughput(kReferenceClientPacketAF1.size(), Direction::FROM_OFF_NETWORK, 0x20)); SendPacketFromClient(kReferenceClientPacketAF1); } TEST_F(QbonePacketProcessorTest, Icmp6EchoResponseHasRightPayload) { auto filter = std::make_unique<MockPacketFilter>(); EXPECT_CALL(*filter, FilterPacket(_, _, _, _)) .WillOnce(WithArgs<2, 3>( Invoke([](absl::string_view payload, icmp6_hdr* icmp_header) { icmp_header->icmp6_type = ICMP6_ECHO_REPLY; icmp_header->icmp6_code = 0; auto* request_header = reinterpret_cast<const icmp6_hdr*>(payload.data()); icmp_header->icmp6_id = request_header->icmp6_id; icmp_header->icmp6_seq = request_header->icmp6_seq; return ProcessingResult::ICMP; }))); processor_->set_filter(std::move(filter)); EXPECT_CALL(stats_, OnPacketDroppedWithIcmp(Direction::FROM_OFF_NETWORK, _)); EXPECT_CALL(output_, SendPacketToClient(_)) .WillOnce(Invoke([](absl::string_view packet) { absl::string_view expected = absl::string_view( kReferenceEchoReplyData, sizeof(kReferenceEchoReplyData)); EXPECT_THAT(packet, Eq(expected)); QUIC_LOG(INFO) << "ICMP response:\n" << quiche::QuicheTextUtils::HexDump(packet); })); SendPacketFromClient(kReferenceEchoRequest); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/qbone/qbone_packet_processor.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/qbone/qbone_packet_processor_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
1ea8ed3d-c026-443e-b379-84a13dec9008
cpp
google/quiche
qbone_packet_exchanger
quiche/quic/qbone/qbone_packet_exchanger.cc
quiche/quic/qbone/qbone_packet_exchanger_test.cc
#include "quiche/quic/qbone/qbone_packet_exchanger.h" #include <memory> #include <string> #include <utility> #include "absl/status/status.h" #include "absl/strings/string_view.h" namespace quic { bool QbonePacketExchanger::ReadAndDeliverPacket( QboneClientInterface* qbone_client) { bool blocked = false; std::string error; std::unique_ptr<QuicData> packet = ReadPacket(&blocked, &error); if (packet == nullptr) { if (!blocked && visitor_) { visitor_->OnReadError(error); } return false; } qbone_client->ProcessPacketFromNetwork(packet->AsStringPiece()); return true; } void QbonePacketExchanger::WritePacketToNetwork(const char* packet, size_t size) { if (visitor_) { absl::Status status = visitor_->OnWrite(absl::string_view(packet, size)); if (!status.ok()) { QUIC_LOG_EVERY_N_SEC(ERROR, 60) << status; } } bool blocked = false; std::string error; if (packet_queue_.empty() && !write_blocked_) { if (WritePacket(packet, size, &blocked, &error)) { return; } if (blocked) { write_blocked_ = true; } else { QUIC_LOG_EVERY_N_SEC(ERROR, 60) << "Packet write failed: " << error; if (visitor_) { visitor_->OnWriteError(error); } } } if (packet_queue_.size() >= max_pending_packets_) { return; } auto data_copy = new char[size]; memcpy(data_copy, packet, size); packet_queue_.push_back( std::make_unique<QuicData>(data_copy, size, true)); } void QbonePacketExchanger::SetWritable() { write_blocked_ = false; while (!packet_queue_.empty()) { bool blocked = false; std::string error; if (WritePacket(packet_queue_.front()->data(), packet_queue_.front()->length(), &blocked, &error)) { packet_queue_.pop_front(); } else { if (!blocked && visitor_) { visitor_->OnWriteError(error); } write_blocked_ = blocked; return; } } } }
#include "quiche/quic/qbone/qbone_packet_exchanger.h" #include <list> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/qbone/mock_qbone_client.h" namespace quic { namespace { using ::testing::StrEq; using ::testing::StrictMock; const size_t kMaxPendingPackets = 2; class MockVisitor : public QbonePacketExchanger::Visitor { public: MOCK_METHOD(void, OnReadError, (const std::string&), (override)); MOCK_METHOD(void, OnWriteError, (const std::string&), (override)); MOCK_METHOD(absl::Status, OnWrite, (absl::string_view), (override)); }; class FakeQbonePacketExchanger : public QbonePacketExchanger { public: using QbonePacketExchanger::QbonePacketExchanger; void AddPacketToBeRead(std::unique_ptr<QuicData> packet) { packets_to_be_read_.push_back(std::move(packet)); } void SetReadError(const std::string& error) { read_error_ = error; } void ForceWriteFailure(bool blocked, const std::string& error) { write_blocked_ = blocked; write_error_ = error; } const std::vector<std::string>& packets_written() const { return packets_written_; } private: std::unique_ptr<QuicData> ReadPacket(bool* blocked, std::string* error) override { *blocked = false; if (packets_to_be_read_.empty()) { *blocked = read_error_.empty(); *error = read_error_; return nullptr; } std::unique_ptr<QuicData> packet = std::move(packets_to_be_read_.front()); packets_to_be_read_.pop_front(); return packet; } bool WritePacket(const char* packet, size_t size, bool* blocked, std::string* error) override { *blocked = false; if (write_blocked_ || !write_error_.empty()) { *blocked = write_blocked_; *error = write_error_; return false; } packets_written_.push_back(std::string(packet, size)); return true; } std::string read_error_; std::list<std::unique_ptr<QuicData>> packets_to_be_read_; std::string write_error_; bool write_blocked_ = false; std::vector<std::string> packets_written_; }; TEST(QbonePacketExchangerTest, ReadAndDeliverPacketDeliversPacketToQboneClient) { StrictMock<MockVisitor> visitor; FakeQbonePacketExchanger exchanger(&visitor, kMaxPendingPackets); StrictMock<MockQboneClient> client; std::string packet = "data"; exchanger.AddPacketToBeRead( std::make_unique<QuicData>(packet.data(), packet.length())); EXPECT_CALL(client, ProcessPacketFromNetwork(StrEq("data"))); EXPECT_TRUE(exchanger.ReadAndDeliverPacket(&client)); } TEST(QbonePacketExchangerTest, ReadAndDeliverPacketNotifiesVisitorOnReadFailure) { MockVisitor visitor; FakeQbonePacketExchanger exchanger(&visitor, kMaxPendingPackets); MockQboneClient client; std::string io_error = "I/O error"; exchanger.SetReadError(io_error); EXPECT_CALL(visitor, OnReadError(StrEq(io_error))).Times(1); EXPECT_FALSE(exchanger.ReadAndDeliverPacket(&client)); } TEST(QbonePacketExchangerTest, ReadAndDeliverPacketDoesNotNotifyVisitorOnBlockedIO) { MockVisitor visitor; FakeQbonePacketExchanger exchanger(&visitor, kMaxPendingPackets); MockQboneClient client; EXPECT_FALSE(exchanger.ReadAndDeliverPacket(&client)); } TEST(QbonePacketExchangerTest, WritePacketToNetworkWritesDirectlyToNetworkWhenNotBlocked) { MockVisitor visitor; FakeQbonePacketExchanger exchanger(&visitor, kMaxPendingPackets); MockQboneClient client; std::string packet = "data"; exchanger.WritePacketToNetwork(packet.data(), packet.length()); ASSERT_EQ(exchanger.packets_written().size(), 1); EXPECT_THAT(exchanger.packets_written()[0], StrEq(packet)); } TEST(QbonePacketExchangerTest, WritePacketToNetworkQueuesPacketsAndProcessThemLater) { MockVisitor visitor; FakeQbonePacketExchanger exchanger(&visitor, kMaxPendingPackets); MockQboneClient client; exchanger.ForceWriteFailure(true, ""); std::vector<std::string> packets = {"packet0", "packet1"}; for (int i = 0; i < packets.size(); i++) { exchanger.WritePacketToNetwork(packets[i].data(), packets[i].length()); } ASSERT_TRUE(exchanger.packets_written().empty()); exchanger.ForceWriteFailure(false, ""); exchanger.SetWritable(); ASSERT_EQ(exchanger.packets_written().size(), 2); for (int i = 0; i < packets.size(); i++) { EXPECT_THAT(exchanger.packets_written()[i], StrEq(packets[i])); } } TEST(QbonePacketExchangerTest, SetWritableContinuesProcessingPacketIfPreviousCallBlocked) { MockVisitor visitor; FakeQbonePacketExchanger exchanger(&visitor, kMaxPendingPackets); MockQboneClient client; exchanger.ForceWriteFailure(true, ""); std::vector<std::string> packets = {"packet0", "packet1"}; for (int i = 0; i < packets.size(); i++) { exchanger.WritePacketToNetwork(packets[i].data(), packets[i].length()); } ASSERT_TRUE(exchanger.packets_written().empty()); exchanger.SetWritable(); ASSERT_TRUE(exchanger.packets_written().empty()); exchanger.ForceWriteFailure(false, ""); exchanger.SetWritable(); ASSERT_EQ(exchanger.packets_written().size(), 2); for (int i = 0; i < packets.size(); i++) { EXPECT_THAT(exchanger.packets_written()[i], StrEq(packets[i])); } } TEST(QbonePacketExchangerTest, WritePacketToNetworkDropsPacketIfQueueIfFull) { std::vector<std::string> packets = {"packet0", "packet1", "packet2"}; size_t queue_size = packets.size() - 1; MockVisitor visitor; FakeQbonePacketExchanger exchanger(&visitor, queue_size); MockQboneClient client; exchanger.ForceWriteFailure(true, ""); for (int i = 0; i < packets.size(); i++) { exchanger.WritePacketToNetwork(packets[i].data(), packets[i].length()); } ASSERT_TRUE(exchanger.packets_written().empty()); exchanger.ForceWriteFailure(false, ""); exchanger.SetWritable(); ASSERT_EQ(exchanger.packets_written().size(), queue_size); for (int i = 0; i < queue_size; i++) { EXPECT_THAT(exchanger.packets_written()[i], StrEq(packets[i])); } } TEST(QbonePacketExchangerTest, WriteErrorsGetNotified) { MockVisitor visitor; FakeQbonePacketExchanger exchanger(&visitor, kMaxPendingPackets); MockQboneClient client; std::string packet = "data"; std::string io_error = "I/O error"; exchanger.ForceWriteFailure(false, io_error); EXPECT_CALL(visitor, OnWriteError(StrEq(io_error))).Times(1); exchanger.WritePacketToNetwork(packet.data(), packet.length()); ASSERT_TRUE(exchanger.packets_written().empty()); exchanger.ForceWriteFailure(true, ""); exchanger.WritePacketToNetwork(packet.data(), packet.length()); std::string sys_error = "sys error"; exchanger.ForceWriteFailure(false, sys_error); EXPECT_CALL(visitor, OnWriteError(StrEq(sys_error))).Times(1); exchanger.SetWritable(); ASSERT_TRUE(exchanger.packets_written().empty()); } TEST(QbonePacketExchangerTest, NullVisitorDoesntCrash) { FakeQbonePacketExchanger exchanger(nullptr, kMaxPendingPackets); MockQboneClient client; std::string packet = "data"; std::string io_error = "I/O error"; exchanger.SetReadError(io_error); EXPECT_FALSE(exchanger.ReadAndDeliverPacket(&client)); exchanger.ForceWriteFailure(false, io_error); exchanger.WritePacketToNetwork(packet.data(), packet.length()); EXPECT_TRUE(exchanger.packets_written().empty()); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/qbone/qbone_packet_exchanger.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/qbone/qbone_packet_exchanger_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
75fb6a2c-6f24-4264-bf11-5f6743f5b5fa
cpp
google/quiche
qbone_client
quiche/quic/qbone/qbone_client.cc
quiche/quic/qbone/qbone_client_test.cc
#include "quiche/quic/qbone/qbone_client.h" #include <memory> #include <utility> #include "absl/strings/string_view.h" #include "quiche/quic/core/io/quic_event_loop.h" #include "quiche/quic/core/quic_bandwidth.h" #include "quiche/quic/core/quic_default_connection_helper.h" #include "quiche/quic/platform/api/quic_testvalue.h" #include "quiche/quic/tools/quic_client_default_network_helper.h" namespace quic { namespace { std::unique_ptr<QuicClientBase::NetworkHelper> CreateNetworkHelper( QuicEventLoop* event_loop, QboneClient* client) { std::unique_ptr<QuicClientBase::NetworkHelper> helper = std::make_unique<QuicClientDefaultNetworkHelper>(event_loop, client); quic::AdjustTestValue("QboneClient/network_helper", &helper); return helper; } } QboneClient::QboneClient(QuicSocketAddress server_address, const QuicServerId& server_id, const ParsedQuicVersionVector& supported_versions, QuicSession::Visitor* session_owner, const QuicConfig& config, QuicEventLoop* event_loop, std::unique_ptr<ProofVerifier> proof_verifier, QbonePacketWriter* qbone_writer, QboneClientControlStream::Handler* qbone_handler) : QuicClientBase(server_id, supported_versions, config, new QuicDefaultConnectionHelper(), event_loop->CreateAlarmFactory().release(), CreateNetworkHelper(event_loop, this), std::move(proof_verifier), nullptr), qbone_writer_(qbone_writer), qbone_handler_(qbone_handler), session_owner_(session_owner), max_pacing_rate_(QuicBandwidth::Zero()) { set_server_address(server_address); crypto_config()->set_alpn("qbone"); } QboneClient::~QboneClient() { ResetSession(); } QboneClientSession* QboneClient::qbone_session() { return static_cast<QboneClientSession*>(QuicClientBase::session()); } void QboneClient::ProcessPacketFromNetwork(absl::string_view packet) { qbone_session()->ProcessPacketFromNetwork(packet); } bool QboneClient::EarlyDataAccepted() { return qbone_session()->EarlyDataAccepted(); } bool QboneClient::ReceivedInchoateReject() { return qbone_session()->ReceivedInchoateReject(); } int QboneClient::GetNumSentClientHellosFromSession() { return qbone_session()->GetNumSentClientHellos(); } int QboneClient::GetNumReceivedServerConfigUpdatesFromSession() { return qbone_session()->GetNumReceivedServerConfigUpdates(); } void QboneClient::ResendSavedData() { } void QboneClient::ClearDataToResend() { } bool QboneClient::HasActiveRequests() { return qbone_session()->HasActiveRequests(); } class QboneClientSessionWithConnection : public QboneClientSession { public: using QboneClientSession::QboneClientSession; ~QboneClientSessionWithConnection() override { DeleteConnection(); } }; std::unique_ptr<QuicSession> QboneClient::CreateQuicClientSession( const ParsedQuicVersionVector& supported_versions, QuicConnection* connection) { if (max_pacing_rate() > quic::QuicBandwidth::Zero()) { QUIC_LOG(INFO) << "Setting max pacing rate to " << max_pacing_rate(); connection->SetMaxPacingRate(max_pacing_rate()); } return std::make_unique<QboneClientSessionWithConnection>( connection, crypto_config(), session_owner(), *config(), supported_versions, server_id(), qbone_writer_, qbone_handler_); } bool QboneClient::use_quarantine_mode() const { return use_quarantine_mode_; } void QboneClient::set_use_quarantine_mode(bool use_quarantine_mode) { use_quarantine_mode_ = use_quarantine_mode; } }
#include "quiche/quic/qbone/qbone_client.h" #include <memory> #include <string> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/core/io/quic_default_event_loop.h" #include "quiche/quic/core/io/quic_event_loop.h" #include "quiche/quic/core/quic_alarm_factory.h" #include "quiche/quic/core/quic_default_clock.h" #include "quiche/quic/core/quic_default_connection_helper.h" #include "quiche/quic/core/quic_dispatcher.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/platform/api/quic_test_loopback.h" #include "quiche/quic/qbone/qbone_packet_processor_test_tools.h" #include "quiche/quic/qbone/qbone_server_session.h" #include "quiche/quic/test_tools/crypto_test_utils.h" #include "quiche/quic/test_tools/quic_connection_peer.h" #include "quiche/quic/test_tools/quic_dispatcher_peer.h" #include "quiche/quic/test_tools/quic_server_peer.h" #include "quiche/quic/test_tools/server_thread.h" #include "quiche/quic/tools/quic_memory_cache_backend.h" #include "quiche/quic/tools/quic_server.h" namespace quic { namespace test { namespace { using ::testing::ElementsAre; ParsedQuicVersionVector GetTestParams() { ParsedQuicVersionVector test_versions; SetQuicReloadableFlag(quic_disable_version_q046, false); return CurrentSupportedVersionsWithQuicCrypto(); } std::string TestPacketIn(const std::string& body) { return PrependIPv6HeaderForTest(body, 5); } std::string TestPacketOut(const std::string& body) { return PrependIPv6HeaderForTest(body, 4); } class DataSavingQbonePacketWriter : public QbonePacketWriter { public: void WritePacketToNetwork(const char* packet, size_t size) override { quiche::QuicheWriterMutexLock lock(&mu_); data_.push_back(std::string(packet, size)); } std::vector<std::string> data() { quiche::QuicheWriterMutexLock lock(&mu_); return data_; } private: quiche::QuicheMutex mu_; std::vector<std::string> data_; }; class ConnectionOwningQboneServerSession : public QboneServerSession { public: ConnectionOwningQboneServerSession( const ParsedQuicVersionVector& supported_versions, QuicConnection* connection, Visitor* owner, const QuicConfig& config, const QuicCryptoServerConfig* quic_crypto_server_config, QuicCompressedCertsCache* compressed_certs_cache, QbonePacketWriter* writer) : QboneServerSession(supported_versions, connection, owner, config, quic_crypto_server_config, compressed_certs_cache, writer, TestLoopback6(), TestLoopback6(), 64, nullptr), connection_(connection) {} private: std::unique_ptr<QuicConnection> connection_; }; class QuicQboneDispatcher : public QuicDispatcher { public: QuicQboneDispatcher( const QuicConfig* config, const QuicCryptoServerConfig* crypto_config, QuicVersionManager* version_manager, std::unique_ptr<QuicConnectionHelperInterface> helper, std::unique_ptr<QuicCryptoServerStreamBase::Helper> session_helper, std::unique_ptr<QuicAlarmFactory> alarm_factory, QbonePacketWriter* writer, ConnectionIdGeneratorInterface& generator) : QuicDispatcher(config, crypto_config, version_manager, std::move(helper), std::move(session_helper), std::move(alarm_factory), kQuicDefaultConnectionIdLength, generator), writer_(writer) {} std::unique_ptr<QuicSession> CreateQuicSession( QuicConnectionId id, const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, absl::string_view alpn, const ParsedQuicVersion& version, const ParsedClientHello& , ConnectionIdGeneratorInterface& connection_id_generator) override { QUICHE_CHECK_EQ(alpn, "qbone"); QuicConnection* connection = new QuicConnection( id, self_address, peer_address, helper(), alarm_factory(), writer(), false, Perspective::IS_SERVER, ParsedQuicVersionVector{version}, connection_id_generator); auto session = std::make_unique<ConnectionOwningQboneServerSession>( GetSupportedVersions(), connection, this, config(), crypto_config(), compressed_certs_cache(), writer_); session->Initialize(); return session; } private: QbonePacketWriter* writer_; }; class QboneTestServer : public QuicServer { public: explicit QboneTestServer(std::unique_ptr<ProofSource> proof_source, quic::QuicMemoryCacheBackend* response_cache) : QuicServer(std::move(proof_source), response_cache) {} QuicDispatcher* CreateQuicDispatcher() override { return new QuicQboneDispatcher( &config(), &crypto_config(), version_manager(), std::make_unique<QuicDefaultConnectionHelper>(), std::make_unique<QboneCryptoServerStreamHelper>(), event_loop()->CreateAlarmFactory(), &writer_, connection_id_generator()); } std::vector<std::string> data() { return writer_.data(); } private: DataSavingQbonePacketWriter writer_; }; class QboneTestClient : public QboneClient { public: QboneTestClient(QuicSocketAddress server_address, const QuicServerId& server_id, const ParsedQuicVersionVector& supported_versions, QuicEventLoop* event_loop, std::unique_ptr<ProofVerifier> proof_verifier) : QboneClient(server_address, server_id, supported_versions, nullptr, QuicConfig(), event_loop, std::move(proof_verifier), &qbone_writer_, nullptr) {} ~QboneTestClient() override {} void SendData(const std::string& data) { qbone_session()->ProcessPacketFromNetwork(data); } void WaitForWriteToFlush() { while (connected() && session()->HasDataToWrite()) { WaitForEvents(); } } bool WaitForDataSize(int n, QuicTime::Delta timeout) { const QuicClock* clock = quic::test::QuicConnectionPeer::GetHelper(session()->connection()) ->GetClock(); const QuicTime deadline = clock->Now() + timeout; while (data().size() < n) { if (clock->Now() > deadline) { return false; } WaitForEvents(); } return true; } std::vector<std::string> data() { return qbone_writer_.data(); } private: DataSavingQbonePacketWriter qbone_writer_; }; class QboneClientTest : public QuicTestWithParam<ParsedQuicVersion> {}; INSTANTIATE_TEST_SUITE_P(Tests, QboneClientTest, ::testing::ValuesIn(GetTestParams()), ::testing::PrintToStringParamName()); TEST_P(QboneClientTest, SendDataFromClient) { quic::QuicMemoryCacheBackend server_backend; auto server = std::make_unique<QboneTestServer>( crypto_test_utils::ProofSourceForTesting(), &server_backend); QboneTestServer* server_ptr = server.get(); QuicSocketAddress server_address(TestLoopback(), 0); ServerThread server_thread(std::move(server), server_address); server_thread.Initialize(); server_address = QuicSocketAddress(server_address.host(), server_thread.GetPort()); server_thread.Start(); std::unique_ptr<QuicEventLoop> event_loop = GetDefaultEventLoop()->Create(quic::QuicDefaultClock::Get()); QboneTestClient client( server_address, QuicServerId("test.example.com", server_address.port()), ParsedQuicVersionVector{GetParam()}, event_loop.get(), crypto_test_utils::ProofVerifierForTesting()); ASSERT_TRUE(client.Initialize()); ASSERT_TRUE(client.Connect()); ASSERT_TRUE(client.WaitForOneRttKeysAvailable()); client.SendData(TestPacketIn("hello")); client.SendData(TestPacketIn("world")); client.WaitForWriteToFlush(); ASSERT_TRUE( server_thread.WaitUntil([&] { return server_ptr->data().size() >= 2; }, QuicTime::Delta::FromSeconds(5))); std::string long_data(1000, 'A'); server_thread.Schedule([server_ptr, &long_data]() { EXPECT_THAT(server_ptr->data(), ElementsAre(TestPacketOut("hello"), TestPacketOut("world"))); auto server_session = static_cast<QboneServerSession*>( QuicDispatcherPeer::GetFirstSessionIfAny( QuicServerPeer::GetDispatcher(server_ptr))); server_session->ProcessPacketFromNetwork( TestPacketIn("Somethingsomething")); server_session->ProcessPacketFromNetwork(TestPacketIn(long_data)); server_session->ProcessPacketFromNetwork(TestPacketIn(long_data)); }); EXPECT_TRUE(client.WaitForDataSize(3, QuicTime::Delta::FromSeconds(5))); EXPECT_THAT(client.data(), ElementsAre(TestPacketOut("Somethingsomething"), TestPacketOut(long_data), TestPacketOut(long_data))); client.Disconnect(); server_thread.Quit(); server_thread.Join(); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/qbone/qbone_client.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/qbone/qbone_client_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
a217a66e-5969-4512-b0f5-1c473f8c4fa5
cpp
google/quiche
qbone_stream
quiche/quic/qbone/qbone_stream.cc
quiche/quic/qbone/qbone_stream_test.cc
#include "quiche/quic/qbone/qbone_stream.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_data_reader.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/qbone/qbone_constants.h" #include "quiche/quic/qbone/qbone_session_base.h" #include "quiche/common/platform/api/quiche_command_line_flags.h" DEFINE_QUICHE_COMMAND_LINE_FLAG(int, qbone_stream_ttl_secs, 3, "The QBONE Stream TTL in seconds."); namespace quic { QboneWriteOnlyStream::QboneWriteOnlyStream(QuicStreamId id, QuicSession* session) : QuicStream(id, session, false, WRITE_UNIDIRECTIONAL) { MaybeSetTtl(QuicTime::Delta::FromSeconds( quiche::GetQuicheCommandLineFlag(FLAGS_qbone_stream_ttl_secs))); } void QboneWriteOnlyStream::WritePacketToQuicStream(absl::string_view packet) { WriteOrBufferData(packet, true, nullptr); } QboneReadOnlyStream::QboneReadOnlyStream(QuicStreamId id, QboneSessionBase* session) : QuicStream(id, session, false, READ_UNIDIRECTIONAL), session_(session) { MaybeSetTtl(QuicTime::Delta::FromSeconds( quiche::GetQuicheCommandLineFlag(FLAGS_qbone_stream_ttl_secs))); } void QboneReadOnlyStream::OnDataAvailable() { sequencer()->Read(&buffer_); if (sequencer()->IsClosed()) { session_->ProcessPacketFromPeer(buffer_); OnFinRead(); return; } if (buffer_.size() > QboneConstants::kMaxQbonePacketBytes) { if (!rst_sent()) { Reset(QUIC_BAD_APPLICATION_PAYLOAD); } StopReading(); } } }
#include "quiche/quic/qbone/qbone_stream.h" #include <memory> #include <optional> #include <string> #include <utility> #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_stream_priority.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/platform/api/quic_test_loopback.h" #include "quiche/quic/qbone/qbone_constants.h" #include "quiche/quic/qbone/qbone_session_base.h" #include "quiche/quic/test_tools/mock_clock.h" #include "quiche/quic/test_tools/mock_connection_id_generator.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/simple_buffer_allocator.h" namespace quic { namespace { using ::testing::_; using ::testing::StrictMock; class MockQuicSession : public QboneSessionBase { public: MockQuicSession(QuicConnection* connection, const QuicConfig& config) : QboneSessionBase(connection, nullptr , config, CurrentSupportedVersions(), nullptr ) {} ~MockQuicSession() override {} QuicConsumedData WritevData(QuicStreamId id, size_t write_length, QuicStreamOffset offset, StreamSendingState state, TransmissionType type, EncryptionLevel level) override { if (!writable_) { return QuicConsumedData(0, false); } return QuicConsumedData(write_length, state != StreamSendingState::NO_FIN); } QboneReadOnlyStream* CreateIncomingStream(QuicStreamId id) override { return nullptr; } MOCK_METHOD(void, MaybeSendRstStreamFrame, (QuicStreamId stream_id, QuicResetStreamError error, QuicStreamOffset bytes_written), (override)); MOCK_METHOD(void, MaybeSendStopSendingFrame, (QuicStreamId stream_id, QuicResetStreamError error), (override)); void set_writable(bool writable) { writable_ = writable; } void RegisterReliableStream(QuicStreamId stream_id) { write_blocked_streams()->RegisterStream(stream_id, false, QuicStreamPriority()); } void ActivateReliableStream(std::unique_ptr<QuicStream> stream) { ActivateStream(std::move(stream)); } std::unique_ptr<QuicCryptoStream> CreateCryptoStream() override { return std::make_unique<test::MockQuicCryptoStream>(this); } MOCK_METHOD(void, ProcessPacketFromPeer, (absl::string_view), (override)); MOCK_METHOD(void, ProcessPacketFromNetwork, (absl::string_view), (override)); private: bool writable_ = true; }; class DummyPacketWriter : public QuicPacketWriter { public: DummyPacketWriter() {} WriteResult WritePacket(const char* buffer, size_t buf_len, const QuicIpAddress& self_address, const QuicSocketAddress& peer_address, PerPacketOptions* options, const QuicPacketWriterParams& params) override { return WriteResult(WRITE_STATUS_ERROR, 0); } bool IsWriteBlocked() const override { return false; }; void SetWritable() override {} std::optional<int> MessageTooBigErrorCode() const override { return std::nullopt; } QuicByteCount GetMaxPacketSize( const QuicSocketAddress& peer_address) const override { return 0; } bool SupportsReleaseTime() const override { return false; } bool IsBatchMode() const override { return false; } bool SupportsEcn() const override { return false; } QuicPacketBuffer GetNextWriteLocation( const QuicIpAddress& self_address, const QuicSocketAddress& peer_address) override { return {nullptr, nullptr}; } WriteResult Flush() override { return WriteResult(WRITE_STATUS_OK, 0); } }; class QboneReadOnlyStreamTest : public ::testing::Test, public QuicConnectionHelperInterface { public: void CreateReliableQuicStream() { Perspective perspective = Perspective::IS_SERVER; bool owns_writer = true; alarm_factory_ = std::make_unique<test::MockAlarmFactory>(); connection_.reset(new QuicConnection( test::TestConnectionId(0), QuicSocketAddress(TestLoopback(), 0), QuicSocketAddress(TestLoopback(), 0), this , alarm_factory_.get(), new DummyPacketWriter(), owns_writer, perspective, ParsedVersionOfIndex(CurrentSupportedVersions(), 0), connection_id_generator_)); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1)); session_ = std::make_unique<StrictMock<MockQuicSession>>(connection_.get(), QuicConfig()); session_->Initialize(); stream_ = new QboneReadOnlyStream(kStreamId, session_.get()); session_->ActivateReliableStream( std::unique_ptr<QboneReadOnlyStream>(stream_)); } ~QboneReadOnlyStreamTest() override {} const QuicClock* GetClock() const override { return &clock_; } QuicRandom* GetRandomGenerator() override { return QuicRandom::GetInstance(); } quiche::QuicheBufferAllocator* GetStreamSendBufferAllocator() override { return &buffer_allocator_; } protected: QboneReadOnlyStream* stream_; std::unique_ptr<StrictMock<MockQuicSession>> session_; std::unique_ptr<QuicAlarmFactory> alarm_factory_; std::unique_ptr<QuicConnection> connection_; quiche::SimpleBufferAllocator buffer_allocator_; MockClock clock_; const QuicStreamId kStreamId = QuicUtils::GetFirstUnidirectionalStreamId( CurrentSupportedVersions()[0].transport_version, Perspective::IS_CLIENT); quic::test::MockConnectionIdGenerator connection_id_generator_; }; TEST_F(QboneReadOnlyStreamTest, ReadDataWhole) { std::string packet = "Stuff"; CreateReliableQuicStream(); QuicStreamFrame frame(kStreamId, true, 0, packet); EXPECT_CALL(*session_, ProcessPacketFromPeer("Stuff")); stream_->OnStreamFrame(frame); } TEST_F(QboneReadOnlyStreamTest, ReadBuffered) { CreateReliableQuicStream(); std::string packet = "Stuf"; { QuicStreamFrame frame(kStreamId, false, 0, packet); stream_->OnStreamFrame(frame); } packet = "f"; EXPECT_CALL(*session_, ProcessPacketFromPeer("Stuff")); { QuicStreamFrame frame(kStreamId, true, 4, packet); stream_->OnStreamFrame(frame); } } TEST_F(QboneReadOnlyStreamTest, ReadOutOfOrder) { CreateReliableQuicStream(); std::string packet = "f"; { QuicStreamFrame frame(kStreamId, true, 4, packet); stream_->OnStreamFrame(frame); } packet = "S"; { QuicStreamFrame frame(kStreamId, false, 0, packet); stream_->OnStreamFrame(frame); } packet = "tuf"; EXPECT_CALL(*session_, ProcessPacketFromPeer("Stuff")); { QuicStreamFrame frame(kStreamId, false, 1, packet); stream_->OnStreamFrame(frame); } } TEST_F(QboneReadOnlyStreamTest, ReadBufferedTooLarge) { CreateReliableQuicStream(); std::string packet = "0123456789"; int iterations = (QboneConstants::kMaxQbonePacketBytes / packet.size()) + 2; EXPECT_CALL(*session_, MaybeSendStopSendingFrame( kStreamId, QuicResetStreamError::FromInternal( QUIC_BAD_APPLICATION_PAYLOAD))); EXPECT_CALL( *session_, MaybeSendRstStreamFrame( kStreamId, QuicResetStreamError::FromInternal(QUIC_BAD_APPLICATION_PAYLOAD), _)); for (int i = 0; i < iterations; ++i) { QuicStreamFrame frame(kStreamId, i == (iterations - 1), i * packet.size(), packet); if (!stream_->reading_stopped()) { stream_->OnStreamFrame(frame); } } EXPECT_TRUE(stream_->reading_stopped()); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/qbone/qbone_stream.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/qbone/qbone_stream_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
157ac252-c2fa-4689-9278-684810b59383
cpp
google/quiche
tun_device
quiche/quic/qbone/bonnet/tun_device.cc
quiche/quic/qbone/bonnet/tun_device_test.cc
#include "quiche/quic/qbone/bonnet/tun_device.h" #include <fcntl.h> #include <linux/if_tun.h> #include <net/if.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <ios> #include <string> #include "absl/cleanup/cleanup.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/qbone/platform/kernel_interface.h" ABSL_FLAG(std::string, qbone_client_tun_device_path, "/dev/net/tun", "The path to the QBONE client's TUN device."); namespace quic { const int kInvalidFd = -1; TunTapDevice::TunTapDevice(const std::string& interface_name, int mtu, bool persist, bool setup_tun, bool is_tap, KernelInterface* kernel) : interface_name_(interface_name), mtu_(mtu), persist_(persist), setup_tun_(setup_tun), is_tap_(is_tap), file_descriptor_(kInvalidFd), kernel_(*kernel) {} TunTapDevice::~TunTapDevice() { if (!persist_) { Down(); } CloseDevice(); } bool TunTapDevice::Init() { if (interface_name_.empty() || interface_name_.size() >= IFNAMSIZ) { QUIC_BUG(quic_bug_10995_1) << "interface_name must be nonempty and shorter than " << IFNAMSIZ; return false; } if (!OpenDevice()) { return false; } if (!ConfigureInterface()) { return false; } return true; } bool TunTapDevice::Up() { if (!setup_tun_) { return true; } struct ifreq if_request; memset(&if_request, 0, sizeof(if_request)); interface_name_.copy(if_request.ifr_name, IFNAMSIZ); if_request.ifr_flags = IFF_UP; return NetdeviceIoctl(SIOCSIFFLAGS, reinterpret_cast<void*>(&if_request)); } bool TunTapDevice::Down() { if (!setup_tun_) { return true; } struct ifreq if_request; memset(&if_request, 0, sizeof(if_request)); interface_name_.copy(if_request.ifr_name, IFNAMSIZ); if_request.ifr_flags = 0; return NetdeviceIoctl(SIOCSIFFLAGS, reinterpret_cast<void*>(&if_request)); } int TunTapDevice::GetFileDescriptor() const { return file_descriptor_; } bool TunTapDevice::OpenDevice() { if (file_descriptor_ != kInvalidFd) { CloseDevice(); } struct ifreq if_request; memset(&if_request, 0, sizeof(if_request)); interface_name_.copy(if_request.ifr_name, IFNAMSIZ); if_request.ifr_flags = IFF_MULTI_QUEUE | IFF_NO_PI; if (is_tap_) { if_request.ifr_flags |= IFF_TAP; } else { if_request.ifr_flags |= IFF_TUN; } bool successfully_opened = false; auto cleanup = absl::MakeCleanup([this, &successfully_opened]() { if (!successfully_opened) { CloseDevice(); } }); const std::string tun_device_path = absl::GetFlag(FLAGS_qbone_client_tun_device_path); int fd = kernel_.open(tun_device_path.c_str(), O_RDWR); if (fd < 0) { QUIC_PLOG(WARNING) << "Failed to open " << tun_device_path; return successfully_opened; } file_descriptor_ = fd; if (!CheckFeatures(fd)) { return successfully_opened; } if (kernel_.ioctl(fd, TUNSETIFF, reinterpret_cast<void*>(&if_request)) != 0) { QUIC_PLOG(WARNING) << "Failed to TUNSETIFF on fd(" << fd << ")"; return successfully_opened; } if (kernel_.ioctl( fd, TUNSETPERSIST, persist_ ? reinterpret_cast<void*>(&if_request) : nullptr) != 0) { QUIC_PLOG(WARNING) << "Failed to TUNSETPERSIST on fd(" << fd << ")"; return successfully_opened; } successfully_opened = true; return successfully_opened; } bool TunTapDevice::ConfigureInterface() { if (!setup_tun_) { return true; } struct ifreq if_request; memset(&if_request, 0, sizeof(if_request)); interface_name_.copy(if_request.ifr_name, IFNAMSIZ); if_request.ifr_mtu = mtu_; if (!NetdeviceIoctl(SIOCSIFMTU, reinterpret_cast<void*>(&if_request))) { CloseDevice(); return false; } return true; } bool TunTapDevice::CheckFeatures(int tun_device_fd) { unsigned int actual_features; if (kernel_.ioctl(tun_device_fd, TUNGETFEATURES, &actual_features) != 0) { QUIC_PLOG(WARNING) << "Failed to TUNGETFEATURES"; return false; } unsigned int required_features = IFF_TUN | IFF_NO_PI; if ((required_features & actual_features) != required_features) { QUIC_LOG(WARNING) << "Required feature does not exist. required_features: 0x" << std::hex << required_features << " vs actual_features: 0x" << std::hex << actual_features; return false; } return true; } bool TunTapDevice::NetdeviceIoctl(int request, void* argp) { int fd = kernel_.socket(AF_INET6, SOCK_DGRAM, 0); if (fd < 0) { QUIC_PLOG(WARNING) << "Failed to create AF_INET6 socket."; return false; } if (kernel_.ioctl(fd, request, argp) != 0) { QUIC_PLOG(WARNING) << "Failed ioctl request: " << request; kernel_.close(fd); return false; } kernel_.close(fd); return true; } void TunTapDevice::CloseDevice() { if (file_descriptor_ != kInvalidFd) { kernel_.close(file_descriptor_); file_descriptor_ = kInvalidFd; } } }
#include "quiche/quic/qbone/bonnet/tun_device.h" #include <linux/if.h> #include <linux/if_tun.h> #include <sys/ioctl.h> #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/qbone/platform/mock_kernel.h" namespace quic::test { namespace { using ::testing::_; using ::testing::AnyNumber; using ::testing::Invoke; using ::testing::Return; using ::testing::StrEq; using ::testing::Unused; const char kDeviceName[] = "tun0"; const int kSupportedFeatures = IFF_TUN | IFF_TAP | IFF_MULTI_QUEUE | IFF_ONE_QUEUE | IFF_NO_PI; class TunDeviceTest : public QuicTest { protected: void SetUp() override { EXPECT_CALL(mock_kernel_, socket(AF_INET6, _, _)) .Times(AnyNumber()) .WillRepeatedly(Invoke([this](Unused, Unused, Unused) { EXPECT_CALL(mock_kernel_, close(next_fd_)).WillOnce(Return(0)); return next_fd_++; })); } void SetInitExpectations(int mtu, bool persist) { EXPECT_CALL(mock_kernel_, open(StrEq("/dev/net/tun"), _)) .Times(AnyNumber()) .WillRepeatedly(Invoke([this](Unused, Unused) { EXPECT_CALL(mock_kernel_, close(next_fd_)).WillOnce(Return(0)); return next_fd_++; })); EXPECT_CALL(mock_kernel_, ioctl(_, TUNGETFEATURES, _)) .Times(AnyNumber()) .WillRepeatedly(Invoke([](Unused, Unused, void* argp) { auto* actual_flags = reinterpret_cast<int*>(argp); *actual_flags = kSupportedFeatures; return 0; })); EXPECT_CALL(mock_kernel_, ioctl(_, TUNSETIFF, _)) .Times(AnyNumber()) .WillRepeatedly(Invoke([](Unused, Unused, void* argp) { auto* ifr = reinterpret_cast<struct ifreq*>(argp); EXPECT_EQ(IFF_TUN | IFF_MULTI_QUEUE | IFF_NO_PI, ifr->ifr_flags); EXPECT_THAT(ifr->ifr_name, StrEq(kDeviceName)); return 0; })); EXPECT_CALL(mock_kernel_, ioctl(_, TUNSETPERSIST, _)) .Times(AnyNumber()) .WillRepeatedly(Invoke([persist](Unused, Unused, void* argp) { auto* ifr = reinterpret_cast<struct ifreq*>(argp); if (persist) { EXPECT_THAT(ifr->ifr_name, StrEq(kDeviceName)); } else { EXPECT_EQ(nullptr, ifr); } return 0; })); EXPECT_CALL(mock_kernel_, ioctl(_, SIOCSIFMTU, _)) .Times(AnyNumber()) .WillRepeatedly(Invoke([mtu](Unused, Unused, void* argp) { auto* ifr = reinterpret_cast<struct ifreq*>(argp); EXPECT_EQ(mtu, ifr->ifr_mtu); EXPECT_THAT(ifr->ifr_name, StrEq(kDeviceName)); return 0; })); } void ExpectUp(bool fail) { EXPECT_CALL(mock_kernel_, ioctl(_, SIOCSIFFLAGS, _)) .WillOnce(Invoke([fail](Unused, Unused, void* argp) { auto* ifr = reinterpret_cast<struct ifreq*>(argp); EXPECT_TRUE(ifr->ifr_flags & IFF_UP); EXPECT_THAT(ifr->ifr_name, StrEq(kDeviceName)); if (fail) { return -1; } else { return 0; } })); } void ExpectDown(bool fail) { EXPECT_CALL(mock_kernel_, ioctl(_, SIOCSIFFLAGS, _)) .WillOnce(Invoke([fail](Unused, Unused, void* argp) { auto* ifr = reinterpret_cast<struct ifreq*>(argp); EXPECT_FALSE(ifr->ifr_flags & IFF_UP); EXPECT_THAT(ifr->ifr_name, StrEq(kDeviceName)); if (fail) { return -1; } else { return 0; } })); } MockKernel mock_kernel_; int next_fd_ = 100; }; TEST_F(TunDeviceTest, BasicWorkFlow) { SetInitExpectations( 1500, false); TunTapDevice tun_device(kDeviceName, 1500, false, true, false, &mock_kernel_); EXPECT_TRUE(tun_device.Init()); EXPECT_GT(tun_device.GetFileDescriptor(), -1); ExpectUp( false); EXPECT_TRUE(tun_device.Up()); ExpectDown( false); } TEST_F(TunDeviceTest, FailToOpenTunDevice) { SetInitExpectations( 1500, false); EXPECT_CALL(mock_kernel_, open(StrEq("/dev/net/tun"), _)) .WillOnce(Return(-1)); TunTapDevice tun_device(kDeviceName, 1500, false, true, false, &mock_kernel_); EXPECT_FALSE(tun_device.Init()); EXPECT_EQ(tun_device.GetFileDescriptor(), -1); ExpectDown(false); } TEST_F(TunDeviceTest, FailToCheckFeature) { SetInitExpectations( 1500, false); EXPECT_CALL(mock_kernel_, ioctl(_, TUNGETFEATURES, _)).WillOnce(Return(-1)); TunTapDevice tun_device(kDeviceName, 1500, false, true, false, &mock_kernel_); EXPECT_FALSE(tun_device.Init()); EXPECT_EQ(tun_device.GetFileDescriptor(), -1); ExpectDown(false); } TEST_F(TunDeviceTest, TooFewFeature) { SetInitExpectations( 1500, false); EXPECT_CALL(mock_kernel_, ioctl(_, TUNGETFEATURES, _)) .WillOnce(Invoke([](Unused, Unused, void* argp) { int* actual_features = reinterpret_cast<int*>(argp); *actual_features = IFF_TUN | IFF_ONE_QUEUE; return 0; })); TunTapDevice tun_device(kDeviceName, 1500, false, true, false, &mock_kernel_); EXPECT_FALSE(tun_device.Init()); EXPECT_EQ(tun_device.GetFileDescriptor(), -1); ExpectDown(false); } TEST_F(TunDeviceTest, FailToSetFlag) { SetInitExpectations( 1500, true); EXPECT_CALL(mock_kernel_, ioctl(_, TUNSETIFF, _)).WillOnce(Return(-1)); TunTapDevice tun_device(kDeviceName, 1500, true, true, false, &mock_kernel_); EXPECT_FALSE(tun_device.Init()); EXPECT_EQ(tun_device.GetFileDescriptor(), -1); } TEST_F(TunDeviceTest, FailToPersistDevice) { SetInitExpectations( 1500, true); EXPECT_CALL(mock_kernel_, ioctl(_, TUNSETPERSIST, _)).WillOnce(Return(-1)); TunTapDevice tun_device(kDeviceName, 1500, true, true, false, &mock_kernel_); EXPECT_FALSE(tun_device.Init()); EXPECT_EQ(tun_device.GetFileDescriptor(), -1); } TEST_F(TunDeviceTest, FailToOpenSocket) { SetInitExpectations( 1500, true); EXPECT_CALL(mock_kernel_, socket(AF_INET6, _, _)).WillOnce(Return(-1)); TunTapDevice tun_device(kDeviceName, 1500, true, true, false, &mock_kernel_); EXPECT_FALSE(tun_device.Init()); EXPECT_EQ(tun_device.GetFileDescriptor(), -1); } TEST_F(TunDeviceTest, FailToSetMtu) { SetInitExpectations( 1500, true); EXPECT_CALL(mock_kernel_, ioctl(_, SIOCSIFMTU, _)).WillOnce(Return(-1)); TunTapDevice tun_device(kDeviceName, 1500, true, true, false, &mock_kernel_); EXPECT_FALSE(tun_device.Init()); EXPECT_EQ(tun_device.GetFileDescriptor(), -1); } TEST_F(TunDeviceTest, FailToUp) { SetInitExpectations( 1500, true); TunTapDevice tun_device(kDeviceName, 1500, true, true, false, &mock_kernel_); EXPECT_TRUE(tun_device.Init()); EXPECT_GT(tun_device.GetFileDescriptor(), -1); ExpectUp( true); EXPECT_FALSE(tun_device.Up()); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/qbone/bonnet/tun_device.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/qbone/bonnet/tun_device_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
255b3361-bf35-4cb8-8d6d-b19ad06cd67a
cpp
google/quiche
tun_device_controller
quiche/quic/qbone/bonnet/tun_device_controller.cc
quiche/quic/qbone/bonnet/tun_device_controller_test.cc
#include "quiche/quic/qbone/bonnet/tun_device_controller.h" #include <linux/rtnetlink.h> #include <utility> #include <vector> #include "absl/flags/flag.h" #include "absl/time/clock.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/qbone/qbone_constants.h" #include "quiche/common/quiche_callbacks.h" ABSL_FLAG(bool, qbone_tun_device_replace_default_routing_rules, true, "If true, will define a rule that points packets sourced from the " "qbone interface to the qbone table. This is unnecessary in " "environments with no other ipv6 route."); ABSL_RETIRED_FLAG(int, qbone_route_init_cwnd, 0, "Deprecated. Code no longer modifies initcwnd."); namespace quic { bool TunDeviceController::UpdateAddress(const IpRange& desired_range) { if (!setup_tun_) { return true; } NetlinkInterface::LinkInfo link_info{}; if (!netlink_->GetLinkInfo(ifname_, &link_info)) { return false; } std::vector<NetlinkInterface::AddressInfo> addresses; if (!netlink_->GetAddresses(link_info.index, 0, &addresses, nullptr)) { return false; } QuicIpAddress desired_address = desired_range.FirstAddressInRange(); for (const auto& address : addresses) { if (!netlink_->ChangeLocalAddress( link_info.index, NetlinkInterface::Verb::kRemove, address.interface_address, address.prefix_length, 0, 0, {})) { return false; } } bool address_updated = netlink_->ChangeLocalAddress( link_info.index, NetlinkInterface::Verb::kAdd, desired_address, desired_range.prefix_length(), IFA_F_PERMANENT | IFA_F_NODAD, RT_SCOPE_LINK, {}); if (address_updated) { current_address_ = desired_address; for (const auto& cb : address_update_cbs_) { cb(current_address_); } } return address_updated; } bool TunDeviceController::UpdateRoutes( const IpRange& desired_range, const std::vector<IpRange>& desired_routes) { if (!setup_tun_) { return true; } NetlinkInterface::LinkInfo link_info{}; if (!netlink_->GetLinkInfo(ifname_, &link_info)) { QUIC_LOG(ERROR) << "Could not get link info for interface <" << ifname_ << ">"; return false; } std::vector<NetlinkInterface::RoutingRule> routing_rules; if (!netlink_->GetRouteInfo(&routing_rules)) { QUIC_LOG(ERROR) << "Unable to get route info"; return false; } for (const auto& rule : routing_rules) { if (rule.out_interface == link_info.index && rule.table == QboneConstants::kQboneRouteTableId) { if (!netlink_->ChangeRoute(NetlinkInterface::Verb::kRemove, rule.table, rule.destination_subnet, rule.scope, rule.preferred_source, rule.out_interface)) { QUIC_LOG(ERROR) << "Unable to remove old route to <" << rule.destination_subnet.ToString() << ">"; return false; } } } if (!UpdateRules(desired_range)) { return false; } QuicIpAddress desired_address = desired_range.FirstAddressInRange(); std::vector<IpRange> routes(desired_routes.begin(), desired_routes.end()); routes.emplace_back(*QboneConstants::TerminatorLocalAddressRange()); for (const auto& route : routes) { if (!netlink_->ChangeRoute(NetlinkInterface::Verb::kReplace, QboneConstants::kQboneRouteTableId, route, RT_SCOPE_LINK, desired_address, link_info.index)) { QUIC_LOG(ERROR) << "Unable to add route <" << route.ToString() << ">"; return false; } } return true; } bool TunDeviceController::UpdateRoutesWithRetries( const IpRange& desired_range, const std::vector<IpRange>& desired_routes, int retries) { while (retries-- > 0) { if (UpdateRoutes(desired_range, desired_routes)) { return true; } absl::SleepFor(absl::Milliseconds(100)); } return false; } bool TunDeviceController::UpdateRules(IpRange desired_range) { if (!absl::GetFlag(FLAGS_qbone_tun_device_replace_default_routing_rules)) { return true; } std::vector<NetlinkInterface::IpRule> ip_rules; if (!netlink_->GetRuleInfo(&ip_rules)) { QUIC_LOG(ERROR) << "Unable to get rule info"; return false; } for (const auto& rule : ip_rules) { if (rule.table == QboneConstants::kQboneRouteTableId) { if (!netlink_->ChangeRule(NetlinkInterface::Verb::kRemove, rule.table, rule.source_range)) { QUIC_LOG(ERROR) << "Unable to remove old rule for table <" << rule.table << "> from source <" << rule.source_range.ToString() << ">"; return false; } } } if (!netlink_->ChangeRule(NetlinkInterface::Verb::kAdd, QboneConstants::kQboneRouteTableId, desired_range)) { QUIC_LOG(ERROR) << "Unable to add rule for <" << desired_range.ToString() << ">"; return false; } return true; } QuicIpAddress TunDeviceController::current_address() { return current_address_; } void TunDeviceController::RegisterAddressUpdateCallback( quiche::MultiUseCallback<void(QuicIpAddress)> cb) { address_update_cbs_.push_back(std::move(cb)); } }
#include "quiche/quic/qbone/bonnet/tun_device_controller.h" #include <linux/if_addr.h> #include <linux/rtnetlink.h> #include <string> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/qbone/platform/mock_netlink.h" #include "quiche/quic/qbone/qbone_constants.h" ABSL_DECLARE_FLAG(bool, qbone_tun_device_replace_default_routing_rules); ABSL_DECLARE_FLAG(int, qbone_route_init_cwnd); namespace quic::test { namespace { using ::testing::Eq; constexpr int kIfindex = 42; constexpr char kIfname[] = "qbone0"; const IpRange kIpRange = []() { IpRange range; QCHECK(range.FromString("2604:31c0:2::/64")); return range; }(); constexpr char kOldAddress[] = "1.2.3.4"; constexpr int kOldPrefixLen = 24; using ::testing::_; using ::testing::Invoke; using ::testing::Return; using ::testing::StrictMock; MATCHER_P(IpRangeEq, range, absl::StrCat("expected IpRange to equal ", range.ToString())) { return arg == range; } class TunDeviceControllerTest : public QuicTest { public: TunDeviceControllerTest() : controller_(kIfname, true, &netlink_), link_local_range_(*QboneConstants::TerminatorLocalAddressRange()) { controller_.RegisterAddressUpdateCallback( [this](QuicIpAddress address) { notified_address_ = address; }); } protected: void ExpectLinkInfo(const std::string& interface_name, int ifindex) { EXPECT_CALL(netlink_, GetLinkInfo(interface_name, _)) .WillOnce(Invoke([ifindex](absl::string_view ifname, NetlinkInterface::LinkInfo* link_info) { link_info->index = ifindex; return true; })); } MockNetlink netlink_; TunDeviceController controller_; QuicIpAddress notified_address_; IpRange link_local_range_; }; TEST_F(TunDeviceControllerTest, AddressAppliedWhenNoneExisted) { ExpectLinkInfo(kIfname, kIfindex); EXPECT_CALL(netlink_, GetAddresses(kIfindex, _, _, _)).WillOnce(Return(true)); EXPECT_CALL(netlink_, ChangeLocalAddress( kIfindex, NetlinkInterface::Verb::kAdd, kIpRange.FirstAddressInRange(), kIpRange.prefix_length(), IFA_F_PERMANENT | IFA_F_NODAD, RT_SCOPE_LINK, _)) .WillOnce(Return(true)); EXPECT_TRUE(controller_.UpdateAddress(kIpRange)); EXPECT_THAT(notified_address_, Eq(kIpRange.FirstAddressInRange())); } TEST_F(TunDeviceControllerTest, OldAddressesAreRemoved) { ExpectLinkInfo(kIfname, kIfindex); EXPECT_CALL(netlink_, GetAddresses(kIfindex, _, _, _)) .WillOnce(Invoke([](int interface_index, uint8_t unwanted_flags, std::vector<NetlinkInterface::AddressInfo>* addresses, int* num_ipv6_nodad_dadfailed_addresses) { NetlinkInterface::AddressInfo info{}; info.interface_address.FromString(kOldAddress); info.prefix_length = kOldPrefixLen; addresses->emplace_back(info); return true; })); QuicIpAddress old_address; old_address.FromString(kOldAddress); EXPECT_CALL(netlink_, ChangeLocalAddress(kIfindex, NetlinkInterface::Verb::kRemove, old_address, kOldPrefixLen, _, _, _)) .WillOnce(Return(true)); EXPECT_CALL(netlink_, ChangeLocalAddress( kIfindex, NetlinkInterface::Verb::kAdd, kIpRange.FirstAddressInRange(), kIpRange.prefix_length(), IFA_F_PERMANENT | IFA_F_NODAD, RT_SCOPE_LINK, _)) .WillOnce(Return(true)); EXPECT_TRUE(controller_.UpdateAddress(kIpRange)); EXPECT_THAT(notified_address_, Eq(kIpRange.FirstAddressInRange())); } TEST_F(TunDeviceControllerTest, UpdateRoutesRemovedOldRoutes) { ExpectLinkInfo(kIfname, kIfindex); const int num_matching_routes = 3; EXPECT_CALL(netlink_, GetRouteInfo(_)) .WillOnce( Invoke([](std::vector<NetlinkInterface::RoutingRule>* routing_rules) { NetlinkInterface::RoutingRule non_matching_route{}; non_matching_route.table = QboneConstants::kQboneRouteTableId; non_matching_route.out_interface = kIfindex + 1; routing_rules->push_back(non_matching_route); NetlinkInterface::RoutingRule matching_route{}; matching_route.table = QboneConstants::kQboneRouteTableId; matching_route.out_interface = kIfindex; for (int i = 0; i < num_matching_routes; i++) { routing_rules->push_back(matching_route); } NetlinkInterface::RoutingRule non_matching_table{}; non_matching_table.table = QboneConstants::kQboneRouteTableId + 1; non_matching_table.out_interface = kIfindex; routing_rules->push_back(non_matching_table); return true; })); EXPECT_CALL(netlink_, ChangeRoute(NetlinkInterface::Verb::kRemove, QboneConstants::kQboneRouteTableId, _, _, _, kIfindex)) .Times(num_matching_routes) .WillRepeatedly(Return(true)); EXPECT_CALL(netlink_, GetRuleInfo(_)).WillOnce(Return(true)); EXPECT_CALL(netlink_, ChangeRule(NetlinkInterface::Verb::kAdd, QboneConstants::kQboneRouteTableId, IpRangeEq(kIpRange))) .WillOnce(Return(true)); EXPECT_CALL(netlink_, ChangeRoute(NetlinkInterface::Verb::kReplace, QboneConstants::kQboneRouteTableId, IpRangeEq(link_local_range_), _, _, kIfindex)) .WillOnce(Return(true)); EXPECT_TRUE(controller_.UpdateRoutes(kIpRange, {})); } TEST_F(TunDeviceControllerTest, UpdateRoutesAddsNewRoutes) { ExpectLinkInfo(kIfname, kIfindex); EXPECT_CALL(netlink_, GetRouteInfo(_)).WillOnce(Return(true)); EXPECT_CALL(netlink_, GetRuleInfo(_)).WillOnce(Return(true)); EXPECT_CALL(netlink_, ChangeRoute(NetlinkInterface::Verb::kReplace, QboneConstants::kQboneRouteTableId, IpRangeEq(kIpRange), _, _, kIfindex)) .Times(2) .WillRepeatedly(Return(true)) .RetiresOnSaturation(); EXPECT_CALL(netlink_, ChangeRule(NetlinkInterface::Verb::kAdd, QboneConstants::kQboneRouteTableId, IpRangeEq(kIpRange))) .WillOnce(Return(true)); EXPECT_CALL(netlink_, ChangeRoute(NetlinkInterface::Verb::kReplace, QboneConstants::kQboneRouteTableId, IpRangeEq(link_local_range_), _, _, kIfindex)) .WillOnce(Return(true)); EXPECT_TRUE(controller_.UpdateRoutes(kIpRange, {kIpRange, kIpRange})); } TEST_F(TunDeviceControllerTest, EmptyUpdateRouteKeepsLinkLocalRoute) { ExpectLinkInfo(kIfname, kIfindex); EXPECT_CALL(netlink_, GetRouteInfo(_)).WillOnce(Return(true)); EXPECT_CALL(netlink_, GetRuleInfo(_)).WillOnce(Return(true)); EXPECT_CALL(netlink_, ChangeRule(NetlinkInterface::Verb::kAdd, QboneConstants::kQboneRouteTableId, IpRangeEq(kIpRange))) .WillOnce(Return(true)); EXPECT_CALL(netlink_, ChangeRoute(NetlinkInterface::Verb::kReplace, QboneConstants::kQboneRouteTableId, IpRangeEq(link_local_range_), _, _, kIfindex)) .WillOnce(Return(true)); EXPECT_TRUE(controller_.UpdateRoutes(kIpRange, {})); } TEST_F(TunDeviceControllerTest, DisablingRoutingRulesSkipsRuleCreation) { absl::SetFlag(&FLAGS_qbone_tun_device_replace_default_routing_rules, false); ExpectLinkInfo(kIfname, kIfindex); EXPECT_CALL(netlink_, GetRouteInfo(_)).WillOnce(Return(true)); EXPECT_CALL(netlink_, ChangeRoute(NetlinkInterface::Verb::kReplace, QboneConstants::kQboneRouteTableId, IpRangeEq(kIpRange), _, _, kIfindex)) .Times(2) .WillRepeatedly(Return(true)) .RetiresOnSaturation(); EXPECT_CALL(netlink_, ChangeRoute(NetlinkInterface::Verb::kReplace, QboneConstants::kQboneRouteTableId, IpRangeEq(link_local_range_), _, _, kIfindex)) .WillOnce(Return(true)); EXPECT_TRUE(controller_.UpdateRoutes(kIpRange, {kIpRange, kIpRange})); } class DisabledTunDeviceControllerTest : public QuicTest { public: DisabledTunDeviceControllerTest() : controller_(kIfname, false, &netlink_), link_local_range_(*QboneConstants::TerminatorLocalAddressRange()) {} StrictMock<MockNetlink> netlink_; TunDeviceController controller_; IpRange link_local_range_; }; TEST_F(DisabledTunDeviceControllerTest, UpdateRoutesIsNop) { EXPECT_THAT(controller_.UpdateRoutes(kIpRange, {}), Eq(true)); } TEST_F(DisabledTunDeviceControllerTest, UpdateAddressIsNop) { EXPECT_THAT(controller_.UpdateAddress(kIpRange), Eq(true)); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/qbone/bonnet/tun_device_controller.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/qbone/bonnet/tun_device_controller_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
668bf81b-a8db-4ed7-ae62-1dee10fb1e5c
cpp
google/quiche
tun_device_packet_exchanger
quiche/quic/qbone/bonnet/tun_device_packet_exchanger.cc
quiche/quic/qbone/bonnet/tun_device_packet_exchanger_test.cc
#include "quiche/quic/qbone/bonnet/tun_device_packet_exchanger.h" #include <netinet/icmp6.h> #include <netinet/ip6.h> #include <memory> #include <string> #include <utility> #include "absl/strings/str_cat.h" #include "quiche/quic/qbone/platform/icmp_packet.h" #include "quiche/quic/qbone/platform/netlink_interface.h" #include "quiche/quic/qbone/qbone_constants.h" namespace quic { TunDevicePacketExchanger::TunDevicePacketExchanger( size_t mtu, KernelInterface* kernel, NetlinkInterface* netlink, QbonePacketExchanger::Visitor* visitor, size_t max_pending_packets, bool is_tap, StatsInterface* stats, absl::string_view ifname) : QbonePacketExchanger(visitor, max_pending_packets), mtu_(mtu), kernel_(kernel), netlink_(netlink), ifname_(ifname), is_tap_(is_tap), stats_(stats) { if (is_tap_) { mtu_ += ETH_HLEN; } } bool TunDevicePacketExchanger::WritePacket(const char* packet, size_t size, bool* blocked, std::string* error) { *blocked = false; if (fd_ < 0) { *error = absl::StrCat("Invalid file descriptor of the TUN device: ", fd_); stats_->OnWriteError(error); return false; } auto buffer = std::make_unique<QuicData>(packet, size); if (is_tap_) { buffer = ApplyL2Headers(*buffer); } int result = kernel_->write(fd_, buffer->data(), buffer->length()); if (result == -1) { if (errno == EWOULDBLOCK || errno == EAGAIN) { *error = absl::ErrnoToStatus(errno, "Write to the TUN device was blocked.") .message(); *blocked = true; stats_->OnWriteError(error); } return false; } stats_->OnPacketWritten(result); return true; } std::unique_ptr<QuicData> TunDevicePacketExchanger::ReadPacket( bool* blocked, std::string* error) { *blocked = false; if (fd_ < 0) { *error = absl::StrCat("Invalid file descriptor of the TUN device: ", fd_); stats_->OnReadError(error); return nullptr; } auto read_buffer = std::make_unique<char[]>(mtu_); int result = kernel_->read(fd_, read_buffer.get(), mtu_); if (result <= 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) { *error = absl::ErrnoToStatus(errno, "Read from the TUN device was blocked.") .message(); *blocked = true; stats_->OnReadError(error); } return nullptr; } auto buffer = std::make_unique<QuicData>(read_buffer.release(), result, true); if (is_tap_) { buffer = ConsumeL2Headers(*buffer); } if (buffer) { stats_->OnPacketRead(buffer->length()); } return buffer; } void TunDevicePacketExchanger::set_file_descriptor(int fd) { fd_ = fd; } const TunDevicePacketExchanger::StatsInterface* TunDevicePacketExchanger::stats_interface() const { return stats_; } std::unique_ptr<QuicData> TunDevicePacketExchanger::ApplyL2Headers( const QuicData& l3_packet) { if (is_tap_ && !mac_initialized_) { NetlinkInterface::LinkInfo link_info{}; if (netlink_->GetLinkInfo(ifname_, &link_info)) { memcpy(tap_mac_, link_info.hardware_address, ETH_ALEN); mac_initialized_ = true; } else { QUIC_LOG_EVERY_N_SEC(ERROR, 30) << "Unable to get link info for: " << ifname_; } } const auto l2_packet_size = l3_packet.length() + ETH_HLEN; auto l2_buffer = std::make_unique<char[]>(l2_packet_size); auto* hdr = reinterpret_cast<ethhdr*>(l2_buffer.get()); memcpy(hdr->h_dest, tap_mac_, ETH_ALEN); memcpy(hdr->h_source, tap_mac_, ETH_ALEN); hdr->h_proto = absl::ghtons(ETH_P_IPV6); memcpy(l2_buffer.get() + ETH_HLEN, l3_packet.data(), l3_packet.length()); return std::make_unique<QuicData>(l2_buffer.release(), l2_packet_size, true); } std::unique_ptr<QuicData> TunDevicePacketExchanger::ConsumeL2Headers( const QuicData& l2_packet) { if (l2_packet.length() < ETH_HLEN) { return nullptr; } auto* hdr = reinterpret_cast<const ethhdr*>(l2_packet.data()); if (hdr->h_proto != absl::ghtons(ETH_P_IPV6)) { return nullptr; } constexpr auto kIp6PrefixLen = ETH_HLEN + sizeof(ip6_hdr); constexpr auto kIcmp6PrefixLen = kIp6PrefixLen + sizeof(icmp6_hdr); if (l2_packet.length() < kIp6PrefixLen) { return nullptr; } auto* ip_hdr = reinterpret_cast<const ip6_hdr*>(l2_packet.data() + ETH_HLEN); const bool is_icmp = ip_hdr->ip6_ctlun.ip6_un1.ip6_un1_nxt == IPPROTO_ICMPV6; bool is_neighbor_solicit = false; if (is_icmp) { if (l2_packet.length() < kIcmp6PrefixLen) { return nullptr; } is_neighbor_solicit = reinterpret_cast<const icmp6_hdr*>(l2_packet.data() + kIp6PrefixLen) ->icmp6_type == ND_NEIGHBOR_SOLICIT; } if (is_neighbor_solicit) { auto* icmp6_payload = l2_packet.data() + kIcmp6PrefixLen; QuicIpAddress target_address( *reinterpret_cast<const in6_addr*>(icmp6_payload)); if (target_address != *QboneConstants::GatewayAddress()) { return nullptr; } constexpr size_t kIcmpv6OptionSize = 8; const int payload_size = sizeof(in6_addr) + kIcmpv6OptionSize; auto payload = std::make_unique<char[]>(payload_size); memcpy(payload.get(), icmp6_payload, sizeof(in6_addr)); int pos = sizeof(in6_addr); payload[pos++] = ND_OPT_TARGET_LINKADDR; payload[pos++] = 1; memcpy(&payload[pos], tap_mac_, ETH_ALEN); icmp6_hdr response_hdr{}; response_hdr.icmp6_type = ND_NEIGHBOR_ADVERT; response_hdr.icmp6_dataun.icmp6_un_data8[0] = 64; CreateIcmpPacket(ip_hdr->ip6_src, ip_hdr->ip6_src, response_hdr, absl::string_view(payload.get(), payload_size), [this](absl::string_view packet) { bool blocked; std::string error; WritePacket(packet.data(), packet.size(), &blocked, &error); }); return nullptr; } const auto l3_packet_size = l2_packet.length() - ETH_HLEN; auto shift_buffer = std::make_unique<char[]>(l3_packet_size); memcpy(shift_buffer.get(), l2_packet.data() + ETH_HLEN, l3_packet_size); return std::make_unique<QuicData>(shift_buffer.release(), l3_packet_size, true); } }
#include "quiche/quic/qbone/bonnet/tun_device_packet_exchanger.h" #include <string> #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/qbone/bonnet/mock_packet_exchanger_stats_interface.h" #include "quiche/quic/qbone/mock_qbone_client.h" #include "quiche/quic/qbone/platform/mock_kernel.h" namespace quic::test { namespace { const size_t kMtu = 1000; const size_t kMaxPendingPackets = 5; const int kFd = 15; using ::testing::_; using ::testing::Invoke; using ::testing::StrEq; using ::testing::StrictMock; class MockVisitor : public QbonePacketExchanger::Visitor { public: MOCK_METHOD(void, OnReadError, (const std::string&), (override)); MOCK_METHOD(void, OnWriteError, (const std::string&), (override)); MOCK_METHOD(absl::Status, OnWrite, (absl::string_view), (override)); }; class TunDevicePacketExchangerTest : public QuicTest { protected: TunDevicePacketExchangerTest() : exchanger_(kMtu, &mock_kernel_, nullptr, &mock_visitor_, kMaxPendingPackets, false, &mock_stats_, absl::string_view()) { exchanger_.set_file_descriptor(kFd); } ~TunDevicePacketExchangerTest() override = default; MockKernel mock_kernel_; StrictMock<MockVisitor> mock_visitor_; StrictMock<MockQboneClient> mock_client_; StrictMock<MockPacketExchangerStatsInterface> mock_stats_; TunDevicePacketExchanger exchanger_; }; TEST_F(TunDevicePacketExchangerTest, WritePacketReturnsFalseOnError) { std::string packet = "fake packet"; EXPECT_CALL(mock_kernel_, write(kFd, _, packet.size())) .WillOnce(Invoke([](int fd, const void* buf, size_t count) { errno = ECOMM; return -1; })); EXPECT_CALL(mock_visitor_, OnWriteError(_)); EXPECT_CALL(mock_visitor_, OnWrite(StrEq(packet))).Times(1); exchanger_.WritePacketToNetwork(packet.data(), packet.size()); } TEST_F(TunDevicePacketExchangerTest, WritePacketReturnFalseAndBlockedOnBlockedTunnel) { std::string packet = "fake packet"; EXPECT_CALL(mock_kernel_, write(kFd, _, packet.size())) .WillOnce(Invoke([](int fd, const void* buf, size_t count) { errno = EAGAIN; return -1; })); EXPECT_CALL(mock_stats_, OnWriteError(_)).Times(1); EXPECT_CALL(mock_visitor_, OnWrite(StrEq(packet))).Times(1); exchanger_.WritePacketToNetwork(packet.data(), packet.size()); } TEST_F(TunDevicePacketExchangerTest, WritePacketReturnsTrueOnSuccessfulWrite) { std::string packet = "fake packet"; EXPECT_CALL(mock_kernel_, write(kFd, _, packet.size())) .WillOnce(Invoke([packet](int fd, const void* buf, size_t count) { EXPECT_THAT(reinterpret_cast<const char*>(buf), StrEq(packet)); return count; })); EXPECT_CALL(mock_stats_, OnPacketWritten(_)).Times(1); EXPECT_CALL(mock_visitor_, OnWrite(StrEq(packet))).Times(1); exchanger_.WritePacketToNetwork(packet.data(), packet.size()); } TEST_F(TunDevicePacketExchangerTest, ReadPacketReturnsNullOnError) { EXPECT_CALL(mock_kernel_, read(kFd, _, kMtu)) .WillOnce(Invoke([](int fd, void* buf, size_t count) { errno = ECOMM; return -1; })); EXPECT_CALL(mock_visitor_, OnReadError(_)); exchanger_.ReadAndDeliverPacket(&mock_client_); } TEST_F(TunDevicePacketExchangerTest, ReadPacketReturnsNullOnBlockedRead) { EXPECT_CALL(mock_kernel_, read(kFd, _, kMtu)) .WillOnce(Invoke([](int fd, void* buf, size_t count) { errno = EAGAIN; return -1; })); EXPECT_CALL(mock_stats_, OnReadError(_)).Times(1); EXPECT_FALSE(exchanger_.ReadAndDeliverPacket(&mock_client_)); } TEST_F(TunDevicePacketExchangerTest, ReadPacketReturnsThePacketOnSuccessfulRead) { std::string packet = "fake_packet"; EXPECT_CALL(mock_kernel_, read(kFd, _, kMtu)) .WillOnce(Invoke([packet](int fd, void* buf, size_t count) { memcpy(buf, packet.data(), packet.size()); return packet.size(); })); EXPECT_CALL(mock_client_, ProcessPacketFromNetwork(StrEq(packet))); EXPECT_CALL(mock_stats_, OnPacketRead(_)).Times(1); EXPECT_TRUE(exchanger_.ReadAndDeliverPacket(&mock_client_)); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/qbone/bonnet/tun_device_packet_exchanger.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/qbone/bonnet/tun_device_packet_exchanger_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
e6db5c00-dfce-46d8-abed-ae3cefc506d1
cpp
google/quiche
icmp_reachable
quiche/quic/qbone/bonnet/icmp_reachable.cc
quiche/quic/qbone/bonnet/icmp_reachable_test.cc
#include "quiche/quic/qbone/bonnet/icmp_reachable.h" #include <netinet/ip6.h> #include <string> #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/io/quic_event_loop.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/qbone/platform/icmp_packet.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_text_utils.h" namespace quic { namespace { constexpr QuicSocketEventMask kEventMask = kSocketEventReadable | kSocketEventWritable; constexpr size_t kMtu = 1280; constexpr size_t kIPv6AddrSize = sizeof(in6_addr); } const char kUnknownSource[] = "UNKNOWN"; const char kNoSource[] = "N/A"; IcmpReachable::IcmpReachable(QuicIpAddress source, QuicIpAddress destination, QuicTime::Delta timeout, KernelInterface* kernel, QuicEventLoop* event_loop, StatsInterface* stats) : timeout_(timeout), event_loop_(event_loop), clock_(event_loop->GetClock()), alarm_factory_(event_loop->CreateAlarmFactory()), cb_(this), alarm_(alarm_factory_->CreateAlarm(new AlarmCallback(this))), kernel_(kernel), stats_(stats), send_fd_(0), recv_fd_(0) { src_.sin6_family = AF_INET6; dst_.sin6_family = AF_INET6; memcpy(&src_.sin6_addr, source.ToPackedString().data(), kIPv6AddrSize); memcpy(&dst_.sin6_addr, destination.ToPackedString().data(), kIPv6AddrSize); } IcmpReachable::~IcmpReachable() { if (send_fd_ > 0) { kernel_->close(send_fd_); } if (recv_fd_ > 0) { bool success = event_loop_->UnregisterSocket(recv_fd_); QUICHE_DCHECK(success); kernel_->close(recv_fd_); } } bool IcmpReachable::Init() { send_fd_ = kernel_->socket(PF_INET6, SOCK_RAW | SOCK_NONBLOCK, IPPROTO_RAW); if (send_fd_ < 0) { QUIC_PLOG(ERROR) << "Unable to open socket."; return false; } if (kernel_->bind(send_fd_, reinterpret_cast<struct sockaddr*>(&src_), sizeof(sockaddr_in6)) < 0) { QUIC_PLOG(ERROR) << "Unable to bind socket."; return false; } recv_fd_ = kernel_->socket(PF_INET6, SOCK_RAW | SOCK_NONBLOCK, IPPROTO_ICMPV6); if (recv_fd_ < 0) { QUIC_PLOG(ERROR) << "Unable to open socket."; return false; } if (kernel_->bind(recv_fd_, reinterpret_cast<struct sockaddr*>(&src_), sizeof(sockaddr_in6)) < 0) { QUIC_PLOG(ERROR) << "Unable to bind socket."; return false; } icmp6_filter filter; ICMP6_FILTER_SETBLOCKALL(&filter); ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &filter); if (kernel_->setsockopt(recv_fd_, SOL_ICMPV6, ICMP6_FILTER, &filter, sizeof(filter)) < 0) { QUIC_LOG(ERROR) << "Unable to set ICMP6 filter."; return false; } if (!event_loop_->RegisterSocket(recv_fd_, kEventMask, &cb_)) { QUIC_LOG(ERROR) << "Unable to register recv ICMP socket"; return false; } alarm_->Set(clock_->Now()); quiche::QuicheWriterMutexLock mu(&header_lock_); icmp_header_.icmp6_type = ICMP6_ECHO_REQUEST; icmp_header_.icmp6_code = 0; QuicRandom::GetInstance()->RandBytes(&icmp_header_.icmp6_id, sizeof(uint16_t)); return true; } bool IcmpReachable::OnEvent(int fd) { char buffer[kMtu]; sockaddr_in6 source_addr{}; socklen_t source_addr_len = sizeof(source_addr); ssize_t size = kernel_->recvfrom(fd, &buffer, kMtu, 0, reinterpret_cast<sockaddr*>(&source_addr), &source_addr_len); if (size < 0) { if (errno != EAGAIN && errno != EWOULDBLOCK) { stats_->OnReadError(errno); } return false; } QUIC_VLOG(2) << quiche::QuicheTextUtils::HexDump( absl::string_view(buffer, size)); auto* header = reinterpret_cast<const icmp6_hdr*>(&buffer); quiche::QuicheWriterMutexLock mu(&header_lock_); if (header->icmp6_data32[0] != icmp_header_.icmp6_data32[0]) { QUIC_VLOG(2) << "Unexpected response. id: " << header->icmp6_id << " seq: " << header->icmp6_seq << " Expected id: " << icmp_header_.icmp6_id << " seq: " << icmp_header_.icmp6_seq; return true; } end_ = clock_->Now(); QUIC_VLOG(1) << "Received ping response in " << (end_ - start_); std::string source; QuicIpAddress source_ip; if (!source_ip.FromPackedString( reinterpret_cast<char*>(&source_addr.sin6_addr), sizeof(in6_addr))) { QUIC_LOG(WARNING) << "Unable to parse source address."; source = kUnknownSource; } else { source = source_ip.ToString(); } stats_->OnEvent({Status::REACHABLE, end_ - start_, source}); return true; } void IcmpReachable::OnAlarm() { quiche::QuicheWriterMutexLock mu(&header_lock_); if (end_ < start_) { QUIC_VLOG(1) << "Timed out on sequence: " << icmp_header_.icmp6_seq; stats_->OnEvent({Status::UNREACHABLE, QuicTime::Delta::Zero(), kNoSource}); } icmp_header_.icmp6_seq++; CreateIcmpPacket(src_.sin6_addr, dst_.sin6_addr, icmp_header_, "", [this](absl::string_view packet) { QUIC_VLOG(2) << quiche::QuicheTextUtils::HexDump(packet); ssize_t size = kernel_->sendto( send_fd_, packet.data(), packet.size(), 0, reinterpret_cast<struct sockaddr*>(&dst_), sizeof(sockaddr_in6)); if (size < packet.size()) { stats_->OnWriteError(errno); } start_ = clock_->Now(); }); alarm_->Set(clock_->ApproximateNow() + timeout_); } absl::string_view IcmpReachable::StatusName(IcmpReachable::Status status) { switch (status) { case REACHABLE: return "REACHABLE"; case UNREACHABLE: return "UNREACHABLE"; default: return "UNKNOWN"; } } void IcmpReachable::EpollCallback::OnSocketEvent(QuicEventLoop* event_loop, SocketFd fd, QuicSocketEventMask events) { bool can_read_more = reachable_->OnEvent(fd); if (can_read_more) { bool success = event_loop->ArtificiallyNotifyEvent(fd, kSocketEventReadable); QUICHE_DCHECK(success); } } }
#include "quiche/quic/qbone/bonnet/icmp_reachable.h" #include <netinet/ip6.h> #include <memory> #include <string> #include "absl/container/node_hash_map.h" #include "quiche/quic/core/io/quic_default_event_loop.h" #include "quiche/quic/core/io/quic_event_loop.h" #include "quiche/quic/core/quic_default_clock.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/qbone/platform/mock_kernel.h" namespace quic::test { namespace { using ::testing::_; using ::testing::InSequence; using ::testing::Invoke; using ::testing::Return; using ::testing::StrictMock; constexpr char kSourceAddress[] = "fe80:1:2:3:4::1"; constexpr char kDestinationAddress[] = "fe80:4:3:2:1::1"; constexpr int kFakeWriteFd = 0; icmp6_hdr GetHeaderFromPacket(const void* buf, size_t len) { QUICHE_CHECK_GE(len, sizeof(ip6_hdr) + sizeof(icmp6_hdr)); auto* buffer = reinterpret_cast<const char*>(buf); return *reinterpret_cast<const icmp6_hdr*>(&buffer[sizeof(ip6_hdr)]); } class StatsInterface : public IcmpReachable::StatsInterface { public: void OnEvent(IcmpReachable::ReachableEvent event) override { switch (event.status) { case IcmpReachable::REACHABLE: { reachable_count_++; break; } case IcmpReachable::UNREACHABLE: { unreachable_count_++; break; } } current_source_ = event.source; } void OnReadError(int error) override { read_errors_[error]++; } void OnWriteError(int error) override { write_errors_[error]++; } bool HasWriteErrors() { return !write_errors_.empty(); } int WriteErrorCount(int error) { return write_errors_[error]; } bool HasReadErrors() { return !read_errors_.empty(); } int ReadErrorCount(int error) { return read_errors_[error]; } int reachable_count() { return reachable_count_; } int unreachable_count() { return unreachable_count_; } std::string current_source() { return current_source_; } private: int reachable_count_ = 0; int unreachable_count_ = 0; std::string current_source_{}; absl::node_hash_map<int, int> read_errors_; absl::node_hash_map<int, int> write_errors_; }; class IcmpReachableTest : public QuicTest { public: IcmpReachableTest() : event_loop_(GetDefaultEventLoop()->Create(QuicDefaultClock::Get())) { QUICHE_CHECK(source_.FromString(kSourceAddress)); QUICHE_CHECK(destination_.FromString(kDestinationAddress)); int pipe_fds[2]; QUICHE_CHECK(pipe(pipe_fds) >= 0) << "pipe() failed"; read_fd_ = pipe_fds[0]; read_src_fd_ = pipe_fds[1]; } void SetFdExpectations() { InSequence seq; EXPECT_CALL(kernel_, socket(_, _, _)).WillOnce(Return(kFakeWriteFd)); EXPECT_CALL(kernel_, bind(kFakeWriteFd, _, _)).WillOnce(Return(0)); EXPECT_CALL(kernel_, socket(_, _, _)).WillOnce(Return(read_fd_)); EXPECT_CALL(kernel_, bind(read_fd_, _, _)).WillOnce(Return(0)); EXPECT_CALL(kernel_, setsockopt(read_fd_, SOL_ICMPV6, ICMP6_FILTER, _, _)); EXPECT_CALL(kernel_, close(read_fd_)).WillOnce(Invoke([](int fd) { return close(fd); })); } protected: QuicIpAddress source_; QuicIpAddress destination_; int read_fd_; int read_src_fd_; StrictMock<MockKernel> kernel_; std::unique_ptr<QuicEventLoop> event_loop_; StatsInterface stats_; }; TEST_F(IcmpReachableTest, SendsPings) { IcmpReachable reachable(source_, destination_, QuicTime::Delta::Zero(), &kernel_, event_loop_.get(), &stats_); SetFdExpectations(); ASSERT_TRUE(reachable.Init()); EXPECT_CALL(kernel_, sendto(kFakeWriteFd, _, _, _, _, _)) .WillOnce(Invoke([](int sockfd, const void* buf, size_t len, int flags, const struct sockaddr* dest_addr, socklen_t addrlen) { auto icmp_header = GetHeaderFromPacket(buf, len); EXPECT_EQ(icmp_header.icmp6_type, ICMP6_ECHO_REQUEST); EXPECT_EQ(icmp_header.icmp6_seq, 1); return len; })); event_loop_->RunEventLoopOnce(QuicTime::Delta::FromSeconds(1)); EXPECT_FALSE(stats_.HasWriteErrors()); } TEST_F(IcmpReachableTest, HandlesUnreachableEvents) { IcmpReachable reachable(source_, destination_, QuicTime::Delta::Zero(), &kernel_, event_loop_.get(), &stats_); SetFdExpectations(); ASSERT_TRUE(reachable.Init()); EXPECT_CALL(kernel_, sendto(kFakeWriteFd, _, _, _, _, _)) .Times(2) .WillRepeatedly(Invoke([](int sockfd, const void* buf, size_t len, int flags, const struct sockaddr* dest_addr, socklen_t addrlen) { return len; })); event_loop_->RunEventLoopOnce(QuicTime::Delta::FromSeconds(1)); EXPECT_EQ(stats_.unreachable_count(), 0); event_loop_->RunEventLoopOnce(QuicTime::Delta::FromSeconds(1)); EXPECT_FALSE(stats_.HasWriteErrors()); EXPECT_EQ(stats_.unreachable_count(), 1); EXPECT_EQ(stats_.current_source(), kNoSource); } TEST_F(IcmpReachableTest, HandlesReachableEvents) { IcmpReachable reachable(source_, destination_, QuicTime::Delta::Zero(), &kernel_, event_loop_.get(), &stats_); SetFdExpectations(); ASSERT_TRUE(reachable.Init()); icmp6_hdr last_request_hdr{}; EXPECT_CALL(kernel_, sendto(kFakeWriteFd, _, _, _, _, _)) .Times(2) .WillRepeatedly( Invoke([&last_request_hdr]( int sockfd, const void* buf, size_t len, int flags, const struct sockaddr* dest_addr, socklen_t addrlen) { last_request_hdr = GetHeaderFromPacket(buf, len); return len; })); sockaddr_in6 source_addr{}; std::string packed_source = source_.ToPackedString(); memcpy(&source_addr.sin6_addr, packed_source.data(), packed_source.size()); EXPECT_CALL(kernel_, recvfrom(read_fd_, _, _, _, _, _)) .WillOnce( Invoke([&source_addr](int sockfd, void* buf, size_t len, int flags, struct sockaddr* src_addr, socklen_t* addrlen) { *reinterpret_cast<sockaddr_in6*>(src_addr) = source_addr; return read(sockfd, buf, len); })); event_loop_->RunEventLoopOnce(QuicTime::Delta::FromSeconds(1)); EXPECT_EQ(stats_.reachable_count(), 0); icmp6_hdr response = last_request_hdr; response.icmp6_type = ICMP6_ECHO_REPLY; write(read_src_fd_, reinterpret_cast<const void*>(&response), sizeof(icmp6_hdr)); event_loop_->RunEventLoopOnce(QuicTime::Delta::FromSeconds(1)); EXPECT_FALSE(stats_.HasReadErrors()); EXPECT_FALSE(stats_.HasWriteErrors()); EXPECT_EQ(stats_.reachable_count(), 1); EXPECT_EQ(stats_.current_source(), source_.ToString()); } TEST_F(IcmpReachableTest, HandlesWriteErrors) { IcmpReachable reachable(source_, destination_, QuicTime::Delta::Zero(), &kernel_, event_loop_.get(), &stats_); SetFdExpectations(); ASSERT_TRUE(reachable.Init()); EXPECT_CALL(kernel_, sendto(kFakeWriteFd, _, _, _, _, _)) .WillOnce(Invoke([](int sockfd, const void* buf, size_t len, int flags, const struct sockaddr* dest_addr, socklen_t addrlen) { errno = EAGAIN; return 0; })); event_loop_->RunEventLoopOnce(QuicTime::Delta::FromSeconds(1)); EXPECT_EQ(stats_.WriteErrorCount(EAGAIN), 1); } TEST_F(IcmpReachableTest, HandlesReadErrors) { IcmpReachable reachable(source_, destination_, QuicTime::Delta::Zero(), &kernel_, event_loop_.get(), &stats_); SetFdExpectations(); ASSERT_TRUE(reachable.Init()); EXPECT_CALL(kernel_, sendto(kFakeWriteFd, _, _, _, _, _)) .WillOnce(Invoke([](int sockfd, const void* buf, size_t len, int flags, const struct sockaddr* dest_addr, socklen_t addrlen) { return len; })); EXPECT_CALL(kernel_, recvfrom(read_fd_, _, _, _, _, _)) .WillOnce(Invoke([](int sockfd, void* buf, size_t len, int flags, struct sockaddr* src_addr, socklen_t* addrlen) { errno = EIO; return -1; })); icmp6_hdr response{}; write(read_src_fd_, reinterpret_cast<const void*>(&response), sizeof(icmp6_hdr)); event_loop_->RunEventLoopOnce(QuicTime::Delta::FromSeconds(1)); EXPECT_EQ(stats_.reachable_count(), 0); EXPECT_EQ(stats_.ReadErrorCount(EIO), 1); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/qbone/bonnet/icmp_reachable.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/qbone/bonnet/icmp_reachable_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
5e8694bc-5801-48fa-903c-52aec37caa65
cpp
google/quiche
qbone_tunnel_silo
quiche/quic/qbone/bonnet/qbone_tunnel_silo.cc
quiche/quic/qbone/bonnet/qbone_tunnel_silo_test.cc
#include "quiche/quic/qbone/bonnet/qbone_tunnel_silo.h" namespace quic { void QboneTunnelSilo::Run() { while (ShouldRun()) { tunnel_->WaitForEvents(); } QUIC_LOG(INFO) << "Tunnel has disconnected in state: " << tunnel_->StateToString(tunnel_->Disconnect()); } void QboneTunnelSilo::Quit() { QUIC_LOG(INFO) << "Quit called on QboneTunnelSilo"; quitting_.Notify(); tunnel_->Wake(); } bool QboneTunnelSilo::ShouldRun() { bool post_init_shutdown_ready = only_setup_tun_ && tunnel_->state() == quic::QboneTunnelInterface::STARTED; return !quitting_.HasBeenNotified() && !post_init_shutdown_ready; } }
#include "quiche/quic/qbone/bonnet/qbone_tunnel_silo.h" #include "absl/synchronization/notification.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/qbone/bonnet/mock_qbone_tunnel.h" namespace quic { namespace { using ::testing::Eq; using ::testing::Invoke; using ::testing::Return; TEST(QboneTunnelSiloTest, SiloRunsEventLoop) { MockQboneTunnel mock_tunnel; absl::Notification event_loop_run; EXPECT_CALL(mock_tunnel, WaitForEvents) .WillRepeatedly(Invoke([&event_loop_run]() { if (!event_loop_run.HasBeenNotified()) { event_loop_run.Notify(); } return false; })); QboneTunnelSilo silo(&mock_tunnel, false); silo.Start(); event_loop_run.WaitForNotification(); absl::Notification client_disconnected; EXPECT_CALL(mock_tunnel, Disconnect) .WillOnce(Invoke([&client_disconnected]() { client_disconnected.Notify(); return QboneTunnelInterface::ENDED; })); silo.Quit(); client_disconnected.WaitForNotification(); silo.Join(); } TEST(QboneTunnelSiloTest, SiloCanShutDownAfterInit) { MockQboneTunnel mock_tunnel; int iteration_count = 0; EXPECT_CALL(mock_tunnel, WaitForEvents) .WillRepeatedly(Invoke([&iteration_count]() { iteration_count++; return false; })); EXPECT_CALL(mock_tunnel, state) .WillOnce(Return(QboneTunnelInterface::START_REQUESTED)) .WillOnce(Return(QboneTunnelInterface::STARTED)); absl::Notification client_disconnected; EXPECT_CALL(mock_tunnel, Disconnect) .WillOnce(Invoke([&client_disconnected]() { client_disconnected.Notify(); return QboneTunnelInterface::ENDED; })); QboneTunnelSilo silo(&mock_tunnel, true); silo.Start(); client_disconnected.WaitForNotification(); silo.Join(); EXPECT_THAT(iteration_count, Eq(1)); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/qbone/bonnet/qbone_tunnel_silo.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/qbone/bonnet/qbone_tunnel_silo_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
7091306e-56ad-4352-8992-08f37b677804
cpp
google/quiche
ip_range
quiche/quic/qbone/platform/ip_range.cc
quiche/quic/qbone/platform/ip_range_test.cc
#include "quiche/quic/qbone/platform/ip_range.h" #include <string> #include "quiche/common/quiche_endian.h" namespace quic { namespace { constexpr size_t kIPv4Size = 32; constexpr size_t kIPv6Size = 128; QuicIpAddress TruncateToLength(const QuicIpAddress& input, size_t* prefix_length) { QuicIpAddress output; if (input.IsIPv4()) { if (*prefix_length > kIPv4Size) { *prefix_length = kIPv4Size; return input; } uint32_t raw_address = *reinterpret_cast<const uint32_t*>(input.ToPackedString().data()); raw_address = quiche::QuicheEndian::NetToHost32(raw_address); raw_address &= ~0U << (kIPv4Size - *prefix_length); raw_address = quiche::QuicheEndian::HostToNet32(raw_address); output.FromPackedString(reinterpret_cast<const char*>(&raw_address), sizeof(raw_address)); return output; } if (input.IsIPv6()) { if (*prefix_length > kIPv6Size) { *prefix_length = kIPv6Size; return input; } uint64_t raw_address[2]; memcpy(raw_address, input.ToPackedString().data(), sizeof(raw_address)); raw_address[0] = quiche::QuicheEndian::NetToHost64(raw_address[0]); raw_address[1] = quiche::QuicheEndian::NetToHost64(raw_address[1]); if (*prefix_length <= kIPv6Size / 2) { raw_address[0] &= ~uint64_t{0} << (kIPv6Size / 2 - *prefix_length); raw_address[1] = 0; } else { raw_address[1] &= ~uint64_t{0} << (kIPv6Size - *prefix_length); } raw_address[0] = quiche::QuicheEndian::HostToNet64(raw_address[0]); raw_address[1] = quiche::QuicheEndian::HostToNet64(raw_address[1]); output.FromPackedString(reinterpret_cast<const char*>(raw_address), sizeof(raw_address)); return output; } return output; } } IpRange::IpRange(const QuicIpAddress& prefix, size_t prefix_length) : prefix_(prefix), prefix_length_(prefix_length) { prefix_ = TruncateToLength(prefix_, &prefix_length_); } bool IpRange::operator==(IpRange other) const { return prefix_ == other.prefix_ && prefix_length_ == other.prefix_length_; } bool IpRange::operator!=(IpRange other) const { return !(*this == other); } bool IpRange::FromString(const std::string& range) { size_t slash_pos = range.find('/'); if (slash_pos == std::string::npos) { return false; } QuicIpAddress prefix; bool success = prefix.FromString(range.substr(0, slash_pos)); if (!success) { return false; } uint64_t num_processed = 0; size_t prefix_length = std::stoi(range.substr(slash_pos + 1), &num_processed); if (num_processed + 1 + slash_pos != range.length()) { return false; } prefix_ = TruncateToLength(prefix, &prefix_length); prefix_length_ = prefix_length; return true; } QuicIpAddress IpRange::FirstAddressInRange() const { return prefix(); } }
#include "quiche/quic/qbone/platform/ip_range.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace { TEST(IpRangeTest, TruncateWorksIPv4) { QuicIpAddress before_truncate; before_truncate.FromString("255.255.255.255"); EXPECT_EQ("128.0.0.0/1", IpRange(before_truncate, 1).ToString()); EXPECT_EQ("192.0.0.0/2", IpRange(before_truncate, 2).ToString()); EXPECT_EQ("255.224.0.0/11", IpRange(before_truncate, 11).ToString()); EXPECT_EQ("255.255.255.224/27", IpRange(before_truncate, 27).ToString()); EXPECT_EQ("255.255.255.254/31", IpRange(before_truncate, 31).ToString()); EXPECT_EQ("255.255.255.255/32", IpRange(before_truncate, 32).ToString()); EXPECT_EQ("255.255.255.255/32", IpRange(before_truncate, 33).ToString()); } TEST(IpRangeTest, TruncateWorksIPv6) { QuicIpAddress before_truncate; before_truncate.FromString("ffff:ffff:ffff:ffff:f903::5"); EXPECT_EQ("fe00::/7", IpRange(before_truncate, 7).ToString()); EXPECT_EQ("ffff:ffff:ffff::/48", IpRange(before_truncate, 48).ToString()); EXPECT_EQ("ffff:ffff:ffff:ffff::/64", IpRange(before_truncate, 64).ToString()); EXPECT_EQ("ffff:ffff:ffff:ffff:8000::/65", IpRange(before_truncate, 65).ToString()); EXPECT_EQ("ffff:ffff:ffff:ffff:f903::4/127", IpRange(before_truncate, 127).ToString()); } TEST(IpRangeTest, FromStringWorksIPv4) { IpRange range; ASSERT_TRUE(range.FromString("127.0.3.249/26")); EXPECT_EQ("127.0.3.192/26", range.ToString()); } TEST(IpRangeTest, FromStringWorksIPv6) { IpRange range; ASSERT_TRUE(range.FromString("ff01:8f21:77f9::/33")); EXPECT_EQ("ff01:8f21::/33", range.ToString()); } TEST(IpRangeTest, FirstAddressWorksIPv6) { IpRange range; ASSERT_TRUE(range.FromString("ffff:ffff::/64")); QuicIpAddress first_address = range.FirstAddressInRange(); EXPECT_EQ("ffff:ffff::", first_address.ToString()); } TEST(IpRangeTest, FirstAddressWorksIPv4) { IpRange range; ASSERT_TRUE(range.FromString("10.0.0.0/24")); QuicIpAddress first_address = range.FirstAddressInRange(); EXPECT_EQ("10.0.0.0", first_address.ToString()); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/qbone/platform/ip_range.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/qbone/platform/ip_range_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
697a8798-7316-4295-bbdc-6fdc12ed21b4
cpp
google/quiche
tcp_packet
quiche/quic/qbone/platform/tcp_packet.cc
quiche/quic/qbone/platform/tcp_packet_test.cc
#include "quiche/quic/qbone/platform/tcp_packet.h" #include <netinet/ip6.h> #include "absl/base/optimization.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/internet_checksum.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/common/quiche_callbacks.h" #include "quiche/common/quiche_endian.h" namespace quic { namespace { constexpr size_t kIPv6AddressSize = sizeof(in6_addr); constexpr size_t kTcpTtl = 64; struct TCPv6Packet { ip6_hdr ip_header; tcphdr tcp_header; }; struct TCPv6PseudoHeader { uint32_t payload_size{}; uint8_t zeros[3] = {0, 0, 0}; uint8_t next_header = IPPROTO_TCP; }; } void CreateTcpResetPacket( absl::string_view original_packet, quiche::UnretainedCallback<void(absl::string_view)> cb) { if (ABSL_PREDICT_FALSE(original_packet.size() < sizeof(ip6_hdr))) { return; } auto* ip6_header = reinterpret_cast<const ip6_hdr*>(original_packet.data()); if (ABSL_PREDICT_FALSE(ip6_header->ip6_vfc >> 4 != 6)) { return; } if (ABSL_PREDICT_FALSE(ip6_header->ip6_nxt != IPPROTO_TCP)) { return; } if (ABSL_PREDICT_FALSE(quiche::QuicheEndian::NetToHost16( ip6_header->ip6_plen) < sizeof(tcphdr))) { return; } auto* tcp_header = reinterpret_cast<const tcphdr*>(ip6_header + 1); TCPv6Packet tcp_packet{}; const size_t payload_size = sizeof(tcphdr); tcp_packet.ip_header.ip6_vfc = 0x6 << 4; tcp_packet.ip_header.ip6_plen = quiche::QuicheEndian::HostToNet16(payload_size); tcp_packet.ip_header.ip6_nxt = IPPROTO_TCP; tcp_packet.ip_header.ip6_hops = kTcpTtl; tcp_packet.ip_header.ip6_src = ip6_header->ip6_dst; tcp_packet.ip_header.ip6_dst = ip6_header->ip6_src; tcp_packet.tcp_header.dest = tcp_header->source; tcp_packet.tcp_header.source = tcp_header->dest; tcp_packet.tcp_header.doff = sizeof(tcphdr) >> 2; tcp_packet.tcp_header.check = 0; tcp_packet.tcp_header.rst = 1; if (tcp_header->ack) { tcp_packet.tcp_header.seq = tcp_header->ack_seq; } else { tcp_packet.tcp_header.ack = 1; tcp_packet.tcp_header.seq = 0; tcp_packet.tcp_header.ack_seq = quiche::QuicheEndian::HostToNet32( quiche::QuicheEndian::NetToHost32(tcp_header->seq) + 1); } TCPv6PseudoHeader pseudo_header{}; pseudo_header.payload_size = quiche::QuicheEndian::HostToNet32(payload_size); InternetChecksum checksum; checksum.Update(tcp_packet.ip_header.ip6_src.s6_addr, kIPv6AddressSize); checksum.Update(tcp_packet.ip_header.ip6_dst.s6_addr, kIPv6AddressSize); checksum.Update(reinterpret_cast<char*>(&pseudo_header), sizeof(pseudo_header)); checksum.Update(reinterpret_cast<const char*>(&tcp_packet.tcp_header), sizeof(tcp_packet.tcp_header)); tcp_packet.tcp_header.check = checksum.Value(); const char* packet = reinterpret_cast<char*>(&tcp_packet); cb(absl::string_view(packet, sizeof(tcp_packet))); } }
#include "quiche/quic/qbone/platform/tcp_packet.h" #include <netinet/ip6.h> #include <cstdint> #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/common/quiche_text_utils.h" namespace quic { namespace { constexpr uint8_t kReferenceTCPSYNPacket[] = { 0x60, 0x00, 0x00, 0x00, 0x00, 0x28, 0x06, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xac, 0x1e, 0x27, 0x0f, 0x4b, 0x01, 0xe8, 0x99, 0x00, 0x00, 0x00, 0x00, 0xa0, 0x02, 0xaa, 0xaa, 0x2e, 0x21, 0x00, 0x00, 0x02, 0x04, 0xff, 0xc4, 0x04, 0x02, 0x08, 0x0a, 0x1b, 0xb8, 0x52, 0xa1, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x03, 0x07, }; constexpr uint8_t kReferenceTCPRSTPacket[] = { 0x60, 0x00, 0x00, 0x00, 0x00, 0x14, 0x06, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x27, 0x0f, 0xac, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x4b, 0x01, 0xe8, 0x9a, 0x50, 0x14, 0x00, 0x00, 0xa9, 0x05, 0x00, 0x00, }; } TEST(TcpPacketTest, CreatedPacketMatchesReference) { absl::string_view syn = absl::string_view(reinterpret_cast<const char*>(kReferenceTCPSYNPacket), sizeof(kReferenceTCPSYNPacket)); absl::string_view expected_packet = absl::string_view(reinterpret_cast<const char*>(kReferenceTCPRSTPacket), sizeof(kReferenceTCPRSTPacket)); CreateTcpResetPacket(syn, [&expected_packet](absl::string_view packet) { QUIC_LOG(INFO) << quiche::QuicheTextUtils::HexDump(packet); ASSERT_EQ(packet, expected_packet); }); } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/qbone/platform/tcp_packet.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/qbone/platform/tcp_packet_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
25afc2a3-e05e-42ff-b5d4-ef54610a8c83
cpp
google/quiche
rtnetlink_message
quiche/quic/qbone/platform/rtnetlink_message.cc
quiche/quic/qbone/platform/rtnetlink_message_test.cc
#include "quiche/quic/qbone/platform/rtnetlink_message.h" #include <memory> #include <utility> namespace quic { RtnetlinkMessage::RtnetlinkMessage(uint16_t type, uint16_t flags, uint32_t seq, uint32_t pid, const void* payload_header, size_t payload_header_length) { auto* buf = new uint8_t[NLMSG_SPACE(payload_header_length)]; memset(buf, 0, NLMSG_SPACE(payload_header_length)); auto* message_header = reinterpret_cast<struct nlmsghdr*>(buf); message_header->nlmsg_len = NLMSG_LENGTH(payload_header_length); message_header->nlmsg_type = type; message_header->nlmsg_flags = flags; message_header->nlmsg_seq = seq; message_header->nlmsg_pid = pid; if (payload_header != nullptr) { memcpy(NLMSG_DATA(message_header), payload_header, payload_header_length); } message_.push_back({buf, NLMSG_SPACE(payload_header_length)}); } RtnetlinkMessage::~RtnetlinkMessage() { for (const auto& iov : message_) { delete[] reinterpret_cast<uint8_t*>(iov.iov_base); } } void RtnetlinkMessage::AppendAttribute(uint16_t type, const void* data, uint16_t data_length) { auto* buf = new uint8_t[RTA_SPACE(data_length)]; memset(buf, 0, RTA_SPACE(data_length)); auto* rta = reinterpret_cast<struct rtattr*>(buf); static_assert(sizeof(uint16_t) == sizeof(rta->rta_len), "struct rtattr uses unsigned short, it's no longer 16bits"); static_assert(sizeof(uint16_t) == sizeof(rta->rta_type), "struct rtattr uses unsigned short, it's no longer 16bits"); rta->rta_len = RTA_LENGTH(data_length); rta->rta_type = type; memcpy(RTA_DATA(rta), data, data_length); message_.push_back({buf, RTA_SPACE(data_length)}); AdjustMessageLength(rta->rta_len); } std::unique_ptr<struct iovec[]> RtnetlinkMessage::BuildIoVec() const { auto message = std::make_unique<struct iovec[]>(message_.size()); int idx = 0; for (const auto& vec : message_) { message[idx++] = vec; } return message; } size_t RtnetlinkMessage::IoVecSize() const { return message_.size(); } void RtnetlinkMessage::AdjustMessageLength(size_t additional_data_length) { MessageHeader()->nlmsg_len = NLMSG_ALIGN(MessageHeader()->nlmsg_len) + additional_data_length; } struct nlmsghdr* RtnetlinkMessage::MessageHeader() { return reinterpret_cast<struct nlmsghdr*>(message_[0].iov_base); } LinkMessage LinkMessage::New(RtnetlinkMessage::Operation request_operation, uint16_t flags, uint32_t seq, uint32_t pid, const struct ifinfomsg* interface_info_header) { uint16_t request_type; switch (request_operation) { case RtnetlinkMessage::Operation::NEW: request_type = RTM_NEWLINK; break; case RtnetlinkMessage::Operation::DEL: request_type = RTM_DELLINK; break; case RtnetlinkMessage::Operation::GET: request_type = RTM_GETLINK; break; } bool is_get = request_type == RTM_GETLINK; if (is_get) { struct rtgenmsg g = {AF_UNSPEC}; return LinkMessage(request_type, flags, seq, pid, &g, sizeof(g)); } return LinkMessage(request_type, flags, seq, pid, interface_info_header, sizeof(struct ifinfomsg)); } AddressMessage AddressMessage::New( RtnetlinkMessage::Operation request_operation, uint16_t flags, uint32_t seq, uint32_t pid, const struct ifaddrmsg* interface_address_header) { uint16_t request_type; switch (request_operation) { case RtnetlinkMessage::Operation::NEW: request_type = RTM_NEWADDR; break; case RtnetlinkMessage::Operation::DEL: request_type = RTM_DELADDR; break; case RtnetlinkMessage::Operation::GET: request_type = RTM_GETADDR; break; } bool is_get = request_type == RTM_GETADDR; if (is_get) { struct rtgenmsg g = {AF_UNSPEC}; return AddressMessage(request_type, flags, seq, pid, &g, sizeof(g)); } return AddressMessage(request_type, flags, seq, pid, interface_address_header, sizeof(struct ifaddrmsg)); } RouteMessage RouteMessage::New(RtnetlinkMessage::Operation request_operation, uint16_t flags, uint32_t seq, uint32_t pid, const struct rtmsg* route_message_header) { uint16_t request_type; switch (request_operation) { case RtnetlinkMessage::Operation::NEW: request_type = RTM_NEWROUTE; break; case RtnetlinkMessage::Operation::DEL: request_type = RTM_DELROUTE; break; case RtnetlinkMessage::Operation::GET: request_type = RTM_GETROUTE; break; } return RouteMessage(request_type, flags, seq, pid, route_message_header, sizeof(struct rtmsg)); } RuleMessage RuleMessage::New(RtnetlinkMessage::Operation request_operation, uint16_t flags, uint32_t seq, uint32_t pid, const struct rtmsg* rule_message_header) { uint16_t request_type; switch (request_operation) { case RtnetlinkMessage::Operation::NEW: request_type = RTM_NEWRULE; break; case RtnetlinkMessage::Operation::DEL: request_type = RTM_DELRULE; break; case RtnetlinkMessage::Operation::GET: request_type = RTM_GETRULE; break; } return RuleMessage(request_type, flags, seq, pid, rule_message_header, sizeof(rtmsg)); } }
#include "quiche/quic/qbone/platform/rtnetlink_message.h" #include <net/if_arp.h> #include <string> #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace { using ::testing::StrEq; TEST(RtnetlinkMessageTest, LinkMessageCanBeCreatedForGetOperation) { uint16_t flags = NLM_F_REQUEST | NLM_F_ROOT | NLM_F_MATCH; uint32_t seq = 42; uint32_t pid = 7; auto message = LinkMessage::New(RtnetlinkMessage::Operation::GET, flags, seq, pid, nullptr); EXPECT_EQ(1, message.IoVecSize()); auto iov = message.BuildIoVec(); EXPECT_EQ(NLMSG_SPACE(sizeof(struct rtgenmsg)), iov[0].iov_len); auto* netlink_message = reinterpret_cast<struct nlmsghdr*>(iov[0].iov_base); EXPECT_EQ(NLMSG_LENGTH(sizeof(struct rtgenmsg)), netlink_message->nlmsg_len); EXPECT_EQ(RTM_GETLINK, netlink_message->nlmsg_type); EXPECT_EQ(flags, netlink_message->nlmsg_flags); EXPECT_EQ(seq, netlink_message->nlmsg_seq); EXPECT_EQ(pid, netlink_message->nlmsg_pid); EXPECT_EQ(NLMSG_LENGTH(sizeof(struct rtgenmsg)), netlink_message->nlmsg_len); } TEST(RtnetlinkMessageTest, LinkMessageCanBeCreatedForNewOperation) { struct ifinfomsg interface_info_header = {AF_INET, 0, ARPHRD_TUNNEL, 3, 0, 0xffffffff}; uint16_t flags = NLM_F_REQUEST | NLM_F_ROOT | NLM_F_MATCH; uint32_t seq = 42; uint32_t pid = 7; auto message = LinkMessage::New(RtnetlinkMessage::Operation::NEW, flags, seq, pid, &interface_info_header); std::string device_name = "device0"; message.AppendAttribute(IFLA_IFNAME, device_name.c_str(), device_name.size()); EXPECT_EQ(2, message.IoVecSize()); auto iov = message.BuildIoVec(); EXPECT_EQ(NLMSG_ALIGN(NLMSG_LENGTH(sizeof(struct ifinfomsg))), iov[0].iov_len); auto* netlink_message = reinterpret_cast<struct nlmsghdr*>(iov[0].iov_base); EXPECT_EQ(NLMSG_ALIGN(NLMSG_LENGTH(sizeof(struct ifinfomsg))) + RTA_LENGTH(device_name.size()), netlink_message->nlmsg_len); EXPECT_EQ(RTM_NEWLINK, netlink_message->nlmsg_type); EXPECT_EQ(flags, netlink_message->nlmsg_flags); EXPECT_EQ(seq, netlink_message->nlmsg_seq); EXPECT_EQ(pid, netlink_message->nlmsg_pid); auto* parsed_header = reinterpret_cast<struct ifinfomsg*>(NLMSG_DATA(netlink_message)); EXPECT_EQ(interface_info_header.ifi_family, parsed_header->ifi_family); EXPECT_EQ(interface_info_header.ifi_type, parsed_header->ifi_type); EXPECT_EQ(interface_info_header.ifi_index, parsed_header->ifi_index); EXPECT_EQ(interface_info_header.ifi_flags, parsed_header->ifi_flags); EXPECT_EQ(interface_info_header.ifi_change, parsed_header->ifi_change); EXPECT_EQ(RTA_SPACE(device_name.size()), iov[1].iov_len); auto* rta = reinterpret_cast<struct rtattr*>(iov[1].iov_base); EXPECT_EQ(IFLA_IFNAME, rta->rta_type); EXPECT_EQ(RTA_LENGTH(device_name.size()), rta->rta_len); EXPECT_THAT(device_name, StrEq(std::string(reinterpret_cast<char*>(RTA_DATA(rta)), RTA_PAYLOAD(rta)))); } TEST(RtnetlinkMessageTest, AddressMessageCanBeCreatedForGetOperation) { uint16_t flags = NLM_F_REQUEST | NLM_F_ROOT | NLM_F_MATCH; uint32_t seq = 42; uint32_t pid = 7; auto message = AddressMessage::New(RtnetlinkMessage::Operation::GET, flags, seq, pid, nullptr); EXPECT_EQ(1, message.IoVecSize()); auto iov = message.BuildIoVec(); EXPECT_EQ(NLMSG_SPACE(sizeof(struct rtgenmsg)), iov[0].iov_len); auto* netlink_message = reinterpret_cast<struct nlmsghdr*>(iov[0].iov_base); EXPECT_EQ(NLMSG_LENGTH(sizeof(struct rtgenmsg)), netlink_message->nlmsg_len); EXPECT_EQ(RTM_GETADDR, netlink_message->nlmsg_type); EXPECT_EQ(flags, netlink_message->nlmsg_flags); EXPECT_EQ(seq, netlink_message->nlmsg_seq); EXPECT_EQ(pid, netlink_message->nlmsg_pid); EXPECT_EQ(NLMSG_LENGTH(sizeof(struct rtgenmsg)), netlink_message->nlmsg_len); } TEST(RtnetlinkMessageTest, AddressMessageCanBeCreatedForNewOperation) { struct ifaddrmsg interface_address_header = {AF_INET, 24, 0, RT_SCOPE_LINK, 4}; uint16_t flags = NLM_F_REQUEST | NLM_F_ROOT | NLM_F_MATCH; uint32_t seq = 42; uint32_t pid = 7; auto message = AddressMessage::New(RtnetlinkMessage::Operation::NEW, flags, seq, pid, &interface_address_header); QuicIpAddress ip; QUICHE_CHECK(ip.FromString("10.0.100.3")); message.AppendAttribute(IFA_ADDRESS, ip.ToPackedString().c_str(), ip.ToPackedString().size()); EXPECT_EQ(2, message.IoVecSize()); auto iov = message.BuildIoVec(); EXPECT_EQ(NLMSG_ALIGN(NLMSG_LENGTH(sizeof(struct ifaddrmsg))), iov[0].iov_len); auto* netlink_message = reinterpret_cast<struct nlmsghdr*>(iov[0].iov_base); EXPECT_EQ(NLMSG_ALIGN(NLMSG_LENGTH(sizeof(struct ifaddrmsg))) + RTA_LENGTH(ip.ToPackedString().size()), netlink_message->nlmsg_len); EXPECT_EQ(RTM_NEWADDR, netlink_message->nlmsg_type); EXPECT_EQ(flags, netlink_message->nlmsg_flags); EXPECT_EQ(seq, netlink_message->nlmsg_seq); EXPECT_EQ(pid, netlink_message->nlmsg_pid); auto* parsed_header = reinterpret_cast<struct ifaddrmsg*>(NLMSG_DATA(netlink_message)); EXPECT_EQ(interface_address_header.ifa_family, parsed_header->ifa_family); EXPECT_EQ(interface_address_header.ifa_prefixlen, parsed_header->ifa_prefixlen); EXPECT_EQ(interface_address_header.ifa_flags, parsed_header->ifa_flags); EXPECT_EQ(interface_address_header.ifa_scope, parsed_header->ifa_scope); EXPECT_EQ(interface_address_header.ifa_index, parsed_header->ifa_index); EXPECT_EQ(RTA_SPACE(ip.ToPackedString().size()), iov[1].iov_len); auto* rta = reinterpret_cast<struct rtattr*>(iov[1].iov_base); EXPECT_EQ(IFA_ADDRESS, rta->rta_type); EXPECT_EQ(RTA_LENGTH(ip.ToPackedString().size()), rta->rta_len); EXPECT_THAT(ip.ToPackedString(), StrEq(std::string(reinterpret_cast<char*>(RTA_DATA(rta)), RTA_PAYLOAD(rta)))); } TEST(RtnetlinkMessageTest, RouteMessageCanBeCreatedFromNewOperation) { struct rtmsg route_message_header = {AF_INET6, 48, 0, 0, RT_TABLE_MAIN, RTPROT_STATIC, RT_SCOPE_LINK, RTN_LOCAL, 0}; uint16_t flags = NLM_F_REQUEST | NLM_F_ROOT | NLM_F_MATCH; uint32_t seq = 42; uint32_t pid = 7; auto message = RouteMessage::New(RtnetlinkMessage::Operation::NEW, flags, seq, pid, &route_message_header); QuicIpAddress preferred_source; QUICHE_CHECK(preferred_source.FromString("ff80::1")); message.AppendAttribute(RTA_PREFSRC, preferred_source.ToPackedString().c_str(), preferred_source.ToPackedString().size()); EXPECT_EQ(2, message.IoVecSize()); auto iov = message.BuildIoVec(); EXPECT_EQ(NLMSG_ALIGN(NLMSG_LENGTH(sizeof(struct rtmsg))), iov[0].iov_len); auto* netlink_message = reinterpret_cast<struct nlmsghdr*>(iov[0].iov_base); EXPECT_EQ(NLMSG_ALIGN(NLMSG_LENGTH(sizeof(struct rtmsg))) + RTA_LENGTH(preferred_source.ToPackedString().size()), netlink_message->nlmsg_len); EXPECT_EQ(RTM_NEWROUTE, netlink_message->nlmsg_type); EXPECT_EQ(flags, netlink_message->nlmsg_flags); EXPECT_EQ(seq, netlink_message->nlmsg_seq); EXPECT_EQ(pid, netlink_message->nlmsg_pid); auto* parsed_header = reinterpret_cast<struct rtmsg*>(NLMSG_DATA(netlink_message)); EXPECT_EQ(route_message_header.rtm_family, parsed_header->rtm_family); EXPECT_EQ(route_message_header.rtm_dst_len, parsed_header->rtm_dst_len); EXPECT_EQ(route_message_header.rtm_src_len, parsed_header->rtm_src_len); EXPECT_EQ(route_message_header.rtm_tos, parsed_header->rtm_tos); EXPECT_EQ(route_message_header.rtm_table, parsed_header->rtm_table); EXPECT_EQ(route_message_header.rtm_protocol, parsed_header->rtm_protocol); EXPECT_EQ(route_message_header.rtm_scope, parsed_header->rtm_scope); EXPECT_EQ(route_message_header.rtm_type, parsed_header->rtm_type); EXPECT_EQ(route_message_header.rtm_flags, parsed_header->rtm_flags); EXPECT_EQ(RTA_SPACE(preferred_source.ToPackedString().size()), iov[1].iov_len); auto* rta = reinterpret_cast<struct rtattr*>(iov[1].iov_base); EXPECT_EQ(RTA_PREFSRC, rta->rta_type); EXPECT_EQ(RTA_LENGTH(preferred_source.ToPackedString().size()), rta->rta_len); EXPECT_THAT(preferred_source.ToPackedString(), StrEq(std::string(reinterpret_cast<char*>(RTA_DATA(rta)), RTA_PAYLOAD(rta)))); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/qbone/platform/rtnetlink_message.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/qbone/platform/rtnetlink_message_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
053b8ccf-9c89-4d6d-8a38-c5c1b6fa7759
cpp
google/quiche
netlink
quiche/quic/qbone/platform/netlink.cc
quiche/quic/qbone/platform/netlink_test.cc
#include "quiche/quic/qbone/platform/netlink.h" #include <linux/fib_rules.h> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/base/attributes.h" #include "absl/strings/str_cat.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/qbone/platform/rtnetlink_message.h" #include "quiche/quic/qbone/qbone_constants.h" namespace quic { Netlink::Netlink(KernelInterface* kernel) : kernel_(kernel) { seq_ = QuicRandom::GetInstance()->RandUint64(); } Netlink::~Netlink() { CloseSocket(); } void Netlink::ResetRecvBuf(size_t size) { if (size != 0) { recvbuf_ = std::make_unique<char[]>(size); } else { recvbuf_ = nullptr; } recvbuf_length_ = size; } bool Netlink::OpenSocket() { if (socket_fd_ >= 0) { return true; } socket_fd_ = kernel_->socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (socket_fd_ < 0) { QUIC_PLOG(ERROR) << "can't open netlink socket"; return false; } QUIC_LOG(INFO) << "Opened a new netlink socket fd = " << socket_fd_; sockaddr_nl myaddr; memset(&myaddr, 0, sizeof(myaddr)); myaddr.nl_family = AF_NETLINK; if (kernel_->bind(socket_fd_, reinterpret_cast<struct sockaddr*>(&myaddr), sizeof(myaddr)) < 0) { QUIC_LOG(INFO) << "can't bind address to socket"; CloseSocket(); return false; } return true; } void Netlink::CloseSocket() { if (socket_fd_ >= 0) { QUIC_LOG(INFO) << "Closing netlink socket fd = " << socket_fd_; kernel_->close(socket_fd_); } ResetRecvBuf(0); socket_fd_ = -1; } namespace { class LinkInfoParser : public NetlinkParserInterface { public: LinkInfoParser(std::string interface_name, Netlink::LinkInfo* link_info) : interface_name_(std::move(interface_name)), link_info_(link_info) {} void Run(struct nlmsghdr* netlink_message) override { if (netlink_message->nlmsg_type != RTM_NEWLINK) { QUIC_LOG(INFO) << absl::StrCat( "Unexpected nlmsg_type: ", netlink_message->nlmsg_type, " expected: ", RTM_NEWLINK); return; } struct ifinfomsg* interface_info = reinterpret_cast<struct ifinfomsg*>(NLMSG_DATA(netlink_message)); if (interface_info->ifi_family != AF_UNSPEC) { QUIC_LOG(INFO) << absl::StrCat( "Unexpected ifi_family: ", interface_info->ifi_family, " expected: ", AF_UNSPEC); return; } char hardware_address[kHwAddrSize]; size_t hardware_address_length = 0; char broadcast_address[kHwAddrSize]; size_t broadcast_address_length = 0; std::string name; struct rtattr* rta; int payload_length = IFLA_PAYLOAD(netlink_message); for (rta = IFLA_RTA(interface_info); RTA_OK(rta, payload_length); rta = RTA_NEXT(rta, payload_length)) { int attribute_length; switch (rta->rta_type) { case IFLA_ADDRESS: { attribute_length = RTA_PAYLOAD(rta); if (attribute_length > kHwAddrSize) { QUIC_VLOG(2) << "IFLA_ADDRESS too long: " << attribute_length; break; } memmove(hardware_address, RTA_DATA(rta), attribute_length); hardware_address_length = attribute_length; break; } case IFLA_BROADCAST: { attribute_length = RTA_PAYLOAD(rta); if (attribute_length > kHwAddrSize) { QUIC_VLOG(2) << "IFLA_BROADCAST too long: " << attribute_length; break; } memmove(broadcast_address, RTA_DATA(rta), attribute_length); broadcast_address_length = attribute_length; break; } case IFLA_IFNAME: { name = std::string(reinterpret_cast<char*>(RTA_DATA(rta)), RTA_PAYLOAD(rta)); name = name.substr(0, name.find('\0')); break; } } } QUIC_VLOG(2) << "interface name: " << name << ", index: " << interface_info->ifi_index; if (name == interface_name_) { link_info_->index = interface_info->ifi_index; link_info_->type = interface_info->ifi_type; link_info_->hardware_address_length = hardware_address_length; if (hardware_address_length > 0) { memmove(&link_info_->hardware_address, hardware_address, hardware_address_length); } link_info_->broadcast_address_length = broadcast_address_length; if (broadcast_address_length > 0) { memmove(&link_info_->broadcast_address, broadcast_address, broadcast_address_length); } found_link_ = true; } } bool found_link() { return found_link_; } private: const std::string interface_name_; Netlink::LinkInfo* const link_info_; bool found_link_ = false; }; } bool Netlink::GetLinkInfo(const std::string& interface_name, LinkInfo* link_info) { auto message = LinkMessage::New(RtnetlinkMessage::Operation::GET, NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST, seq_, getpid(), nullptr); if (!Send(message.BuildIoVec().get(), message.IoVecSize())) { QUIC_LOG(ERROR) << "send failed."; return false; } LinkInfoParser parser(interface_name, link_info); if (!Recv(seq_++, &parser)) { QUIC_LOG(ERROR) << "recv failed."; return false; } return parser.found_link(); } namespace { class LocalAddressParser : public NetlinkParserInterface { public: LocalAddressParser(int interface_index, uint8_t unwanted_flags, std::vector<Netlink::AddressInfo>* local_addresses, int* num_ipv6_nodad_dadfailed_addresses) : interface_index_(interface_index), unwanted_flags_(unwanted_flags), local_addresses_(local_addresses), num_ipv6_nodad_dadfailed_addresses_( num_ipv6_nodad_dadfailed_addresses) {} void Run(struct nlmsghdr* netlink_message) override { if (netlink_message->nlmsg_type != RTM_NEWADDR) { QUIC_LOG(INFO) << "Unexpected nlmsg_type: " << netlink_message->nlmsg_type << " expected: " << RTM_NEWADDR; return; } struct ifaddrmsg* interface_address = reinterpret_cast<struct ifaddrmsg*>(NLMSG_DATA(netlink_message)); if (interface_address->ifa_family != AF_INET && interface_address->ifa_family != AF_INET6) { QUIC_VLOG(2) << absl::StrCat("uninteresting ifa family: ", interface_address->ifa_family); return; } if (num_ipv6_nodad_dadfailed_addresses_ != nullptr && (interface_address->ifa_flags & IFA_F_NODAD) && (interface_address->ifa_flags & IFA_F_DADFAILED)) { ++(*num_ipv6_nodad_dadfailed_addresses_); } uint8_t unwanted_flags = interface_address->ifa_flags & unwanted_flags_; if (unwanted_flags != 0) { QUIC_VLOG(2) << absl::StrCat("unwanted ifa flags: ", unwanted_flags); return; } struct rtattr* rta; int payload_length = IFA_PAYLOAD(netlink_message); Netlink::AddressInfo address_info; for (rta = IFA_RTA(interface_address); RTA_OK(rta, payload_length); rta = RTA_NEXT(rta, payload_length)) { if (rta->rta_type != IFA_LOCAL && rta->rta_type != IFA_ADDRESS) { QUIC_VLOG(2) << "Ignoring uninteresting rta_type: " << rta->rta_type; continue; } switch (interface_address->ifa_family) { case AF_INET: ABSL_FALLTHROUGH_INTENDED; case AF_INET6: if (RTA_PAYLOAD(rta) == sizeof(struct in_addr) || RTA_PAYLOAD(rta) == sizeof(struct in6_addr)) { auto* raw_ip = reinterpret_cast<char*>(RTA_DATA(rta)); if (rta->rta_type == IFA_LOCAL) { address_info.local_address.FromPackedString(raw_ip, RTA_PAYLOAD(rta)); } else { address_info.interface_address.FromPackedString(raw_ip, RTA_PAYLOAD(rta)); } } break; default: QUIC_LOG(ERROR) << absl::StrCat("Unknown address family: ", interface_address->ifa_family); } } QUIC_VLOG(2) << "local_address: " << address_info.local_address.ToString() << " interface_address: " << address_info.interface_address.ToString() << " index: " << interface_address->ifa_index; if (interface_address->ifa_index != interface_index_) { return; } address_info.prefix_length = interface_address->ifa_prefixlen; address_info.scope = interface_address->ifa_scope; if (address_info.local_address.IsInitialized() || address_info.interface_address.IsInitialized()) { local_addresses_->push_back(address_info); } } private: const int interface_index_; const uint8_t unwanted_flags_; std::vector<Netlink::AddressInfo>* const local_addresses_; int* const num_ipv6_nodad_dadfailed_addresses_; }; } bool Netlink::GetAddresses(int interface_index, uint8_t unwanted_flags, std::vector<AddressInfo>* addresses, int* num_ipv6_nodad_dadfailed_addresses) { auto message = AddressMessage::New(RtnetlinkMessage::Operation::GET, NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST, seq_, getpid(), nullptr); if (!Send(message.BuildIoVec().get(), message.IoVecSize())) { QUIC_LOG(ERROR) << "send failed."; return false; } addresses->clear(); if (num_ipv6_nodad_dadfailed_addresses != nullptr) { *num_ipv6_nodad_dadfailed_addresses = 0; } LocalAddressParser parser(interface_index, unwanted_flags, addresses, num_ipv6_nodad_dadfailed_addresses); if (!Recv(seq_++, &parser)) { QUIC_LOG(ERROR) << "recv failed"; return false; } return true; } namespace { class UnknownParser : public NetlinkParserInterface { public: void Run(struct nlmsghdr* netlink_message) override { QUIC_LOG(INFO) << "nlmsg reply type: " << netlink_message->nlmsg_type; } }; } bool Netlink::ChangeLocalAddress( uint32_t interface_index, Verb verb, const QuicIpAddress& address, uint8_t prefix_length, uint8_t ifa_flags, uint8_t ifa_scope, const std::vector<struct rtattr*>& additional_attributes) { if (verb == Verb::kReplace) { return false; } auto operation = verb == Verb::kAdd ? RtnetlinkMessage::Operation::NEW : RtnetlinkMessage::Operation::DEL; uint8_t address_family; if (address.address_family() == IpAddressFamily::IP_V4) { address_family = AF_INET; } else if (address.address_family() == IpAddressFamily::IP_V6) { address_family = AF_INET6; } else { return false; } struct ifaddrmsg address_header = {address_family, prefix_length, ifa_flags, ifa_scope, interface_index}; auto message = AddressMessage::New(operation, NLM_F_REQUEST | NLM_F_ACK, seq_, getpid(), &address_header); for (const auto& attribute : additional_attributes) { if (attribute->rta_type == IFA_LOCAL) { continue; } message.AppendAttribute(attribute->rta_type, RTA_DATA(attribute), RTA_PAYLOAD(attribute)); } message.AppendAttribute(IFA_LOCAL, address.ToPackedString().c_str(), address.ToPackedString().size()); if (!Send(message.BuildIoVec().get(), message.IoVecSize())) { QUIC_LOG(ERROR) << "send failed"; return false; } UnknownParser parser; if (!Recv(seq_++, &parser)) { QUIC_LOG(ERROR) << "receive failed."; return false; } return true; } namespace { class RoutingRuleParser : public NetlinkParserInterface { public: explicit RoutingRuleParser(std::vector<Netlink::RoutingRule>* routing_rules) : routing_rules_(routing_rules) {} void Run(struct nlmsghdr* netlink_message) override { if (netlink_message->nlmsg_type != RTM_NEWROUTE) { QUIC_LOG(WARNING) << absl::StrCat( "Unexpected nlmsg_type: ", netlink_message->nlmsg_type, " expected: ", RTM_NEWROUTE); return; } auto* route = reinterpret_cast<struct rtmsg*>(NLMSG_DATA(netlink_message)); int payload_length = RTM_PAYLOAD(netlink_message); if (route->rtm_family != AF_INET && route->rtm_family != AF_INET6) { QUIC_VLOG(2) << absl::StrCat("Uninteresting family: ", route->rtm_family); return; } Netlink::RoutingRule rule; rule.scope = route->rtm_scope; rule.table = route->rtm_table; struct rtattr* rta; for (rta = RTM_RTA(route); RTA_OK(rta, payload_length); rta = RTA_NEXT(rta, payload_length)) { switch (rta->rta_type) { case RTA_TABLE: { rule.table = *reinterpret_cast<uint32_t*>(RTA_DATA(rta)); break; } case RTA_DST: { QuicIpAddress destination; destination.FromPackedString(reinterpret_cast<char*> RTA_DATA(rta), RTA_PAYLOAD(rta)); rule.destination_subnet = IpRange(destination, route->rtm_dst_len); break; } case RTA_PREFSRC: { QuicIpAddress preferred_source; rule.preferred_source.FromPackedString( reinterpret_cast<char*> RTA_DATA(rta), RTA_PAYLOAD(rta)); break; } case RTA_OIF: { rule.out_interface = *reinterpret_cast<int*>(RTA_DATA(rta)); break; } default: { QUIC_VLOG(2) << absl::StrCat("Uninteresting attribute: ", rta->rta_type); } } } routing_rules_->push_back(rule); } private: std::vector<Netlink::RoutingRule>* routing_rules_; }; } bool Netlink::GetRouteInfo(std::vector<Netlink::RoutingRule>* routing_rules) { rtmsg route_message{}; route_message.rtm_table = RT_TABLE_MAIN; auto message = RouteMessage::New(RtnetlinkMessage::Operation::GET, NLM_F_REQUEST | NLM_F_ROOT | NLM_F_MATCH, seq_, getpid(), &route_message); if (!Send(message.BuildIoVec().get(), message.IoVecSize())) { QUIC_LOG(ERROR) << "send failed"; return false; } RoutingRuleParser parser(routing_rules); if (!Recv(seq_++, &parser)) { QUIC_LOG(ERROR) << "recv failed"; return false; } return true; } bool Netlink::ChangeRoute(Netlink::Verb verb, uint32_t table, const IpRange& destination_subnet, uint8_t scope, QuicIpAddress preferred_source, int32_t interface_index) { if (!destination_subnet.prefix().IsInitialized()) { return false; } if (destination_subnet.address_family() != IpAddressFamily::IP_V4 && destination_subnet.address_family() != IpAddressFamily::IP_V6) { return false; } if (preferred_source.IsInitialized() && preferred_source.address_family() != destination_subnet.address_family()) { return false; } RtnetlinkMessage::Operation operation; uint16_t flags = NLM_F_REQUEST | NLM_F_ACK; switch (verb) { case Verb::kAdd: operation = RtnetlinkMessage::Operation::NEW; flags |= NLM_F_EXCL | NLM_F_CREATE; break; case Verb::kRemove: operation = RtnetlinkMessage::Operation::DEL; break; case Verb::kReplace: operation = RtnetlinkMessage::Operation::NEW; flags |= NLM_F_REPLACE | NLM_F_CREATE; break; } struct rtmsg route_message; memset(&route_message, 0, sizeof(route_message)); route_message.rtm_family = destination_subnet.address_family() == IpAddressFamily::IP_V4 ? AF_INET : AF_INET6; route_message.rtm_dst_len = destination_subnet.prefix_length(); route_message.rtm_src_len = 0; route_message.rtm_table = RT_TABLE_MAIN; route_message.rtm_protocol = verb == Verb::kRemove ? RTPROT_UNSPEC : RTPROT_STATIC; route_message.rtm_scope = scope; route_message.rtm_type = RTN_UNICAST; auto message = RouteMessage::New(operation, flags, seq_, getpid(), &route_message); message.AppendAttribute(RTA_TABLE, &table, sizeof(table)); message.AppendAttribute(RTA_OIF, &interface_index, sizeof(interface_index)); message.AppendAttribute( RTA_DST, reinterpret_cast<const void*>( destination_subnet.prefix().ToPackedString().c_str()), destination_subnet.prefix().ToPackedString().size()); if (preferred_source.IsInitialized()) { auto src_str = preferred_source.ToPackedString(); message.AppendAttribute(RTA_PREFSRC, reinterpret_cast<const void*>(src_str.c_str()), src_str.size()); } if (verb != Verb::kRemove) { auto gateway_str = QboneConstants::GatewayAddress()->ToPackedString(); message.AppendAttribute(RTA_GATEWAY, reinterpret_cast<const void*>(gateway_str.c_str()), gateway_str.size()); } if (!Send(message.BuildIoVec().get(), message.IoVecSize())) { QUIC_LOG(ERROR) << "send failed"; return false; } UnknownParser parser; if (!Recv(seq_++, &parser)) { QUIC_LOG(ERROR) << "receive failed."; return false; } return true; } namespace { class IpRuleParser : public NetlinkParserInterface { public: explicit IpRuleParser(std::vector<Netlink::IpRule>* ip_rules) : ip_rules_(ip_rules) {} void Run(struct nlmsghdr* netlink_message) override { if (netlink_message->nlmsg_type != RTM_NEWRULE) { QUIC_LOG(WARNING) << absl::StrCat( "Unexpected nlmsg_type: ", netlink_message->nlmsg_type, " expected: ", RTM_NEWRULE); return; } auto* rule = reinterpret_cast<rtmsg*>(NLMSG_DATA(netlink_message)); int payload_length = RTM_PAYLOAD(netlink_message); if (rule->rtm_family != AF_INET6) { QUIC_LOG(ERROR) << absl::StrCat("Unexpected family: ", rule->rtm_family); return; } Netlink::IpRule ip_rule; ip_rule.table = rule->rtm_table; struct rtattr* rta; for (rta = RTM_RTA(rule); RTA_OK(rta, payload_length); rta = RTA_NEXT(rta, payload_length)) { switch (rta->rta_type) { case RTA_TABLE: { ip_rule.table = *reinterpret_cast<uint32_t*>(RTA_DATA(rta)); break; } case RTA_SRC: { QuicIpAddress src_addr; src_addr.FromPackedString(reinterpret_cast<char*>(RTA_DATA(rta)), RTA_PAYLOAD(rta)); IpRange src_range(src_addr, rule->rtm_src_len); ip_rule.source_range = src_range; break; } default: { QUIC_VLOG(2) << absl::StrCat("Uninteresting attribute: ", rta->rta_type); } } } ip_rules_->emplace_back(ip_rule); } private: std::vector<Netlink::IpRule>* ip_rules_; }; } bool Netlink::GetRuleInfo(std::vector<Netlink::IpRule>* ip_rules) { rtmsg rule_message{}; rule_message.rtm_family = AF_INET6; auto message = RuleMessage::New(RtnetlinkMessage::Operation::GET, NLM_F_REQUEST | NLM_F_DUMP, seq_, getpid(), &rule_message); if (!Send(message.BuildIoVec().get(), message.IoVecSize())) { QUIC_LOG(ERROR) << "send failed"; return false; } IpRuleParser parser(ip_rules); if (!Recv(seq_++, &parser)) { QUIC_LOG(ERROR) << "receive failed."; return false; } return true; } bool Netlink::ChangeRule(Verb verb, uint32_t table, IpRange source_range) { RtnetlinkMessage::Operation operation; uint16_t flags = NLM_F_REQUEST | NLM_F_ACK; rtmsg rule_message{}; rule_message.rtm_family = AF_INET6; rule_message.rtm_protocol = RTPROT_STATIC; rule_message.rtm_scope = RT_SCOPE_UNIVERSE; rule_message.rtm_table = RT_TABLE_UNSPEC; rule_message.rtm_flags |= FIB_RULE_FIND_SADDR; switch (verb) { case Verb::kAdd: if (!source_range.IsInitialized()) { QUIC_LOG(ERROR) << "Source range must be initialized."; return false; } operation = RtnetlinkMessage::Operation::NEW; flags |= NLM_F_EXCL | NLM_F_CREATE; rule_message.rtm_type = FRA_DST; rule_message.rtm_src_len = source_range.prefix_length(); break; case Verb::kRemove: operation = RtnetlinkMessage::Operation::DEL; break; case Verb::kReplace: QUIC_LOG(ERROR) << "Unsupported verb: kReplace"; return false; } auto message = RuleMessage::New(operation, flags, seq_, getpid(), &rule_message); message.AppendAttribute(RTA_TABLE, &table, sizeof(table)); if (source_range.IsInitialized()) { std::string packed_src = source_range.prefix().ToPackedString(); message.AppendAttribute(RTA_SRC, reinterpret_cast<const void*>(packed_src.c_str()), packed_src.size()); } if (!Send(message.BuildIoVec().get(), message.IoVecSize())) { QUIC_LOG(ERROR) << "send failed"; return false; } UnknownParser parser; if (!Recv(seq_++, &parser)) { QUIC_LOG(ERROR) << "receive failed."; return false; } return true; } bool Netlink::Send(struct iovec* iov, size_t iovlen) { if (!OpenSocket()) { QUIC_LOG(ERROR) << "can't open socket"; return false; } sockaddr_nl netlink_address; memset(&netlink_address, 0, sizeof(netlink_address)); netlink_address.nl_family = AF_NETLINK; netlink_address.nl_pid = 0; netlink_address.nl_groups = 0; struct msghdr msg = { &netlink_address, sizeof(netlink_address), iov, iovlen, nullptr, 0, 0}; if (kernel_->sendmsg(socket_fd_, &msg, 0) < 0) { QUIC_LOG(ERROR) << "sendmsg failed"; CloseSocket(); return false; } return true; } bool Netlink::Recv(uint32_t seq, NetlinkParserInterface* parser) { sockaddr_nl netlink_address; for (;;) { socklen_t address_length = sizeof(netlink_address); int next_packet_size = kernel_->recvfrom( socket_fd_, recvbuf_.get(), 0, MSG_PEEK | MSG_TRUNC, reinterpret_cast<struct sockaddr*>(&netlink_address), &address_length); if (next_packet_size < 0) { QUIC_LOG(ERROR) << "error recvfrom with MSG_PEEK | MSG_TRUNC to get packet length."; CloseSocket(); return false; } QUIC_VLOG(3) << "netlink packet size: " << next_packet_size; if (next_packet_size > recvbuf_length_) { QUIC_VLOG(2) << "resizing recvbuf to " << next_packet_size; ResetRecvBuf(next_packet_size); } memset(recvbuf_.get(), 0, recvbuf_length_); int len = kernel_->recvfrom( socket_fd_, recvbuf_.get(), recvbuf_length_, 0, reinterpret_cast<struct sockaddr*>(&netlink_address), &address_length); QUIC_VLOG(3) << "recvfrom returned: " << len; if (len < 0) { QUIC_LOG(INFO) << "can't receive netlink packet"; CloseSocket(); return false; } struct nlmsghdr* netlink_message; for (netlink_message = reinterpret_cast<struct nlmsghdr*>(recvbuf_.get()); NLMSG_OK(netlink_message, len); netlink_message = NLMSG_NEXT(netlink_message, len)) { QUIC_VLOG(3) << "netlink_message->nlmsg_type = " << netlink_message->nlmsg_type; if (netlink_message->nlmsg_seq != seq) { QUIC_LOG(INFO) << "netlink_message not meant for us." << " seq: " << seq << " nlmsg_seq: " << netlink_message->nlmsg_seq; continue; } if (netlink_message->nlmsg_type == NLMSG_DONE) { return true; } if (netlink_message->nlmsg_type == NLMSG_ERROR) { struct nlmsgerr* err = reinterpret_cast<struct nlmsgerr*>(NLMSG_DATA(netlink_message)); if (netlink_message->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) { QUIC_LOG(INFO) << "netlink_message ERROR truncated"; } else { if (err->error == 0) { QUIC_VLOG(3) << "Netlink sent an ACK"; return true; } QUIC_LOG(INFO) << "netlink_message ERROR: " << err->error; } return false; } parser->Run(netlink_message); } } } }
#include "quiche/quic/qbone/platform/netlink.h" #include <functional> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/node_hash_set.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/qbone/platform/mock_kernel.h" #include "quiche/quic/qbone/qbone_constants.h" namespace quic::test { namespace { using ::testing::_; using ::testing::Contains; using ::testing::InSequence; using ::testing::Invoke; using ::testing::Return; using ::testing::Unused; const int kSocketFd = 101; class NetlinkTest : public QuicTest { protected: NetlinkTest() { ON_CALL(mock_kernel_, socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE)) .WillByDefault(Invoke([this](Unused, Unused, Unused) { EXPECT_CALL(mock_kernel_, close(kSocketFd)).WillOnce(Return(0)); return kSocketFd; })); } void ExpectNetlinkPacket( uint16_t type, uint16_t flags, const std::function<ssize_t(void* buf, size_t len, int seq)>& recv_callback, const std::function<void(const void* buf, size_t len)>& send_callback = nullptr) { static int seq = -1; InSequence s; EXPECT_CALL(mock_kernel_, sendmsg(kSocketFd, _, _)) .WillOnce(Invoke([type, flags, send_callback]( Unused, const struct msghdr* msg, int) { EXPECT_EQ(sizeof(struct sockaddr_nl), msg->msg_namelen); auto* nl_addr = reinterpret_cast<const struct sockaddr_nl*>(msg->msg_name); EXPECT_EQ(AF_NETLINK, nl_addr->nl_family); EXPECT_EQ(0, nl_addr->nl_pid); EXPECT_EQ(0, nl_addr->nl_groups); EXPECT_GE(msg->msg_iovlen, 1); EXPECT_GE(msg->msg_iov[0].iov_len, sizeof(struct nlmsghdr)); std::string buf; for (int i = 0; i < msg->msg_iovlen; i++) { buf.append( std::string(reinterpret_cast<char*>(msg->msg_iov[i].iov_base), msg->msg_iov[i].iov_len)); } auto* netlink_message = reinterpret_cast<const struct nlmsghdr*>(buf.c_str()); EXPECT_EQ(type, netlink_message->nlmsg_type); EXPECT_EQ(flags, netlink_message->nlmsg_flags); EXPECT_GE(buf.size(), netlink_message->nlmsg_len); if (send_callback != nullptr) { send_callback(buf.c_str(), buf.size()); } QUICHE_CHECK_EQ(seq, -1); seq = netlink_message->nlmsg_seq; return buf.size(); })); EXPECT_CALL(mock_kernel_, recvfrom(kSocketFd, _, 0, MSG_PEEK | MSG_TRUNC, _, _)) .WillOnce(Invoke([this, recv_callback](Unused, Unused, Unused, Unused, struct sockaddr* src_addr, socklen_t* addrlen) { auto* nl_addr = reinterpret_cast<struct sockaddr_nl*>(src_addr); nl_addr->nl_family = AF_NETLINK; nl_addr->nl_pid = 0; nl_addr->nl_groups = 0; int ret = recv_callback(reply_packet_, sizeof(reply_packet_), seq); QUICHE_CHECK_LE(ret, sizeof(reply_packet_)); return ret; })); EXPECT_CALL(mock_kernel_, recvfrom(kSocketFd, _, _, _, _, _)) .WillOnce(Invoke([recv_callback](Unused, void* buf, size_t len, Unused, struct sockaddr* src_addr, socklen_t* addrlen) { auto* nl_addr = reinterpret_cast<struct sockaddr_nl*>(src_addr); nl_addr->nl_family = AF_NETLINK; nl_addr->nl_pid = 0; nl_addr->nl_groups = 0; int ret = recv_callback(buf, len, seq); EXPECT_GE(len, ret); seq = -1; return ret; })); } char reply_packet_[4096]; MockKernel mock_kernel_; }; void AddRTA(struct nlmsghdr* netlink_message, uint16_t type, const void* data, size_t len) { auto* next_header_ptr = reinterpret_cast<char*>(netlink_message) + NLMSG_ALIGN(netlink_message->nlmsg_len); auto* rta = reinterpret_cast<struct rtattr*>(next_header_ptr); rta->rta_type = type; rta->rta_len = RTA_LENGTH(len); memcpy(RTA_DATA(rta), data, len); netlink_message->nlmsg_len = NLMSG_ALIGN(netlink_message->nlmsg_len) + RTA_LENGTH(len); } void CreateIfinfomsg(struct nlmsghdr* netlink_message, const std::string& interface_name, uint16_t type, int index, unsigned int flags, unsigned int change, uint8_t address[], int address_len, uint8_t broadcast[], int broadcast_len) { auto* interface_info = reinterpret_cast<struct ifinfomsg*>(NLMSG_DATA(netlink_message)); interface_info->ifi_family = AF_UNSPEC; interface_info->ifi_type = type; interface_info->ifi_index = index; interface_info->ifi_flags = flags; interface_info->ifi_change = change; netlink_message->nlmsg_len = NLMSG_LENGTH(sizeof(struct ifinfomsg)); AddRTA(netlink_message, IFLA_ADDRESS, address, address_len); AddRTA(netlink_message, IFLA_BROADCAST, broadcast, broadcast_len); AddRTA(netlink_message, IFLA_IFNAME, interface_name.c_str(), interface_name.size()); } struct nlmsghdr* CreateNetlinkMessage(void* buf, struct nlmsghdr* previous_netlink_message, uint16_t type, int seq) { auto* next_header_ptr = reinterpret_cast<char*>(buf); if (previous_netlink_message != nullptr) { next_header_ptr = reinterpret_cast<char*>(previous_netlink_message) + NLMSG_ALIGN(previous_netlink_message->nlmsg_len); } auto* netlink_message = reinterpret_cast<nlmsghdr*>(next_header_ptr); netlink_message->nlmsg_len = NLMSG_LENGTH(0); netlink_message->nlmsg_type = type; netlink_message->nlmsg_flags = NLM_F_MULTI; netlink_message->nlmsg_pid = 0; netlink_message->nlmsg_seq = seq; return netlink_message; } void CreateIfaddrmsg(struct nlmsghdr* nlm, int interface_index, unsigned char prefixlen, unsigned char flags, unsigned char scope, QuicIpAddress ip) { QUICHE_CHECK(ip.IsInitialized()); unsigned char family; switch (ip.address_family()) { case IpAddressFamily::IP_V4: family = AF_INET; break; case IpAddressFamily::IP_V6: family = AF_INET6; break; default: QUIC_BUG(quic_bug_11034_1) << absl::StrCat("unexpected address family: ", ip.address_family()); family = AF_UNSPEC; } auto* msg = reinterpret_cast<struct ifaddrmsg*>(NLMSG_DATA(nlm)); msg->ifa_family = family; msg->ifa_prefixlen = prefixlen; msg->ifa_flags = flags; msg->ifa_scope = scope; msg->ifa_index = interface_index; nlm->nlmsg_len = NLMSG_LENGTH(sizeof(struct ifaddrmsg)); AddRTA(nlm, IFA_LOCAL, ip.ToPackedString().c_str(), ip.ToPackedString().size()); } void CreateRtmsg(struct nlmsghdr* nlm, unsigned char family, unsigned char destination_length, unsigned char source_length, unsigned char tos, unsigned char table, unsigned char protocol, unsigned char scope, unsigned char type, unsigned int flags, QuicIpAddress destination, int interface_index) { auto* msg = reinterpret_cast<struct rtmsg*>(NLMSG_DATA(nlm)); msg->rtm_family = family; msg->rtm_dst_len = destination_length; msg->rtm_src_len = source_length; msg->rtm_tos = tos; msg->rtm_table = table; msg->rtm_protocol = protocol; msg->rtm_scope = scope; msg->rtm_type = type; msg->rtm_flags = flags; nlm->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg)); AddRTA(nlm, RTA_DST, destination.ToPackedString().c_str(), destination.ToPackedString().size()); AddRTA(nlm, RTA_OIF, &interface_index, sizeof(interface_index)); } TEST_F(NetlinkTest, GetLinkInfoWorks) { auto netlink = std::make_unique<Netlink>(&mock_kernel_); uint8_t hwaddr[] = {'a', 'b', 'c', 'd', 'e', 'f'}; uint8_t bcaddr[] = {'c', 'b', 'a', 'f', 'e', 'd'}; ExpectNetlinkPacket( RTM_GETLINK, NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST, [&hwaddr, &bcaddr](void* buf, size_t len, int seq) { int ret = 0; struct nlmsghdr* netlink_message = CreateNetlinkMessage(buf, nullptr, RTM_NEWLINK, seq); CreateIfinfomsg(netlink_message, "tun0", 1, 7, 0, 0xFFFFFFFF, hwaddr, 6, bcaddr, 6); ret += NLMSG_ALIGN(netlink_message->nlmsg_len); netlink_message = CreateNetlinkMessage(buf, netlink_message, NLMSG_DONE, seq); ret += NLMSG_ALIGN(netlink_message->nlmsg_len); return ret; }); Netlink::LinkInfo link_info; EXPECT_TRUE(netlink->GetLinkInfo("tun0", &link_info)); EXPECT_EQ(7, link_info.index); EXPECT_EQ(1, link_info.type); for (int i = 0; i < link_info.hardware_address_length; ++i) { EXPECT_EQ(hwaddr[i], link_info.hardware_address[i]); } for (int i = 0; i < link_info.broadcast_address_length; ++i) { EXPECT_EQ(bcaddr[i], link_info.broadcast_address[i]); } } TEST_F(NetlinkTest, GetAddressesWorks) { auto netlink = std::make_unique<Netlink>(&mock_kernel_); absl::node_hash_set<std::string> addresses = { QuicIpAddress::Any4().ToString(), QuicIpAddress::Any6().ToString()}; ExpectNetlinkPacket( RTM_GETADDR, NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST, [&addresses](void* buf, size_t len, int seq) { int ret = 0; struct nlmsghdr* nlm = nullptr; for (const auto& address : addresses) { QuicIpAddress ip; ip.FromString(address); nlm = CreateNetlinkMessage(buf, nlm, RTM_NEWADDR, seq); CreateIfaddrmsg(nlm, 7, 24, 0, RT_SCOPE_UNIVERSE, ip); ret += NLMSG_ALIGN(nlm->nlmsg_len); } { QuicIpAddress ip; ip.FromString("10.0.0.1"); nlm = CreateNetlinkMessage(buf, nlm, RTM_NEWADDR, seq); CreateIfaddrmsg(nlm, 7, 16, IFA_F_OPTIMISTIC, RT_SCOPE_UNIVERSE, ip); ret += NLMSG_ALIGN(nlm->nlmsg_len); ip.FromString("10.0.0.2"); nlm = CreateNetlinkMessage(buf, nlm, RTM_NEWADDR, seq); CreateIfaddrmsg(nlm, 7, 16, IFA_F_TENTATIVE, RT_SCOPE_UNIVERSE, ip); ret += NLMSG_ALIGN(nlm->nlmsg_len); } nlm = CreateNetlinkMessage(buf, nlm, NLMSG_DONE, seq); ret += NLMSG_ALIGN(nlm->nlmsg_len); return ret; }); std::vector<Netlink::AddressInfo> reported_addresses; int num_ipv6_nodad_dadfailed_addresses = 0; EXPECT_TRUE(netlink->GetAddresses(7, IFA_F_TENTATIVE | IFA_F_OPTIMISTIC, &reported_addresses, &num_ipv6_nodad_dadfailed_addresses)); for (const auto& reported_address : reported_addresses) { EXPECT_TRUE(reported_address.local_address.IsInitialized()); EXPECT_FALSE(reported_address.interface_address.IsInitialized()); EXPECT_THAT(addresses, Contains(reported_address.local_address.ToString())); addresses.erase(reported_address.local_address.ToString()); EXPECT_EQ(24, reported_address.prefix_length); } EXPECT_TRUE(addresses.empty()); } TEST_F(NetlinkTest, ChangeLocalAddressAdd) { auto netlink = std::make_unique<Netlink>(&mock_kernel_); QuicIpAddress ip = QuicIpAddress::Any6(); ExpectNetlinkPacket( RTM_NEWADDR, NLM_F_ACK | NLM_F_REQUEST, [](void* buf, size_t len, int seq) { struct nlmsghdr* netlink_message = CreateNetlinkMessage(buf, nullptr, NLMSG_ERROR, seq); auto* err = reinterpret_cast<struct nlmsgerr*>(NLMSG_DATA(netlink_message)); err->error = 0; netlink_message->nlmsg_len = NLMSG_LENGTH(sizeof(struct nlmsgerr)); return netlink_message->nlmsg_len; }, [ip](const void* buf, size_t len) { auto* netlink_message = reinterpret_cast<const struct nlmsghdr*>(buf); auto* ifa = reinterpret_cast<const struct ifaddrmsg*>( NLMSG_DATA(netlink_message)); EXPECT_EQ(19, ifa->ifa_prefixlen); EXPECT_EQ(RT_SCOPE_UNIVERSE, ifa->ifa_scope); EXPECT_EQ(IFA_F_PERMANENT, ifa->ifa_flags); EXPECT_EQ(7, ifa->ifa_index); EXPECT_EQ(AF_INET6, ifa->ifa_family); const struct rtattr* rta; int payload_length = IFA_PAYLOAD(netlink_message); int num_rta = 0; for (rta = IFA_RTA(ifa); RTA_OK(rta, payload_length); rta = RTA_NEXT(rta, payload_length)) { switch (rta->rta_type) { case IFA_LOCAL: { EXPECT_EQ(ip.ToPackedString().size(), RTA_PAYLOAD(rta)); const auto* raw_address = reinterpret_cast<const char*>(RTA_DATA(rta)); ASSERT_EQ(sizeof(in6_addr), RTA_PAYLOAD(rta)); QuicIpAddress address; address.FromPackedString(raw_address, RTA_PAYLOAD(rta)); EXPECT_EQ(ip, address); break; } case IFA_CACHEINFO: { EXPECT_EQ(sizeof(struct ifa_cacheinfo), RTA_PAYLOAD(rta)); const auto* cache_info = reinterpret_cast<const struct ifa_cacheinfo*>(RTA_DATA(rta)); EXPECT_EQ(8, cache_info->ifa_prefered); EXPECT_EQ(6, cache_info->ifa_valid); EXPECT_EQ(4, cache_info->cstamp); EXPECT_EQ(2, cache_info->tstamp); break; } default: EXPECT_TRUE(false) << "Seeing rtattr that should not exist"; } ++num_rta; } EXPECT_EQ(2, num_rta); }); struct { struct rtattr rta; struct ifa_cacheinfo cache_info; } additional_rta; additional_rta.rta.rta_type = IFA_CACHEINFO; additional_rta.rta.rta_len = RTA_LENGTH(sizeof(struct ifa_cacheinfo)); additional_rta.cache_info.ifa_prefered = 8; additional_rta.cache_info.ifa_valid = 6; additional_rta.cache_info.cstamp = 4; additional_rta.cache_info.tstamp = 2; EXPECT_TRUE(netlink->ChangeLocalAddress(7, Netlink::Verb::kAdd, ip, 19, IFA_F_PERMANENT, RT_SCOPE_UNIVERSE, {&additional_rta.rta})); } TEST_F(NetlinkTest, ChangeLocalAddressRemove) { auto netlink = std::make_unique<Netlink>(&mock_kernel_); QuicIpAddress ip = QuicIpAddress::Any4(); ExpectNetlinkPacket( RTM_DELADDR, NLM_F_ACK | NLM_F_REQUEST, [](void* buf, size_t len, int seq) { struct nlmsghdr* netlink_message = CreateNetlinkMessage(buf, nullptr, NLMSG_ERROR, seq); auto* err = reinterpret_cast<struct nlmsgerr*>(NLMSG_DATA(netlink_message)); err->error = 0; netlink_message->nlmsg_len = NLMSG_LENGTH(sizeof(struct nlmsgerr)); return netlink_message->nlmsg_len; }, [ip](const void* buf, size_t len) { auto* netlink_message = reinterpret_cast<const struct nlmsghdr*>(buf); auto* ifa = reinterpret_cast<const struct ifaddrmsg*>( NLMSG_DATA(netlink_message)); EXPECT_EQ(32, ifa->ifa_prefixlen); EXPECT_EQ(RT_SCOPE_UNIVERSE, ifa->ifa_scope); EXPECT_EQ(0, ifa->ifa_flags); EXPECT_EQ(7, ifa->ifa_index); EXPECT_EQ(AF_INET, ifa->ifa_family); const struct rtattr* rta; int payload_length = IFA_PAYLOAD(netlink_message); int num_rta = 0; for (rta = IFA_RTA(ifa); RTA_OK(rta, payload_length); rta = RTA_NEXT(rta, payload_length)) { switch (rta->rta_type) { case IFA_LOCAL: { const auto* raw_address = reinterpret_cast<const char*>(RTA_DATA(rta)); ASSERT_EQ(sizeof(in_addr), RTA_PAYLOAD(rta)); QuicIpAddress address; address.FromPackedString(raw_address, RTA_PAYLOAD(rta)); EXPECT_EQ(ip, address); break; } default: EXPECT_TRUE(false) << "Seeing rtattr that should not exist"; } ++num_rta; } EXPECT_EQ(1, num_rta); }); EXPECT_TRUE(netlink->ChangeLocalAddress(7, Netlink::Verb::kRemove, ip, 32, 0, RT_SCOPE_UNIVERSE, {})); } TEST_F(NetlinkTest, GetRouteInfoWorks) { auto netlink = std::make_unique<Netlink>(&mock_kernel_); QuicIpAddress destination; ASSERT_TRUE(destination.FromString("f800::2")); ExpectNetlinkPacket(RTM_GETROUTE, NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST, [destination](void* buf, size_t len, int seq) { int ret = 0; struct nlmsghdr* netlink_message = CreateNetlinkMessage( buf, nullptr, RTM_NEWROUTE, seq); CreateRtmsg(netlink_message, AF_INET6, 48, 0, 0, RT_TABLE_MAIN, RTPROT_STATIC, RT_SCOPE_LINK, RTN_UNICAST, 0, destination, 7); ret += NLMSG_ALIGN(netlink_message->nlmsg_len); netlink_message = CreateNetlinkMessage( buf, netlink_message, NLMSG_DONE, seq); ret += NLMSG_ALIGN(netlink_message->nlmsg_len); QUIC_LOG(INFO) << "ret: " << ret; return ret; }); std::vector<Netlink::RoutingRule> routing_rules; EXPECT_TRUE(netlink->GetRouteInfo(&routing_rules)); ASSERT_EQ(1, routing_rules.size()); EXPECT_EQ(RT_SCOPE_LINK, routing_rules[0].scope); EXPECT_EQ(IpRange(destination, 48).ToString(), routing_rules[0].destination_subnet.ToString()); EXPECT_FALSE(routing_rules[0].preferred_source.IsInitialized()); EXPECT_EQ(7, routing_rules[0].out_interface); } TEST_F(NetlinkTest, ChangeRouteAdd) { auto netlink = std::make_unique<Netlink>(&mock_kernel_); QuicIpAddress preferred_ip; preferred_ip.FromString("ff80:dead:beef::1"); IpRange subnet; subnet.FromString("ff80:dead:beef::/48"); int egress_interface_index = 7; ExpectNetlinkPacket( RTM_NEWROUTE, NLM_F_ACK | NLM_F_REQUEST | NLM_F_CREATE | NLM_F_EXCL, [](void* buf, size_t len, int seq) { struct nlmsghdr* netlink_message = CreateNetlinkMessage(buf, nullptr, NLMSG_ERROR, seq); auto* err = reinterpret_cast<struct nlmsgerr*>(NLMSG_DATA(netlink_message)); err->error = 0; netlink_message->nlmsg_len = NLMSG_LENGTH(sizeof(struct nlmsgerr)); return netlink_message->nlmsg_len; }, [preferred_ip, subnet, egress_interface_index](const void* buf, size_t len) { auto* netlink_message = reinterpret_cast<const struct nlmsghdr*>(buf); auto* rtm = reinterpret_cast<const struct rtmsg*>(NLMSG_DATA(netlink_message)); EXPECT_EQ(AF_INET6, rtm->rtm_family); EXPECT_EQ(48, rtm->rtm_dst_len); EXPECT_EQ(0, rtm->rtm_src_len); EXPECT_EQ(RT_TABLE_MAIN, rtm->rtm_table); EXPECT_EQ(RTPROT_STATIC, rtm->rtm_protocol); EXPECT_EQ(RT_SCOPE_LINK, rtm->rtm_scope); EXPECT_EQ(RTN_UNICAST, rtm->rtm_type); const struct rtattr* rta; int payload_length = RTM_PAYLOAD(netlink_message); int num_rta = 0; for (rta = RTM_RTA(rtm); RTA_OK(rta, payload_length); rta = RTA_NEXT(rta, payload_length)) { switch (rta->rta_type) { case RTA_PREFSRC: { const auto* raw_address = reinterpret_cast<const char*>(RTA_DATA(rta)); ASSERT_EQ(sizeof(struct in6_addr), RTA_PAYLOAD(rta)); QuicIpAddress address; address.FromPackedString(raw_address, RTA_PAYLOAD(rta)); EXPECT_EQ(preferred_ip, address); break; } case RTA_GATEWAY: { const auto* raw_address = reinterpret_cast<const char*>(RTA_DATA(rta)); ASSERT_EQ(sizeof(struct in6_addr), RTA_PAYLOAD(rta)); QuicIpAddress address; address.FromPackedString(raw_address, RTA_PAYLOAD(rta)); EXPECT_EQ(*QboneConstants::GatewayAddress(), address); break; } case RTA_OIF: { ASSERT_EQ(sizeof(int), RTA_PAYLOAD(rta)); const auto* interface_index = reinterpret_cast<const int*>(RTA_DATA(rta)); EXPECT_EQ(egress_interface_index, *interface_index); break; } case RTA_DST: { const auto* raw_address = reinterpret_cast<const char*>(RTA_DATA(rta)); ASSERT_EQ(sizeof(struct in6_addr), RTA_PAYLOAD(rta)); QuicIpAddress address; address.FromPackedString(raw_address, RTA_PAYLOAD(rta)); EXPECT_EQ(subnet.ToString(), IpRange(address, rtm->rtm_dst_len).ToString()); break; } case RTA_TABLE: { ASSERT_EQ(*reinterpret_cast<uint32_t*>(RTA_DATA(rta)), QboneConstants::kQboneRouteTableId); break; } default: EXPECT_TRUE(false) << "Seeing rtattr that should not be sent"; } ++num_rta; } EXPECT_EQ(5, num_rta); }); EXPECT_TRUE(netlink->ChangeRoute( Netlink::Verb::kAdd, QboneConstants::kQboneRouteTableId, subnet, RT_SCOPE_LINK, preferred_ip, egress_interface_index)); } TEST_F(NetlinkTest, ChangeRouteRemove) { auto netlink = std::make_unique<Netlink>(&mock_kernel_); QuicIpAddress preferred_ip; preferred_ip.FromString("ff80:dead:beef::1"); IpRange subnet; subnet.FromString("ff80:dead:beef::/48"); int egress_interface_index = 7; ExpectNetlinkPacket( RTM_DELROUTE, NLM_F_ACK | NLM_F_REQUEST, [](void* buf, size_t len, int seq) { struct nlmsghdr* netlink_message = CreateNetlinkMessage(buf, nullptr, NLMSG_ERROR, seq); auto* err = reinterpret_cast<struct nlmsgerr*>(NLMSG_DATA(netlink_message)); err->error = 0; netlink_message->nlmsg_len = NLMSG_LENGTH(sizeof(struct nlmsgerr)); return netlink_message->nlmsg_len; }, [preferred_ip, subnet, egress_interface_index](const void* buf, size_t len) { auto* netlink_message = reinterpret_cast<const struct nlmsghdr*>(buf); auto* rtm = reinterpret_cast<const struct rtmsg*>(NLMSG_DATA(netlink_message)); EXPECT_EQ(AF_INET6, rtm->rtm_family); EXPECT_EQ(48, rtm->rtm_dst_len); EXPECT_EQ(0, rtm->rtm_src_len); EXPECT_EQ(RT_TABLE_MAIN, rtm->rtm_table); EXPECT_EQ(RTPROT_UNSPEC, rtm->rtm_protocol); EXPECT_EQ(RT_SCOPE_LINK, rtm->rtm_scope); EXPECT_EQ(RTN_UNICAST, rtm->rtm_type); const struct rtattr* rta; int payload_length = RTM_PAYLOAD(netlink_message); int num_rta = 0; for (rta = RTM_RTA(rtm); RTA_OK(rta, payload_length); rta = RTA_NEXT(rta, payload_length)) { switch (rta->rta_type) { case RTA_PREFSRC: { const auto* raw_address = reinterpret_cast<const char*>(RTA_DATA(rta)); ASSERT_EQ(sizeof(struct in6_addr), RTA_PAYLOAD(rta)); QuicIpAddress address; address.FromPackedString(raw_address, RTA_PAYLOAD(rta)); EXPECT_EQ(preferred_ip, address); break; } case RTA_OIF: { ASSERT_EQ(sizeof(int), RTA_PAYLOAD(rta)); const auto* interface_index = reinterpret_cast<const int*>(RTA_DATA(rta)); EXPECT_EQ(egress_interface_index, *interface_index); break; } case RTA_DST: { const auto* raw_address = reinterpret_cast<const char*>(RTA_DATA(rta)); ASSERT_EQ(sizeof(struct in6_addr), RTA_PAYLOAD(rta)); QuicIpAddress address; address.FromPackedString(raw_address, RTA_PAYLOAD(rta)); EXPECT_EQ(subnet.ToString(), IpRange(address, rtm->rtm_dst_len).ToString()); break; } case RTA_TABLE: { ASSERT_EQ(*reinterpret_cast<uint32_t*>(RTA_DATA(rta)), QboneConstants::kQboneRouteTableId); break; } default: EXPECT_TRUE(false) << "Seeing rtattr that should not be sent"; } ++num_rta; } EXPECT_EQ(4, num_rta); }); EXPECT_TRUE(netlink->ChangeRoute( Netlink::Verb::kRemove, QboneConstants::kQboneRouteTableId, subnet, RT_SCOPE_LINK, preferred_ip, egress_interface_index)); } TEST_F(NetlinkTest, ChangeRouteReplace) { auto netlink = std::make_unique<Netlink>(&mock_kernel_); QuicIpAddress preferred_ip; preferred_ip.FromString("ff80:dead:beef::1"); IpRange subnet; subnet.FromString("ff80:dead:beef::/48"); int egress_interface_index = 7; ExpectNetlinkPacket( RTM_NEWROUTE, NLM_F_ACK | NLM_F_REQUEST | NLM_F_CREATE | NLM_F_REPLACE, [](void* buf, size_t len, int seq) { struct nlmsghdr* netlink_message = CreateNetlinkMessage(buf, nullptr, NLMSG_ERROR, seq); auto* err = reinterpret_cast<struct nlmsgerr*>(NLMSG_DATA(netlink_message)); err->error = 0; netlink_message->nlmsg_len = NLMSG_LENGTH(sizeof(struct nlmsgerr)); return netlink_message->nlmsg_len; }, [preferred_ip, subnet, egress_interface_index](const void* buf, size_t len) { auto* netlink_message = reinterpret_cast<const struct nlmsghdr*>(buf); auto* rtm = reinterpret_cast<const struct rtmsg*>(NLMSG_DATA(netlink_message)); EXPECT_EQ(AF_INET6, rtm->rtm_family); EXPECT_EQ(48, rtm->rtm_dst_len); EXPECT_EQ(0, rtm->rtm_src_len); EXPECT_EQ(RT_TABLE_MAIN, rtm->rtm_table); EXPECT_EQ(RTPROT_STATIC, rtm->rtm_protocol); EXPECT_EQ(RT_SCOPE_LINK, rtm->rtm_scope); EXPECT_EQ(RTN_UNICAST, rtm->rtm_type); const struct rtattr* rta; int payload_length = RTM_PAYLOAD(netlink_message); int num_rta = 0; for (rta = RTM_RTA(rtm); RTA_OK(rta, payload_length); rta = RTA_NEXT(rta, payload_length)) { switch (rta->rta_type) { case RTA_PREFSRC: { const auto* raw_address = reinterpret_cast<const char*>(RTA_DATA(rta)); ASSERT_EQ(sizeof(struct in6_addr), RTA_PAYLOAD(rta)); QuicIpAddress address; address.FromPackedString(raw_address, RTA_PAYLOAD(rta)); EXPECT_EQ(preferred_ip, address); break; } case RTA_GATEWAY: { const auto* raw_address = reinterpret_cast<const char*>(RTA_DATA(rta)); ASSERT_EQ(sizeof(struct in6_addr), RTA_PAYLOAD(rta)); QuicIpAddress address; address.FromPackedString(raw_address, RTA_PAYLOAD(rta)); EXPECT_EQ(*QboneConstants::GatewayAddress(), address); break; } case RTA_OIF: { ASSERT_EQ(sizeof(int), RTA_PAYLOAD(rta)); const auto* interface_index = reinterpret_cast<const int*>(RTA_DATA(rta)); EXPECT_EQ(egress_interface_index, *interface_index); break; } case RTA_DST: { const auto* raw_address = reinterpret_cast<const char*>(RTA_DATA(rta)); ASSERT_EQ(sizeof(struct in6_addr), RTA_PAYLOAD(rta)); QuicIpAddress address; address.FromPackedString(raw_address, RTA_PAYLOAD(rta)); EXPECT_EQ(subnet.ToString(), IpRange(address, rtm->rtm_dst_len).ToString()); break; } case RTA_TABLE: { ASSERT_EQ(*reinterpret_cast<uint32_t*>(RTA_DATA(rta)), QboneConstants::kQboneRouteTableId); break; } default: EXPECT_TRUE(false) << "Seeing rtattr that should not be sent"; } ++num_rta; } EXPECT_EQ(5, num_rta); }); EXPECT_TRUE(netlink->ChangeRoute( Netlink::Verb::kReplace, QboneConstants::kQboneRouteTableId, subnet, RT_SCOPE_LINK, preferred_ip, egress_interface_index)); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/qbone/platform/netlink.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/qbone/platform/netlink_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
e38f2614-c0c8-476a-930c-933b2ee50af8
cpp
google/quiche
icmp_packet
quiche/quic/qbone/platform/icmp_packet.cc
quiche/quic/qbone/platform/icmp_packet_test.cc
#include "quiche/quic/qbone/platform/icmp_packet.h" #include <netinet/ip6.h> #include <algorithm> #include "absl/strings/string_view.h" #include "quiche/quic/core/internet_checksum.h" #include "quiche/common/quiche_callbacks.h" #include "quiche/common/quiche_endian.h" namespace quic { namespace { constexpr size_t kIPv6AddressSize = sizeof(in6_addr); constexpr size_t kIPv6HeaderSize = sizeof(ip6_hdr); constexpr size_t kICMPv6HeaderSize = sizeof(icmp6_hdr); constexpr size_t kIPv6MinPacketSize = 1280; constexpr size_t kIcmpTtl = 255; constexpr size_t kICMPv6BodyMaxSize = kIPv6MinPacketSize - kIPv6HeaderSize - kICMPv6HeaderSize; struct ICMPv6Packet { ip6_hdr ip_header; icmp6_hdr icmp_header; uint8_t body[kICMPv6BodyMaxSize]; }; struct IPv6PseudoHeader { uint32_t payload_size{}; uint8_t zeros[3] = {0, 0, 0}; uint8_t next_header = IPPROTO_ICMPV6; }; } void CreateIcmpPacket(in6_addr src, in6_addr dst, const icmp6_hdr& icmp_header, absl::string_view body, quiche::UnretainedCallback<void(absl::string_view)> cb) { const size_t body_size = std::min(body.size(), kICMPv6BodyMaxSize); const size_t payload_size = kICMPv6HeaderSize + body_size; ICMPv6Packet icmp_packet{}; icmp_packet.ip_header.ip6_vfc = 0x6 << 4; icmp_packet.ip_header.ip6_plen = quiche::QuicheEndian::HostToNet16(payload_size); icmp_packet.ip_header.ip6_nxt = IPPROTO_ICMPV6; icmp_packet.ip_header.ip6_hops = kIcmpTtl; icmp_packet.ip_header.ip6_src = src; icmp_packet.ip_header.ip6_dst = dst; icmp_packet.icmp_header = icmp_header; icmp_packet.icmp_header.icmp6_cksum = 0; IPv6PseudoHeader pseudo_header{}; pseudo_header.payload_size = quiche::QuicheEndian::HostToNet32(payload_size); InternetChecksum checksum; checksum.Update(icmp_packet.ip_header.ip6_src.s6_addr, kIPv6AddressSize); checksum.Update(icmp_packet.ip_header.ip6_dst.s6_addr, kIPv6AddressSize); checksum.Update(reinterpret_cast<char*>(&pseudo_header), sizeof(pseudo_header)); checksum.Update(reinterpret_cast<const char*>(&icmp_packet.icmp_header), sizeof(icmp_packet.icmp_header)); checksum.Update(body.data(), body_size); icmp_packet.icmp_header.icmp6_cksum = checksum.Value(); memcpy(icmp_packet.body, body.data(), body_size); const char* packet = reinterpret_cast<char*>(&icmp_packet); const size_t packet_size = offsetof(ICMPv6Packet, body) + body_size; cb(absl::string_view(packet, packet_size)); } }
#include "quiche/quic/qbone/platform/icmp_packet.h" #include <netinet/ip6.h> #include <cstdint> #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/common/quiche_text_utils.h" namespace quic { namespace { constexpr char kReferenceSourceAddress[] = "fe80:1:2:3:4::1"; constexpr char kReferenceDestinationAddress[] = "fe80:4:3:2:1::1"; constexpr uint8_t kReferenceICMPMessageBody[] { 0xd2, 0x61, 0x29, 0x5b, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x59, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37 }; constexpr uint8_t kReferenceICMPPacket[] = { 0x60, 0x00, 0x00, 0x00, 0x00, 0x40, 0x3a, 0xFF, 0xfe, 0x80, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfe, 0x80, 0x00, 0x04, 0x00, 0x03, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x80, 0x00, 0xec, 0x00, 0xcb, 0x82, 0x00, 0x01, 0xd2, 0x61, 0x29, 0x5b, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x59, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37 }; } TEST(IcmpPacketTest, CreatedPacketMatchesReference) { QuicIpAddress src; ASSERT_TRUE(src.FromString(kReferenceSourceAddress)); in6_addr src_addr; memcpy(src_addr.s6_addr, src.ToPackedString().data(), sizeof(in6_addr)); QuicIpAddress dst; ASSERT_TRUE(dst.FromString(kReferenceDestinationAddress)); in6_addr dst_addr; memcpy(dst_addr.s6_addr, dst.ToPackedString().data(), sizeof(in6_addr)); icmp6_hdr icmp_header{}; icmp_header.icmp6_type = ICMP6_ECHO_REQUEST; icmp_header.icmp6_id = 0x82cb; icmp_header.icmp6_seq = 0x0100; absl::string_view message_body = absl::string_view( reinterpret_cast<const char*>(kReferenceICMPMessageBody), 56); absl::string_view expected_packet = absl::string_view( reinterpret_cast<const char*>(kReferenceICMPPacket), 104); CreateIcmpPacket(src_addr, dst_addr, icmp_header, message_body, [&expected_packet](absl::string_view packet) { QUIC_LOG(INFO) << quiche::QuicheTextUtils::HexDump(packet); ASSERT_EQ(packet, expected_packet); }); } TEST(IcmpPacketTest, NonZeroChecksumIsIgnored) { QuicIpAddress src; ASSERT_TRUE(src.FromString(kReferenceSourceAddress)); in6_addr src_addr; memcpy(src_addr.s6_addr, src.ToPackedString().data(), sizeof(in6_addr)); QuicIpAddress dst; ASSERT_TRUE(dst.FromString(kReferenceDestinationAddress)); in6_addr dst_addr; memcpy(dst_addr.s6_addr, dst.ToPackedString().data(), sizeof(in6_addr)); icmp6_hdr icmp_header{}; icmp_header.icmp6_type = ICMP6_ECHO_REQUEST; icmp_header.icmp6_id = 0x82cb; icmp_header.icmp6_seq = 0x0100; icmp_header.icmp6_cksum = 0x1234; absl::string_view message_body = absl::string_view( reinterpret_cast<const char*>(kReferenceICMPMessageBody), 56); absl::string_view expected_packet = absl::string_view( reinterpret_cast<const char*>(kReferenceICMPPacket), 104); CreateIcmpPacket(src_addr, dst_addr, icmp_header, message_body, [&expected_packet](absl::string_view packet) { QUIC_LOG(INFO) << quiche::QuicheTextUtils::HexDump(packet); ASSERT_EQ(packet, expected_packet); }); } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/qbone/platform/icmp_packet.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/qbone/platform/icmp_packet_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
d5aedaf9-d758-4aa4-98f7-1f005b8f5a21
cpp
google/quiche
priority_write_scheduler
quiche/http2/core/priority_write_scheduler.h
quiche/http2/core/priority_write_scheduler_test.cc
#ifndef QUICHE_HTTP2_CORE_PRIORITY_WRITE_SCHEDULER_H_ #define QUICHE_HTTP2_CORE_PRIORITY_WRITE_SCHEDULER_H_ #include <algorithm> #include <cstddef> #include <cstdint> #include <memory> #include <optional> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/strings/str_cat.h" #include "absl/time/time.h" #include "quiche/http2/core/spdy_protocol.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_circular_deque.h" namespace http2 { namespace test { template <typename StreamIdType> class PriorityWriteSchedulerPeer; } struct QUICHE_EXPORT SpdyPriorityToSpdyPriority { spdy::SpdyPriority operator()(spdy::SpdyPriority priority) { return priority; } }; template <typename StreamIdType, typename PriorityType = spdy::SpdyPriority, typename PriorityTypeToInt = SpdyPriorityToSpdyPriority, typename IntToPriorityType = SpdyPriorityToSpdyPriority> class QUICHE_EXPORT PriorityWriteScheduler { public: static constexpr int kHighestPriority = 0; static constexpr int kLowestPriority = 7; static_assert(spdy::kV3HighestPriority == kHighestPriority); static_assert(spdy::kV3LowestPriority == kLowestPriority); void RegisterStream(StreamIdType stream_id, PriorityType priority) { auto stream_info = std::make_unique<StreamInfo>( StreamInfo{std::move(priority), stream_id, false}); bool inserted = stream_infos_.insert(std::make_pair(stream_id, std::move(stream_info))) .second; QUICHE_BUG_IF(spdy_bug_19_2, !inserted) << "Stream " << stream_id << " already registered"; } void UnregisterStream(StreamIdType stream_id) { auto it = stream_infos_.find(stream_id); if (it == stream_infos_.end()) { QUICHE_BUG(spdy_bug_19_3) << "Stream " << stream_id << " not registered"; return; } const StreamInfo* const stream_info = it->second.get(); if (stream_info->ready) { bool erased = Erase(&priority_infos_[PriorityTypeToInt()(stream_info->priority)] .ready_list, stream_info); QUICHE_DCHECK(erased); } stream_infos_.erase(it); } bool StreamRegistered(StreamIdType stream_id) const { return stream_infos_.find(stream_id) != stream_infos_.end(); } PriorityType GetStreamPriority(StreamIdType stream_id) const { auto it = stream_infos_.find(stream_id); if (it == stream_infos_.end()) { QUICHE_DVLOG(1) << "Stream " << stream_id << " not registered"; return IntToPriorityType()(kLowestPriority); } return it->second->priority; } void UpdateStreamPriority(StreamIdType stream_id, PriorityType priority) { auto it = stream_infos_.find(stream_id); if (it == stream_infos_.end()) { QUICHE_DVLOG(1) << "Stream " << stream_id << " not registered"; return; } StreamInfo* const stream_info = it->second.get(); if (stream_info->priority == priority) { return; } if (PriorityTypeToInt()(stream_info->priority) != PriorityTypeToInt()(priority) && stream_info->ready) { bool erased = Erase(&priority_infos_[PriorityTypeToInt()(stream_info->priority)] .ready_list, stream_info); QUICHE_DCHECK(erased); priority_infos_[PriorityTypeToInt()(priority)].ready_list.push_back( stream_info); ++num_ready_streams_; } stream_info->priority = std::move(priority); } void RecordStreamEventTime(StreamIdType stream_id, absl::Time now) { auto it = stream_infos_.find(stream_id); if (it == stream_infos_.end()) { QUICHE_BUG(spdy_bug_19_4) << "Stream " << stream_id << " not registered"; return; } PriorityInfo& priority_info = priority_infos_[PriorityTypeToInt()(it->second->priority)]; priority_info.last_event_time = std::max(priority_info.last_event_time, absl::make_optional(now)); } std::optional<absl::Time> GetLatestEventWithPriority( StreamIdType stream_id) const { auto it = stream_infos_.find(stream_id); if (it == stream_infos_.end()) { QUICHE_BUG(spdy_bug_19_5) << "Stream " << stream_id << " not registered"; return std::nullopt; } std::optional<absl::Time> last_event_time; const StreamInfo* const stream_info = it->second.get(); for (int p = kHighestPriority; p < PriorityTypeToInt()(stream_info->priority); ++p) { last_event_time = std::max(last_event_time, priority_infos_[p].last_event_time); } return last_event_time; } StreamIdType PopNextReadyStream() { return std::get<0>(PopNextReadyStreamAndPriority()); } std::tuple<StreamIdType, PriorityType> PopNextReadyStreamAndPriority() { for (int p = kHighestPriority; p <= kLowestPriority; ++p) { ReadyList& ready_list = priority_infos_[p].ready_list; if (!ready_list.empty()) { StreamInfo* const info = ready_list.front(); ready_list.pop_front(); --num_ready_streams_; QUICHE_DCHECK(stream_infos_.find(info->stream_id) != stream_infos_.end()); info->ready = false; return std::make_tuple(info->stream_id, info->priority); } } QUICHE_BUG(spdy_bug_19_6) << "No ready streams available"; return std::make_tuple(0, IntToPriorityType()(kLowestPriority)); } bool ShouldYield(StreamIdType stream_id) const { auto it = stream_infos_.find(stream_id); if (it == stream_infos_.end()) { QUICHE_BUG(spdy_bug_19_7) << "Stream " << stream_id << " not registered"; return false; } const StreamInfo* const stream_info = it->second.get(); for (int p = kHighestPriority; p < PriorityTypeToInt()(stream_info->priority); ++p) { if (!priority_infos_[p].ready_list.empty()) { return true; } } const auto& ready_list = priority_infos_[PriorityTypeToInt()(it->second->priority)].ready_list; if (ready_list.empty() || ready_list.front()->stream_id == stream_id) { return false; } return true; } void MarkStreamReady(StreamIdType stream_id, bool add_to_front) { auto it = stream_infos_.find(stream_id); if (it == stream_infos_.end()) { QUICHE_BUG(spdy_bug_19_8) << "Stream " << stream_id << " not registered"; return; } StreamInfo* const stream_info = it->second.get(); if (stream_info->ready) { return; } ReadyList& ready_list = priority_infos_[PriorityTypeToInt()(stream_info->priority)].ready_list; if (add_to_front) { ready_list.push_front(stream_info); } else { ready_list.push_back(stream_info); } ++num_ready_streams_; stream_info->ready = true; } void MarkStreamNotReady(StreamIdType stream_id) { auto it = stream_infos_.find(stream_id); if (it == stream_infos_.end()) { QUICHE_BUG(spdy_bug_19_9) << "Stream " << stream_id << " not registered"; return; } StreamInfo* const stream_info = it->second.get(); if (!stream_info->ready) { return; } bool erased = Erase( &priority_infos_[PriorityTypeToInt()(stream_info->priority)].ready_list, stream_info); QUICHE_DCHECK(erased); stream_info->ready = false; } bool HasReadyStreams() const { return num_ready_streams_ > 0; } size_t NumReadyStreams() const { return num_ready_streams_; } size_t NumRegisteredStreams() const { return stream_infos_.size(); } std::string DebugString() const { return absl::StrCat( "PriorityWriteScheduler {num_streams=", stream_infos_.size(), " num_ready_streams=", NumReadyStreams(), "}"); } bool IsStreamReady(StreamIdType stream_id) const { auto it = stream_infos_.find(stream_id); if (it == stream_infos_.end()) { QUICHE_DLOG(INFO) << "Stream " << stream_id << " not registered"; return false; } return it->second->ready; } private: friend class test::PriorityWriteSchedulerPeer<StreamIdType>; struct QUICHE_EXPORT StreamInfo { PriorityType priority; StreamIdType stream_id; bool ready; }; using ReadyList = quiche::QuicheCircularDeque<StreamInfo*>; struct QUICHE_EXPORT PriorityInfo { ReadyList ready_list; std::optional<absl::Time> last_event_time; }; using StreamInfoMap = absl::flat_hash_map<StreamIdType, std::unique_ptr<StreamInfo>>; bool Erase(ReadyList* ready_list, const StreamInfo* info) { auto it = std::remove(ready_list->begin(), ready_list->end(), info); if (it == ready_list->end()) { return false; } ready_list->pop_back(); --num_ready_streams_; return true; } size_t num_ready_streams_ = 0; PriorityInfo priority_infos_[kLowestPriority + 1]; StreamInfoMap stream_infos_; }; } #endif
#include "quiche/http2/core/priority_write_scheduler.h" #include "quiche/http2/core/spdy_protocol.h" #include "quiche/http2/test_tools/spdy_test_utils.h" #include "quiche/common/platform/api/quiche_expect_bug.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { using ::spdy::SpdyPriority; using ::spdy::SpdyStreamId; using ::testing::Eq; using ::testing::Optional; template <typename StreamIdType> class PriorityWriteSchedulerPeer { public: explicit PriorityWriteSchedulerPeer( PriorityWriteScheduler<StreamIdType>* scheduler) : scheduler_(scheduler) {} size_t NumReadyStreams(SpdyPriority priority) const { return scheduler_->priority_infos_[priority].ready_list.size(); } private: PriorityWriteScheduler<StreamIdType>* scheduler_; }; namespace { class PriorityWriteSchedulerTest : public quiche::test::QuicheTest { public: static constexpr int kLowestPriority = PriorityWriteScheduler<SpdyStreamId>::kLowestPriority; PriorityWriteSchedulerTest() : peer_(&scheduler_) {} PriorityWriteScheduler<SpdyStreamId> scheduler_; PriorityWriteSchedulerPeer<SpdyStreamId> peer_; }; TEST_F(PriorityWriteSchedulerTest, RegisterUnregisterStreams) { EXPECT_FALSE(scheduler_.HasReadyStreams()); EXPECT_FALSE(scheduler_.StreamRegistered(1)); EXPECT_EQ(0u, scheduler_.NumRegisteredStreams()); scheduler_.RegisterStream(1, 1); EXPECT_TRUE(scheduler_.StreamRegistered(1)); EXPECT_EQ(1u, scheduler_.NumRegisteredStreams()); EXPECT_QUICHE_BUG(scheduler_.RegisterStream(1, 1), "Stream 1 already registered"); EXPECT_EQ(1u, scheduler_.NumRegisteredStreams()); EXPECT_QUICHE_BUG(scheduler_.RegisterStream(1, 2), "Stream 1 already registered"); EXPECT_EQ(1u, scheduler_.NumRegisteredStreams()); scheduler_.RegisterStream(2, 3); EXPECT_EQ(2u, scheduler_.NumRegisteredStreams()); EXPECT_FALSE(scheduler_.HasReadyStreams()); scheduler_.UnregisterStream(1); EXPECT_EQ(1u, scheduler_.NumRegisteredStreams()); scheduler_.UnregisterStream(2); EXPECT_EQ(0u, scheduler_.NumRegisteredStreams()); EXPECT_QUICHE_BUG(scheduler_.UnregisterStream(1), "Stream 1 not registered"); EXPECT_QUICHE_BUG(scheduler_.UnregisterStream(2), "Stream 2 not registered"); EXPECT_EQ(0u, scheduler_.NumRegisteredStreams()); } TEST_F(PriorityWriteSchedulerTest, GetStreamPriority) { EXPECT_EQ(kLowestPriority, scheduler_.GetStreamPriority(1)); scheduler_.RegisterStream(1, 3); EXPECT_EQ(3, scheduler_.GetStreamPriority(1)); EXPECT_QUICHE_BUG(scheduler_.RegisterStream(1, 4), "Stream 1 already registered"); EXPECT_EQ(3, scheduler_.GetStreamPriority(1)); scheduler_.UpdateStreamPriority(1, 5); EXPECT_EQ(5, scheduler_.GetStreamPriority(1)); scheduler_.MarkStreamReady(1, true); EXPECT_EQ(5, scheduler_.GetStreamPriority(1)); EXPECT_EQ(1u, peer_.NumReadyStreams(5)); scheduler_.UpdateStreamPriority(1, 6); EXPECT_EQ(6, scheduler_.GetStreamPriority(1)); EXPECT_EQ(0u, peer_.NumReadyStreams(5)); EXPECT_EQ(1u, peer_.NumReadyStreams(6)); EXPECT_EQ(1u, scheduler_.PopNextReadyStream()); EXPECT_EQ(6, scheduler_.GetStreamPriority(1)); scheduler_.UnregisterStream(1); EXPECT_EQ(kLowestPriority, scheduler_.GetStreamPriority(1)); } TEST_F(PriorityWriteSchedulerTest, PopNextReadyStreamAndPriority) { scheduler_.RegisterStream(1, 3); scheduler_.MarkStreamReady(1, true); EXPECT_EQ(std::make_tuple(1u, 3), scheduler_.PopNextReadyStreamAndPriority()); scheduler_.UnregisterStream(1); } TEST_F(PriorityWriteSchedulerTest, UpdateStreamPriority) { EXPECT_EQ(kLowestPriority, scheduler_.GetStreamPriority(3)); EXPECT_FALSE(scheduler_.StreamRegistered(3)); scheduler_.UpdateStreamPriority(3, 1); EXPECT_FALSE(scheduler_.StreamRegistered(3)); EXPECT_EQ(kLowestPriority, scheduler_.GetStreamPriority(3)); scheduler_.RegisterStream(3, 1); EXPECT_EQ(1, scheduler_.GetStreamPriority(3)); scheduler_.UpdateStreamPriority(3, 2); EXPECT_EQ(2, scheduler_.GetStreamPriority(3)); scheduler_.UpdateStreamPriority(3, 2); EXPECT_EQ(2, scheduler_.GetStreamPriority(3)); scheduler_.RegisterStream(4, 1); scheduler_.MarkStreamReady(3, false); EXPECT_TRUE(scheduler_.IsStreamReady(3)); scheduler_.MarkStreamReady(4, false); EXPECT_TRUE(scheduler_.IsStreamReady(4)); EXPECT_EQ(4u, scheduler_.PopNextReadyStream()); EXPECT_FALSE(scheduler_.IsStreamReady(4)); EXPECT_EQ(3u, scheduler_.PopNextReadyStream()); EXPECT_FALSE(scheduler_.IsStreamReady(3)); scheduler_.MarkStreamReady(3, false); scheduler_.MarkStreamReady(4, false); scheduler_.UpdateStreamPriority(4, 3); EXPECT_EQ(3u, scheduler_.PopNextReadyStream()); EXPECT_EQ(4u, scheduler_.PopNextReadyStream()); scheduler_.UnregisterStream(3); } TEST_F(PriorityWriteSchedulerTest, MarkStreamReadyBack) { EXPECT_FALSE(scheduler_.HasReadyStreams()); EXPECT_QUICHE_BUG(scheduler_.MarkStreamReady(1, false), "Stream 1 not registered"); EXPECT_FALSE(scheduler_.HasReadyStreams()); EXPECT_QUICHE_BUG(EXPECT_EQ(0u, scheduler_.PopNextReadyStream()), "No ready streams available"); scheduler_.RegisterStream(1, 3); scheduler_.MarkStreamReady(1, false); EXPECT_TRUE(scheduler_.HasReadyStreams()); scheduler_.RegisterStream(2, 3); scheduler_.MarkStreamReady(2, false); scheduler_.RegisterStream(3, 3); scheduler_.MarkStreamReady(3, false); scheduler_.RegisterStream(4, 2); scheduler_.MarkStreamReady(4, false); scheduler_.RegisterStream(5, 5); scheduler_.MarkStreamReady(5, false); EXPECT_EQ(4u, scheduler_.PopNextReadyStream()); EXPECT_EQ(1u, scheduler_.PopNextReadyStream()); EXPECT_EQ(2u, scheduler_.PopNextReadyStream()); EXPECT_EQ(3u, scheduler_.PopNextReadyStream()); EXPECT_EQ(5u, scheduler_.PopNextReadyStream()); EXPECT_QUICHE_BUG(EXPECT_EQ(0u, scheduler_.PopNextReadyStream()), "No ready streams available"); } TEST_F(PriorityWriteSchedulerTest, MarkStreamReadyFront) { EXPECT_FALSE(scheduler_.HasReadyStreams()); EXPECT_QUICHE_BUG(scheduler_.MarkStreamReady(1, true), "Stream 1 not registered"); EXPECT_FALSE(scheduler_.HasReadyStreams()); EXPECT_QUICHE_BUG(EXPECT_EQ(0u, scheduler_.PopNextReadyStream()), "No ready streams available"); scheduler_.RegisterStream(1, 3); scheduler_.MarkStreamReady(1, true); EXPECT_TRUE(scheduler_.HasReadyStreams()); scheduler_.RegisterStream(2, 3); scheduler_.MarkStreamReady(2, true); scheduler_.RegisterStream(3, 3); scheduler_.MarkStreamReady(3, true); scheduler_.RegisterStream(4, 2); scheduler_.MarkStreamReady(4, true); scheduler_.RegisterStream(5, 5); scheduler_.MarkStreamReady(5, true); EXPECT_EQ(4u, scheduler_.PopNextReadyStream()); EXPECT_EQ(3u, scheduler_.PopNextReadyStream()); EXPECT_EQ(2u, scheduler_.PopNextReadyStream()); EXPECT_EQ(1u, scheduler_.PopNextReadyStream()); EXPECT_EQ(5u, scheduler_.PopNextReadyStream()); EXPECT_QUICHE_BUG(EXPECT_EQ(0u, scheduler_.PopNextReadyStream()), "No ready streams available"); } TEST_F(PriorityWriteSchedulerTest, MarkStreamReadyBackAndFront) { scheduler_.RegisterStream(1, 4); scheduler_.RegisterStream(2, 3); scheduler_.RegisterStream(3, 3); scheduler_.RegisterStream(4, 3); scheduler_.RegisterStream(5, 4); scheduler_.RegisterStream(6, 1); scheduler_.MarkStreamReady(1, true); scheduler_.MarkStreamReady(2, true); scheduler_.MarkStreamReady(3, false); scheduler_.MarkStreamReady(4, true); scheduler_.MarkStreamReady(5, false); scheduler_.MarkStreamReady(6, true); EXPECT_EQ(6u, scheduler_.PopNextReadyStream()); EXPECT_EQ(4u, scheduler_.PopNextReadyStream()); EXPECT_EQ(2u, scheduler_.PopNextReadyStream()); EXPECT_EQ(3u, scheduler_.PopNextReadyStream()); EXPECT_EQ(1u, scheduler_.PopNextReadyStream()); EXPECT_EQ(5u, scheduler_.PopNextReadyStream()); EXPECT_QUICHE_BUG(EXPECT_EQ(0u, scheduler_.PopNextReadyStream()), "No ready streams available"); } TEST_F(PriorityWriteSchedulerTest, MarkStreamNotReady) { scheduler_.RegisterStream(1, 1); EXPECT_EQ(0u, scheduler_.NumReadyStreams()); scheduler_.MarkStreamReady(1, false); EXPECT_EQ(1u, scheduler_.NumReadyStreams()); scheduler_.MarkStreamNotReady(1); EXPECT_EQ(0u, scheduler_.NumReadyStreams()); EXPECT_QUICHE_BUG(EXPECT_EQ(0u, scheduler_.PopNextReadyStream()), "No ready streams available"); scheduler_.MarkStreamNotReady(1); EXPECT_EQ(0u, scheduler_.NumReadyStreams()); EXPECT_QUICHE_BUG(scheduler_.MarkStreamNotReady(3), "Stream 3 not registered"); } TEST_F(PriorityWriteSchedulerTest, UnregisterRemovesStream) { scheduler_.RegisterStream(3, 4); scheduler_.MarkStreamReady(3, false); EXPECT_EQ(1u, scheduler_.NumReadyStreams()); scheduler_.UnregisterStream(3); EXPECT_EQ(0u, scheduler_.NumReadyStreams()); EXPECT_QUICHE_BUG(EXPECT_EQ(0u, scheduler_.PopNextReadyStream()), "No ready streams available"); } TEST_F(PriorityWriteSchedulerTest, ShouldYield) { scheduler_.RegisterStream(1, 1); scheduler_.RegisterStream(4, 4); scheduler_.RegisterStream(5, 4); scheduler_.RegisterStream(7, 7); EXPECT_FALSE(scheduler_.ShouldYield(1)); scheduler_.MarkStreamReady(4, false); EXPECT_FALSE(scheduler_.ShouldYield(4)); EXPECT_TRUE(scheduler_.ShouldYield(7)); EXPECT_TRUE(scheduler_.ShouldYield(5)); EXPECT_FALSE(scheduler_.ShouldYield(1)); scheduler_.MarkStreamReady(5, false); EXPECT_FALSE(scheduler_.ShouldYield(4)); EXPECT_TRUE(scheduler_.ShouldYield(5)); } TEST_F(PriorityWriteSchedulerTest, GetLatestEventWithPriority) { EXPECT_QUICHE_BUG( scheduler_.RecordStreamEventTime(3, absl::FromUnixMicros(5)), "Stream 3 not registered"); EXPECT_QUICHE_BUG( EXPECT_FALSE(scheduler_.GetLatestEventWithPriority(4).has_value()), "Stream 4 not registered"); for (int i = 1; i < 5; ++i) { scheduler_.RegisterStream(i, i); } for (int i = 1; i < 5; ++i) { EXPECT_FALSE(scheduler_.GetLatestEventWithPriority(i).has_value()); } for (int i = 1; i < 5; ++i) { scheduler_.RecordStreamEventTime(i, absl::FromUnixMicros(i * 100)); } EXPECT_FALSE(scheduler_.GetLatestEventWithPriority(1).has_value()); for (int i = 2; i < 5; ++i) { EXPECT_THAT(scheduler_.GetLatestEventWithPriority(i), Optional(Eq(absl::FromUnixMicros((i - 1) * 100)))); } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/core/priority_write_scheduler.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/core/priority_write_scheduler_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
5c396182-72ac-466f-b33e-1ce61dd04742
cpp
google/quiche
nghttp2
quiche/http2/adapter/nghttp2.h
quiche/http2/adapter/nghttp2_test.cc
#ifndef QUICHE_HTTP2_ADAPTER_NGHTTP2_H_ #define QUICHE_HTTP2_ADAPTER_NGHTTP2_H_ #include <cstddef> using ssize_t = ptrdiff_t; #include "nghttp2/nghttp2.h" #endif
#include "quiche/http2/adapter/nghttp2.h" #include <string> #include <utility> #include <vector> #include "absl/strings/str_cat.h" #include "quiche/http2/adapter/mock_nghttp2_callbacks.h" #include "quiche/http2/adapter/nghttp2_test_utils.h" #include "quiche/http2/adapter/nghttp2_util.h" #include "quiche/http2/adapter/test_frame_sequence.h" #include "quiche/http2/adapter/test_utils.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace adapter { namespace test { namespace { using testing::_; enum FrameType { DATA, HEADERS, PRIORITY, RST_STREAM, SETTINGS, PUSH_PROMISE, PING, GOAWAY, WINDOW_UPDATE, }; nghttp2_option* GetOptions() { nghttp2_option* options; nghttp2_option_new(&options); nghttp2_option_set_no_closed_streams(options, 1); nghttp2_option_set_no_auto_window_update(options, 1); nghttp2_option_set_max_send_header_block_length(options, 0x2000000); nghttp2_option_set_max_outbound_ack(options, 10000); return options; } class Nghttp2Test : public quiche::test::QuicheTest { public: Nghttp2Test() : session_(MakeSessionPtr(nullptr)) {} void SetUp() override { InitializeSession(); } virtual Perspective GetPerspective() = 0; void InitializeSession() { auto nghttp2_callbacks = MockNghttp2Callbacks::GetCallbacks(); nghttp2_option* options = GetOptions(); nghttp2_session* ptr; if (GetPerspective() == Perspective::kClient) { nghttp2_session_client_new2(&ptr, nghttp2_callbacks.get(), &mock_callbacks_, options); } else { nghttp2_session_server_new2(&ptr, nghttp2_callbacks.get(), &mock_callbacks_, options); } nghttp2_option_del(options); EXPECT_CALL(mock_callbacks_, Send(_, _, _)) .WillRepeatedly( [this](const uint8_t* data, size_t length, int ) { absl::StrAppend(&serialized_, ToStringView(data, length)); return length; }); EXPECT_CALL(mock_callbacks_, SendData(_, _, _, _)) .WillRepeatedly([this](nghttp2_frame* , const uint8_t* framehd, size_t length, nghttp2_data_source* source) { QUICHE_LOG(INFO) << "Appending frame header and " << length << " bytes of data"; auto* s = static_cast<TestDataSource*>(source->ptr); absl::StrAppend(&serialized_, ToStringView(framehd, 9), s->ReadNext(length)); return 0; }); session_ = MakeSessionPtr(ptr); } testing::StrictMock<MockNghttp2Callbacks> mock_callbacks_; nghttp2_session_unique_ptr session_; std::string serialized_; }; class Nghttp2ClientTest : public Nghttp2Test { public: Perspective GetPerspective() override { return Perspective::kClient; } }; TEST_F(Nghttp2ClientTest, ClientReceivesUnexpectedHeaders) { const std::string initial_frames = TestFrameSequence() .ServerPreface() .Ping(42) .WindowUpdate(0, 1000) .Serialize(); testing::InSequence seq; EXPECT_CALL(mock_callbacks_, OnBeginFrame(HasFrameHeader(0, SETTINGS, 0))); EXPECT_CALL(mock_callbacks_, OnFrameRecv(IsSettings(testing::IsEmpty()))); EXPECT_CALL(mock_callbacks_, OnBeginFrame(HasFrameHeader(0, PING, 0))); EXPECT_CALL(mock_callbacks_, OnFrameRecv(IsPing(42))); EXPECT_CALL(mock_callbacks_, OnBeginFrame(HasFrameHeader(0, WINDOW_UPDATE, 0))); EXPECT_CALL(mock_callbacks_, OnFrameRecv(IsWindowUpdate(1000))); ssize_t result = nghttp2_session_mem_recv( session_.get(), ToUint8Ptr(initial_frames.data()), initial_frames.size()); ASSERT_EQ(result, initial_frames.size()); const std::string unexpected_stream_frames = TestFrameSequence() .Headers(1, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, false) .Data(1, "This is the response body.") .RstStream(3, Http2ErrorCode::INTERNAL_ERROR) .GoAway(5, Http2ErrorCode::ENHANCE_YOUR_CALM, "calm down!!") .Serialize(); EXPECT_CALL(mock_callbacks_, OnBeginFrame(HasFrameHeader(1, HEADERS, _))); EXPECT_CALL(mock_callbacks_, OnInvalidFrameRecv(IsHeaders(1, _, _), _)); nghttp2_session_mem_recv(session_.get(), ToUint8Ptr(unexpected_stream_frames.data()), unexpected_stream_frames.size()); } TEST_F(Nghttp2ClientTest, ClientSendsRequest) { int result = nghttp2_session_send(session_.get()); ASSERT_EQ(result, 0); EXPECT_THAT(serialized_, testing::StrEq(spdy::kHttp2ConnectionHeaderPrefix)); serialized_.clear(); const std::string initial_frames = TestFrameSequence().ServerPreface().Serialize(); testing::InSequence s; EXPECT_CALL(mock_callbacks_, OnBeginFrame(HasFrameHeader(0, SETTINGS, 0))); EXPECT_CALL(mock_callbacks_, OnFrameRecv(IsSettings(testing::IsEmpty()))); ssize_t recv_result = nghttp2_session_mem_recv( session_.get(), ToUint8Ptr(initial_frames.data()), initial_frames.size()); EXPECT_EQ(initial_frames.size(), recv_result); EXPECT_CALL(mock_callbacks_, BeforeFrameSend(IsSettings(testing::IsEmpty()))); EXPECT_CALL(mock_callbacks_, OnFrameSend(IsSettings(testing::IsEmpty()))); EXPECT_TRUE(nghttp2_session_want_write(session_.get())); result = nghttp2_session_send(session_.get()); EXPECT_THAT(serialized_, EqualsFrames({spdy::SpdyFrameType::SETTINGS})); serialized_.clear(); EXPECT_FALSE(nghttp2_session_want_write(session_.get())); std::vector<std::pair<absl::string_view, absl::string_view>> headers = { {":method", "POST"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}; std::vector<nghttp2_nv> nvs; for (const auto& h : headers) { nvs.push_back({.name = ToUint8Ptr(h.first.data()), .value = ToUint8Ptr(h.second.data()), .namelen = h.first.size(), .valuelen = h.second.size(), .flags = NGHTTP2_NV_FLAG_NONE}); } const absl::string_view kBody = "This is an example request body."; TestDataSource source{kBody}; nghttp2_data_provider provider = source.MakeDataProvider(); int stream_id = nghttp2_submit_request(session_.get(), nullptr , nvs.data(), nvs.size(), &provider, nullptr ); EXPECT_GT(stream_id, 0); EXPECT_TRUE(nghttp2_session_want_write(session_.get())); EXPECT_CALL(mock_callbacks_, BeforeFrameSend(IsHeaders(stream_id, _, _))); EXPECT_CALL(mock_callbacks_, OnFrameSend(IsHeaders(stream_id, _, _))); EXPECT_CALL(mock_callbacks_, OnFrameSend(IsData(stream_id, kBody.size(), _))); nghttp2_session_send(session_.get()); EXPECT_THAT(serialized_, EqualsFrames({spdy::SpdyFrameType::HEADERS, spdy::SpdyFrameType::DATA})); EXPECT_THAT(serialized_, testing::HasSubstr(kBody)); EXPECT_FALSE(nghttp2_session_want_write(session_.get())); } class Nghttp2ServerTest : public Nghttp2Test { public: Perspective GetPerspective() override { return Perspective::kServer; } }; TEST_F(Nghttp2ServerTest, MismatchedContentLength) { const std::string initial_frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/"}, {"content-length", "50"}}, false) .Data(1, "Less than 50 bytes.", true) .Serialize(); testing::InSequence seq; EXPECT_CALL(mock_callbacks_, OnBeginFrame(HasFrameHeader(0, SETTINGS, _))); EXPECT_CALL(mock_callbacks_, OnFrameRecv(IsSettings(testing::IsEmpty()))); EXPECT_CALL(mock_callbacks_, OnBeginFrame(HasFrameHeader( 1, HEADERS, NGHTTP2_FLAG_END_HEADERS))); EXPECT_CALL(mock_callbacks_, OnBeginHeaders(IsHeaders(1, NGHTTP2_FLAG_END_HEADERS, NGHTTP2_HCAT_REQUEST))); EXPECT_CALL(mock_callbacks_, OnHeader(_, ":method", "POST", _)); EXPECT_CALL(mock_callbacks_, OnHeader(_, ":scheme", "https", _)); EXPECT_CALL(mock_callbacks_, OnHeader(_, ":authority", "example.com", _)); EXPECT_CALL(mock_callbacks_, OnHeader(_, ":path", "/", _)); EXPECT_CALL(mock_callbacks_, OnHeader(_, "content-length", "50", _)); EXPECT_CALL(mock_callbacks_, OnFrameRecv(IsHeaders(1, NGHTTP2_FLAG_END_HEADERS, NGHTTP2_HCAT_REQUEST))); EXPECT_CALL(mock_callbacks_, OnBeginFrame(HasFrameHeader(1, DATA, NGHTTP2_FLAG_END_STREAM))); EXPECT_CALL(mock_callbacks_, OnDataChunkRecv(NGHTTP2_FLAG_END_STREAM, 1, "Less than 50 bytes.")); ssize_t result = nghttp2_session_mem_recv( session_.get(), ToUint8Ptr(initial_frames.data()), initial_frames.size()); ASSERT_EQ(result, initial_frames.size()); } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/nghttp2.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/nghttp2_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
b838e648-4281-4f28-8219-c370a373b8cf
cpp
google/quiche
btree_scheduler
quiche/common/btree_scheduler.h
quiche/common/btree_scheduler_test.cc
#ifndef QUICHE_COMMON_BTREE_SCHEDULER_H_ #define QUICHE_COMMON_BTREE_SCHEDULER_H_ #include <cstddef> #include <limits> #include <optional> #include <utility> #include "absl/base/attributes.h" #include "absl/container/btree_map.h" #include "absl/container/node_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quiche { template <typename Id, typename Priority> class QUICHE_NO_EXPORT BTreeScheduler { public: bool HasRegistered() const { return !streams_.empty(); } bool HasScheduled() const { return !schedule_.empty(); } size_t NumScheduled() const { return schedule_.size(); } size_t NumRegistered() const { return streams_.size(); } size_t NumScheduledInPriorityRange(std::optional<Priority> min, std::optional<Priority> max) const; absl::StatusOr<bool> ShouldYield(Id id) const; std::optional<Priority> GetPriorityFor(Id id) const { auto it = streams_.find(id); if (it == streams_.end()) { return std::nullopt; } return it->second.priority; } absl::StatusOr<Id> PopFront(); absl::Status Register(Id stream_id, const Priority& priority); absl::Status Unregister(Id stream_id); absl::Status UpdatePriority(Id stream_id, const Priority& new_priority); absl::Status Schedule(Id stream_id); bool IsScheduled(Id stream_id) const; private: struct StreamEntry { ABSL_ATTRIBUTE_NO_UNIQUE_ADDRESS Priority priority; std::optional<int> current_sequence_number = std::nullopt; bool scheduled() const { return current_sequence_number.has_value(); } }; using FullStreamEntry = std::pair<const Id, StreamEntry>; struct ScheduleKey { ABSL_ATTRIBUTE_NO_UNIQUE_ADDRESS Priority priority; int sequence_number; bool operator<(const ScheduleKey& other) const { return std::make_tuple(priority, sequence_number) > std::make_tuple(other.priority, other.sequence_number); } static ScheduleKey MinForPriority(Priority priority) { return ScheduleKey{priority, std::numeric_limits<int>::max()}; } static ScheduleKey MaxForPriority(Priority priority) { return ScheduleKey{priority, std::numeric_limits<int>::min()}; } }; using FullScheduleEntry = std::pair<const ScheduleKey, FullStreamEntry*>; using ScheduleIterator = typename absl::btree_map<ScheduleKey, FullStreamEntry*>::const_iterator; static Id StreamId(const FullScheduleEntry& entry) { return entry.second->first; } absl::StatusOr<FullScheduleEntry> DescheduleStream(const StreamEntry& entry); absl::node_hash_map<Id, StreamEntry> streams_; absl::btree_map<ScheduleKey, FullStreamEntry*> schedule_; int current_write_sequence_number_ = 0; }; template <typename Id, typename Priority> size_t BTreeScheduler<Id, Priority>::NumScheduledInPriorityRange( std::optional<Priority> min, std::optional<Priority> max) const { if (min.has_value() && max.has_value()) { QUICHE_DCHECK(*min <= *max); } ScheduleIterator begin = max.has_value() ? schedule_.lower_bound(ScheduleKey::MinForPriority(*max)) : schedule_.begin(); ScheduleIterator end = min.has_value() ? schedule_.upper_bound(ScheduleKey::MaxForPriority(*min)) : schedule_.end(); return end - begin; } template <typename Id, typename Priority> absl::Status BTreeScheduler<Id, Priority>::Register(Id stream_id, const Priority& priority) { auto [it, success] = streams_.insert({stream_id, StreamEntry{priority}}); if (!success) { return absl::AlreadyExistsError("ID already registered"); } return absl::OkStatus(); } template <typename Id, typename Priority> auto BTreeScheduler<Id, Priority>::DescheduleStream(const StreamEntry& entry) -> absl::StatusOr<FullScheduleEntry> { QUICHE_DCHECK(entry.scheduled()); auto it = schedule_.find( ScheduleKey{entry.priority, *entry.current_sequence_number}); if (it == schedule_.end()) { return absl::InternalError( "Calling DescheduleStream() on an entry that is not in the schedule at " "the expected key."); } FullScheduleEntry result = *it; schedule_.erase(it); return result; } template <typename Id, typename Priority> absl::Status BTreeScheduler<Id, Priority>::Unregister(Id stream_id) { auto it = streams_.find(stream_id); if (it == streams_.end()) { return absl::NotFoundError("Stream not registered"); } const StreamEntry& stream = it->second; if (stream.scheduled()) { if (!DescheduleStream(stream).ok()) { QUICHE_BUG(BTreeSchedule_Unregister_NotInSchedule) << "UnregisterStream() called on a stream ID " << stream_id << ", which is marked ready, but is not in the schedule"; } } streams_.erase(it); return absl::OkStatus(); } template <typename Id, typename Priority> absl::Status BTreeScheduler<Id, Priority>::UpdatePriority( Id stream_id, const Priority& new_priority) { auto it = streams_.find(stream_id); if (it == streams_.end()) { return absl::NotFoundError("ID not registered"); } StreamEntry& stream = it->second; std::optional<int> sequence_number; if (stream.scheduled()) { absl::StatusOr<FullScheduleEntry> old_entry = DescheduleStream(stream); if (old_entry.ok()) { sequence_number = old_entry->first.sequence_number; QUICHE_DCHECK_EQ(old_entry->second, &*it); } else { QUICHE_BUG(BTreeScheduler_Update_Not_In_Schedule) << "UpdatePriority() called on a stream ID " << stream_id << ", which is marked ready, but is not in the schedule"; } } stream.priority = new_priority; if (sequence_number.has_value()) { schedule_.insert({ScheduleKey{stream.priority, *sequence_number}, &*it}); } return absl::OkStatus(); } template <typename Id, typename Priority> absl::StatusOr<bool> BTreeScheduler<Id, Priority>::ShouldYield( Id stream_id) const { const auto stream_it = streams_.find(stream_id); if (stream_it == streams_.end()) { return absl::NotFoundError("ID not registered"); } const StreamEntry& stream = stream_it->second; if (schedule_.empty()) { return false; } const FullScheduleEntry& next = *schedule_.begin(); if (StreamId(next) == stream_id) { return false; } return next.first.priority >= stream.priority; } template <typename Id, typename Priority> absl::StatusOr<Id> BTreeScheduler<Id, Priority>::PopFront() { if (schedule_.empty()) { return absl::NotFoundError("No streams scheduled"); } auto schedule_it = schedule_.begin(); QUICHE_DCHECK(schedule_it->second->second.scheduled()); schedule_it->second->second.current_sequence_number = std::nullopt; Id result = StreamId(*schedule_it); schedule_.erase(schedule_it); return result; } template <typename Id, typename Priority> absl::Status BTreeScheduler<Id, Priority>::Schedule(Id stream_id) { const auto stream_it = streams_.find(stream_id); if (stream_it == streams_.end()) { return absl::NotFoundError("ID not registered"); } if (stream_it->second.scheduled()) { return absl::OkStatus(); } auto [schedule_it, success] = schedule_.insert({ScheduleKey{stream_it->second.priority, --current_write_sequence_number_}, &*stream_it}); QUICHE_BUG_IF(WebTransportWriteBlockedList_AddStream_conflict, !success) << "Conflicting key in scheduler for stream " << stream_id; stream_it->second.current_sequence_number = schedule_it->first.sequence_number; return absl::OkStatus(); } template <typename Id, typename Priority> bool BTreeScheduler<Id, Priority>::IsScheduled(Id stream_id) const { const auto stream_it = streams_.find(stream_id); if (stream_it == streams_.end()) { return false; } return stream_it->second.scheduled(); } } #endif
#include "quiche/common/btree_scheduler.h" #include <optional> #include <ostream> #include <string> #include <tuple> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace quiche::test { namespace { using ::testing::ElementsAre; using ::testing::Optional; template <typename Id, typename Priority> void ScheduleIds(BTreeScheduler<Id, Priority>& scheduler, absl::Span<const Id> ids) { for (Id id : ids) { QUICHE_EXPECT_OK(scheduler.Schedule(id)); } } template <typename Id, typename Priority> std::vector<Id> PopAll(BTreeScheduler<Id, Priority>& scheduler) { std::vector<Id> result; result.reserve(scheduler.NumScheduled()); for (;;) { absl::StatusOr<Id> id = scheduler.PopFront(); if (id.ok()) { result.push_back(*id); } else { EXPECT_THAT(id, StatusIs(absl::StatusCode::kNotFound)); break; } } return result; } TEST(BTreeSchedulerTest, SimplePop) { BTreeScheduler<int, int> scheduler; QUICHE_EXPECT_OK(scheduler.Register(1, 100)); QUICHE_EXPECT_OK(scheduler.Register(2, 101)); QUICHE_EXPECT_OK(scheduler.Register(3, 102)); EXPECT_THAT(scheduler.GetPriorityFor(1), Optional(100)); EXPECT_THAT(scheduler.GetPriorityFor(3), Optional(102)); EXPECT_EQ(scheduler.GetPriorityFor(5), std::nullopt); EXPECT_EQ(scheduler.NumScheduled(), 0u); EXPECT_FALSE(scheduler.HasScheduled()); QUICHE_EXPECT_OK(scheduler.Schedule(1)); QUICHE_EXPECT_OK(scheduler.Schedule(2)); QUICHE_EXPECT_OK(scheduler.Schedule(3)); EXPECT_EQ(scheduler.NumScheduled(), 3u); EXPECT_TRUE(scheduler.HasScheduled()); EXPECT_THAT(scheduler.PopFront(), IsOkAndHolds(3)); EXPECT_THAT(scheduler.PopFront(), IsOkAndHolds(2)); EXPECT_THAT(scheduler.PopFront(), IsOkAndHolds(1)); QUICHE_EXPECT_OK(scheduler.Schedule(2)); QUICHE_EXPECT_OK(scheduler.Schedule(1)); QUICHE_EXPECT_OK(scheduler.Schedule(3)); EXPECT_THAT(scheduler.PopFront(), IsOkAndHolds(3)); EXPECT_THAT(scheduler.PopFront(), IsOkAndHolds(2)); EXPECT_THAT(scheduler.PopFront(), IsOkAndHolds(1)); QUICHE_EXPECT_OK(scheduler.Schedule(3)); QUICHE_EXPECT_OK(scheduler.Schedule(1)); EXPECT_THAT(scheduler.PopFront(), IsOkAndHolds(3)); EXPECT_THAT(scheduler.PopFront(), IsOkAndHolds(1)); } TEST(BTreeSchedulerTest, FIFO) { BTreeScheduler<int, int> scheduler; QUICHE_EXPECT_OK(scheduler.Register(1, 100)); QUICHE_EXPECT_OK(scheduler.Register(2, 100)); QUICHE_EXPECT_OK(scheduler.Register(3, 100)); ScheduleIds(scheduler, {2, 1, 3}); EXPECT_THAT(PopAll(scheduler), ElementsAre(2, 1, 3)); QUICHE_EXPECT_OK(scheduler.Register(4, 101)); QUICHE_EXPECT_OK(scheduler.Register(5, 99)); ScheduleIds(scheduler, {5, 1, 2, 3, 4}); EXPECT_THAT(PopAll(scheduler), ElementsAre(4, 1, 2, 3, 5)); ScheduleIds(scheduler, {1, 5, 2, 4, 3}); EXPECT_THAT(PopAll(scheduler), ElementsAre(4, 1, 2, 3, 5)); ScheduleIds(scheduler, {3, 5, 2, 4, 1}); EXPECT_THAT(PopAll(scheduler), ElementsAre(4, 3, 2, 1, 5)); ScheduleIds(scheduler, {3, 2, 1, 2, 3}); EXPECT_THAT(PopAll(scheduler), ElementsAre(3, 2, 1)); } TEST(BTreeSchedulerTest, NumEntriesInRange) { BTreeScheduler<int, int> scheduler; QUICHE_EXPECT_OK(scheduler.Register(1, 0)); QUICHE_EXPECT_OK(scheduler.Register(2, 0)); QUICHE_EXPECT_OK(scheduler.Register(3, 0)); QUICHE_EXPECT_OK(scheduler.Register(4, -2)); QUICHE_EXPECT_OK(scheduler.Register(5, -5)); QUICHE_EXPECT_OK(scheduler.Register(6, 10)); QUICHE_EXPECT_OK(scheduler.Register(7, 16)); QUICHE_EXPECT_OK(scheduler.Register(8, 32)); QUICHE_EXPECT_OK(scheduler.Register(9, 64)); EXPECT_EQ(scheduler.NumScheduled(), 0u); EXPECT_EQ(scheduler.NumScheduledInPriorityRange(std::nullopt, std::nullopt), 0u); EXPECT_EQ(scheduler.NumScheduledInPriorityRange(-1, 1), 0u); for (int stream = 1; stream <= 9; ++stream) { QUICHE_ASSERT_OK(scheduler.Schedule(stream)); } EXPECT_EQ(scheduler.NumScheduled(), 9u); EXPECT_EQ(scheduler.NumScheduledInPriorityRange(std::nullopt, std::nullopt), 9u); EXPECT_EQ(scheduler.NumScheduledInPriorityRange(0, 0), 3u); EXPECT_EQ(scheduler.NumScheduledInPriorityRange(std::nullopt, -1), 2u); EXPECT_EQ(scheduler.NumScheduledInPriorityRange(1, std::nullopt), 4u); } TEST(BTreeSchedulerTest, Registration) { BTreeScheduler<int, int> scheduler; QUICHE_EXPECT_OK(scheduler.Register(1, 0)); QUICHE_EXPECT_OK(scheduler.Register(2, 0)); QUICHE_EXPECT_OK(scheduler.Schedule(1)); QUICHE_EXPECT_OK(scheduler.Schedule(2)); EXPECT_EQ(scheduler.NumScheduled(), 2u); EXPECT_TRUE(scheduler.IsScheduled(2)); EXPECT_THAT(scheduler.Register(2, 0), StatusIs(absl::StatusCode::kAlreadyExists)); QUICHE_EXPECT_OK(scheduler.Unregister(2)); EXPECT_EQ(scheduler.NumScheduled(), 1u); EXPECT_FALSE(scheduler.IsScheduled(2)); EXPECT_THAT(scheduler.UpdatePriority(2, 1234), StatusIs(absl::StatusCode::kNotFound)); EXPECT_THAT(scheduler.Unregister(2), StatusIs(absl::StatusCode::kNotFound)); EXPECT_THAT(scheduler.Schedule(2), StatusIs(absl::StatusCode::kNotFound)); QUICHE_EXPECT_OK(scheduler.Register(2, 0)); EXPECT_EQ(scheduler.NumScheduled(), 1u); EXPECT_TRUE(scheduler.IsScheduled(1)); EXPECT_FALSE(scheduler.IsScheduled(2)); } TEST(BTreeSchedulerTest, UpdatePriorityUp) { BTreeScheduler<int, int> scheduler; QUICHE_EXPECT_OK(scheduler.Register(1, 0)); QUICHE_EXPECT_OK(scheduler.Register(2, 0)); QUICHE_EXPECT_OK(scheduler.Register(3, 0)); ScheduleIds(scheduler, {1, 2, 3}); QUICHE_EXPECT_OK(scheduler.UpdatePriority(2, 1000)); EXPECT_THAT(PopAll(scheduler), ElementsAre(2, 1, 3)); } TEST(BTreeSchedulerTest, UpdatePriorityDown) { BTreeScheduler<int, int> scheduler; QUICHE_EXPECT_OK(scheduler.Register(1, 0)); QUICHE_EXPECT_OK(scheduler.Register(2, 0)); QUICHE_EXPECT_OK(scheduler.Register(3, 0)); ScheduleIds(scheduler, {1, 2, 3}); QUICHE_EXPECT_OK(scheduler.UpdatePriority(2, -1000)); EXPECT_THAT(PopAll(scheduler), ElementsAre(1, 3, 2)); } TEST(BTreeSchedulerTest, UpdatePriorityEqual) { BTreeScheduler<int, int> scheduler; QUICHE_EXPECT_OK(scheduler.Register(1, 0)); QUICHE_EXPECT_OK(scheduler.Register(2, 0)); QUICHE_EXPECT_OK(scheduler.Register(3, 0)); ScheduleIds(scheduler, {1, 2, 3}); QUICHE_EXPECT_OK(scheduler.UpdatePriority(2, 0)); EXPECT_THAT(PopAll(scheduler), ElementsAre(1, 2, 3)); } TEST(BTreeSchedulerTest, UpdatePriorityIntoSameBucket) { BTreeScheduler<int, int> scheduler; QUICHE_EXPECT_OK(scheduler.Register(1, 0)); QUICHE_EXPECT_OK(scheduler.Register(2, -100)); QUICHE_EXPECT_OK(scheduler.Register(3, 0)); ScheduleIds(scheduler, {1, 2, 3}); QUICHE_EXPECT_OK(scheduler.UpdatePriority(2, 0)); EXPECT_THAT(PopAll(scheduler), ElementsAre(1, 2, 3)); } TEST(BTreeSchedulerTest, ShouldYield) { BTreeScheduler<int, int> scheduler; QUICHE_EXPECT_OK(scheduler.Register(10, 100)); QUICHE_EXPECT_OK(scheduler.Register(20, 101)); QUICHE_EXPECT_OK(scheduler.Register(21, 101)); QUICHE_EXPECT_OK(scheduler.Register(30, 102)); EXPECT_THAT(scheduler.ShouldYield(10), IsOkAndHolds(false)); EXPECT_THAT(scheduler.ShouldYield(20), IsOkAndHolds(false)); EXPECT_THAT(scheduler.ShouldYield(21), IsOkAndHolds(false)); EXPECT_THAT(scheduler.ShouldYield(30), IsOkAndHolds(false)); EXPECT_THAT(scheduler.ShouldYield(40), StatusIs(absl::StatusCode::kNotFound)); QUICHE_EXPECT_OK(scheduler.Schedule(20)); EXPECT_THAT(scheduler.ShouldYield(10), IsOkAndHolds(true)); EXPECT_THAT(scheduler.ShouldYield(20), IsOkAndHolds(false)); EXPECT_THAT(scheduler.ShouldYield(21), IsOkAndHolds(true)); EXPECT_THAT(scheduler.ShouldYield(30), IsOkAndHolds(false)); } struct CustomPriority { int a; int b; bool operator<(const CustomPriority& other) const { return std::make_tuple(a, b) < std::make_tuple(other.a, other.b); } }; TEST(BTreeSchedulerTest, CustomPriority) { BTreeScheduler<int, CustomPriority> scheduler; QUICHE_EXPECT_OK(scheduler.Register(10, CustomPriority{0, 1})); QUICHE_EXPECT_OK(scheduler.Register(11, CustomPriority{0, 0})); QUICHE_EXPECT_OK(scheduler.Register(12, CustomPriority{0, 0})); QUICHE_EXPECT_OK(scheduler.Register(13, CustomPriority{10, 0})); QUICHE_EXPECT_OK(scheduler.Register(14, CustomPriority{-10, 0})); ScheduleIds(scheduler, {10, 11, 12, 13, 14}); EXPECT_THAT(PopAll(scheduler), ElementsAre(13, 10, 11, 12, 14)); } struct CustomId { int a; std::string b; bool operator==(const CustomId& other) const { return a == other.a && b == other.b; } template <typename H> friend H AbslHashValue(H h, const CustomId& c) { return H::combine(std::move(h), c.a, c.b); } }; std::ostream& operator<<(std::ostream& os, const CustomId& id) { os << id.a << ":" << id.b; return os; } TEST(BTreeSchedulerTest, CustomIds) { BTreeScheduler<CustomId, int> scheduler; QUICHE_EXPECT_OK(scheduler.Register(CustomId{1, "foo"}, 10)); QUICHE_EXPECT_OK(scheduler.Register(CustomId{1, "bar"}, 12)); QUICHE_EXPECT_OK(scheduler.Register(CustomId{2, "foo"}, 11)); EXPECT_THAT(scheduler.Register(CustomId{1, "foo"}, 10), StatusIs(absl::StatusCode::kAlreadyExists)); ScheduleIds(scheduler, {CustomId{1, "foo"}, CustomId{1, "bar"}, CustomId{2, "foo"}}); EXPECT_THAT(scheduler.ShouldYield(CustomId{1, "foo"}), IsOkAndHolds(true)); EXPECT_THAT(scheduler.ShouldYield(CustomId{1, "bar"}), IsOkAndHolds(false)); EXPECT_THAT( PopAll(scheduler), ElementsAre(CustomId{1, "bar"}, CustomId{2, "foo"}, CustomId{1, "foo"})); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/btree_scheduler.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/btree_scheduler_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
e8a55d3f-1b98-427c-b0aa-d6b46c411ffd
cpp
google/quiche
quiche_linked_hash_map
quiche/common/quiche_linked_hash_map.h
quiche/common/quiche_linked_hash_map_test.cc
#ifndef QUICHE_COMMON_QUICHE_LINKED_HASH_MAP_H_ #define QUICHE_COMMON_QUICHE_LINKED_HASH_MAP_H_ #include <functional> #include <list> #include <tuple> #include <type_traits> #include <utility> #include "absl/container/flat_hash_map.h" #include "absl/hash/hash.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quiche { template <class Key, class Value, class Hash = absl::Hash<Key>, class Eq = std::equal_to<Key>> class QuicheLinkedHashMap { private: typedef std::list<std::pair<Key, Value>> ListType; typedef absl::flat_hash_map<Key, typename ListType::iterator, Hash, Eq> MapType; public: typedef typename ListType::iterator iterator; typedef typename ListType::reverse_iterator reverse_iterator; typedef typename ListType::const_iterator const_iterator; typedef typename ListType::const_reverse_iterator const_reverse_iterator; typedef typename MapType::key_type key_type; typedef typename ListType::value_type value_type; typedef typename ListType::size_type size_type; QuicheLinkedHashMap() = default; explicit QuicheLinkedHashMap(size_type bucket_count) : map_(bucket_count) {} QuicheLinkedHashMap(const QuicheLinkedHashMap& other) = delete; QuicheLinkedHashMap& operator=(const QuicheLinkedHashMap& other) = delete; QuicheLinkedHashMap(QuicheLinkedHashMap&& other) = default; QuicheLinkedHashMap& operator=(QuicheLinkedHashMap&& other) = default; iterator begin() { return list_.begin(); } const_iterator begin() const { return list_.begin(); } iterator end() { return list_.end(); } const_iterator end() const { return list_.end(); } reverse_iterator rbegin() { return list_.rbegin(); } const_reverse_iterator rbegin() const { return list_.rbegin(); } reverse_iterator rend() { return list_.rend(); } const_reverse_iterator rend() const { return list_.rend(); } const value_type& front() const { return list_.front(); } value_type& front() { return list_.front(); } const value_type& back() const { return list_.back(); } value_type& back() { return list_.back(); } void clear() { map_.clear(); list_.clear(); } bool empty() const { return list_.empty(); } void pop_front() { erase(begin()); } size_type erase(const Key& key) { typename MapType::iterator found = map_.find(key); if (found == map_.end()) { return 0; } list_.erase(found->second); map_.erase(found); return 1; } iterator erase(iterator position) { typename MapType::iterator found = map_.find(position->first); QUICHE_CHECK(found->second == position) << "Inconsistent iterator for map and list, or the iterator is " "invalid."; map_.erase(found); return list_.erase(position); } iterator erase(iterator first, iterator last) { while (first != last && first != end()) { first = erase(first); } return first; } iterator find(const Key& key) { typename MapType::iterator found = map_.find(key); if (found == map_.end()) { return end(); } return found->second; } const_iterator find(const Key& key) const { typename MapType::const_iterator found = map_.find(key); if (found == map_.end()) { return end(); } return found->second; } bool contains(const Key& key) const { return find(key) != end(); } Value& operator[](const key_type& key) { return (*((this->insert(std::make_pair(key, Value()))).first)).second; } std::pair<iterator, bool> insert(const std::pair<Key, Value>& pair) { return InsertInternal(pair); } std::pair<iterator, bool> insert(std::pair<Key, Value>&& pair) { return InsertInternal(std::move(pair)); } size_type size() const { return map_.size(); } template <typename... Args> std::pair<iterator, bool> emplace(Args&&... args) { ListType node_donor; auto node_pos = node_donor.emplace(node_donor.end(), std::forward<Args>(args)...); const auto& k = node_pos->first; auto ins = map_.insert({k, node_pos}); if (!ins.second) { return {ins.first->second, false}; } list_.splice(list_.end(), node_donor, node_pos); return {ins.first->second, true}; } void swap(QuicheLinkedHashMap& other) { map_.swap(other.map_); list_.swap(other.list_); } private: template <typename U> std::pair<iterator, bool> InsertInternal(U&& pair) { auto insert_result = map_.try_emplace(pair.first); auto map_iter = insert_result.first; if (!insert_result.second) { return {map_iter->second, false}; } auto list_iter = list_.insert(list_.end(), std::forward<U>(pair)); map_iter->second = list_iter; return {list_iter, true}; } MapType map_; ListType list_; }; } #endif
#include "quiche/common/quiche_linked_hash_map.h" #include <memory> #include <tuple> #include <utility> #include "quiche/common/platform/api/quiche_test.h" using testing::Pair; using testing::Pointee; using testing::UnorderedElementsAre; namespace quiche { namespace test { TEST(LinkedHashMapTest, Move) { QuicheLinkedHashMap<int, std::unique_ptr<int>> m; m[2] = std::make_unique<int>(12); m[3] = std::make_unique<int>(13); QuicheLinkedHashMap<int, std::unique_ptr<int>> n = std::move(m); EXPECT_THAT(n, UnorderedElementsAre(Pair(2, Pointee(12)), Pair(3, Pointee(13)))); } TEST(LinkedHashMapTest, CanEmplaceMoveOnly) { QuicheLinkedHashMap<int, std::unique_ptr<int>> m; struct Data { int k, v; }; const Data data[] = {{1, 123}, {3, 345}, {2, 234}, {4, 456}}; for (const auto& kv : data) { m.emplace(std::piecewise_construct, std::make_tuple(kv.k), std::make_tuple(new int{kv.v})); } EXPECT_TRUE(m.contains(2)); auto found = m.find(2); ASSERT_TRUE(found != m.end()); EXPECT_EQ(234, *found->second); } struct NoCopy { explicit NoCopy(int x) : x(x) {} NoCopy(const NoCopy&) = delete; NoCopy& operator=(const NoCopy&) = delete; NoCopy(NoCopy&&) = delete; NoCopy& operator=(NoCopy&&) = delete; int x; }; TEST(LinkedHashMapTest, CanEmplaceNoMoveNoCopy) { QuicheLinkedHashMap<int, NoCopy> m; struct Data { int k, v; }; const Data data[] = {{1, 123}, {3, 345}, {2, 234}, {4, 456}}; for (const auto& kv : data) { m.emplace(std::piecewise_construct, std::make_tuple(kv.k), std::make_tuple(kv.v)); } EXPECT_TRUE(m.contains(2)); auto found = m.find(2); ASSERT_TRUE(found != m.end()); EXPECT_EQ(234, found->second.x); } TEST(LinkedHashMapTest, ConstKeys) { QuicheLinkedHashMap<int, int> m; m.insert(std::make_pair(1, 2)); std::pair<int, int>& p = *m.begin(); EXPECT_EQ(1, p.first); } TEST(LinkedHashMapTest, Iteration) { QuicheLinkedHashMap<int, int> m; EXPECT_TRUE(m.begin() == m.end()); m.insert(std::make_pair(2, 12)); m.insert(std::make_pair(1, 11)); m.insert(std::make_pair(3, 13)); QuicheLinkedHashMap<int, int>::iterator i = m.begin(); ASSERT_TRUE(m.begin() == i); ASSERT_TRUE(m.end() != i); EXPECT_EQ(2, i->first); EXPECT_EQ(12, i->second); ++i; ASSERT_TRUE(m.end() != i); EXPECT_EQ(1, i->first); EXPECT_EQ(11, i->second); ++i; ASSERT_TRUE(m.end() != i); EXPECT_EQ(3, i->first); EXPECT_EQ(13, i->second); ++i; ASSERT_TRUE(m.end() == i); } TEST(LinkedHashMapTest, ReverseIteration) { QuicheLinkedHashMap<int, int> m; EXPECT_TRUE(m.rbegin() == m.rend()); m.insert(std::make_pair(2, 12)); m.insert(std::make_pair(1, 11)); m.insert(std::make_pair(3, 13)); QuicheLinkedHashMap<int, int>::reverse_iterator i = m.rbegin(); ASSERT_TRUE(m.rbegin() == i); ASSERT_TRUE(m.rend() != i); EXPECT_EQ(3, i->first); EXPECT_EQ(13, i->second); ++i; ASSERT_TRUE(m.rend() != i); EXPECT_EQ(1, i->first); EXPECT_EQ(11, i->second); ++i; ASSERT_TRUE(m.rend() != i); EXPECT_EQ(2, i->first); EXPECT_EQ(12, i->second); ++i; ASSERT_TRUE(m.rend() == i); } TEST(LinkedHashMapTest, Clear) { QuicheLinkedHashMap<int, int> m; m.insert(std::make_pair(2, 12)); m.insert(std::make_pair(1, 11)); m.insert(std::make_pair(3, 13)); ASSERT_EQ(3u, m.size()); m.clear(); EXPECT_EQ(0u, m.size()); m.clear(); EXPECT_EQ(0u, m.size()); } TEST(LinkedHashMapTest, Size) { QuicheLinkedHashMap<int, int> m; EXPECT_EQ(0u, m.size()); m.insert(std::make_pair(2, 12)); EXPECT_EQ(1u, m.size()); m.insert(std::make_pair(1, 11)); EXPECT_EQ(2u, m.size()); m.insert(std::make_pair(3, 13)); EXPECT_EQ(3u, m.size()); m.clear(); EXPECT_EQ(0u, m.size()); } TEST(LinkedHashMapTest, Empty) { QuicheLinkedHashMap<int, int> m; ASSERT_TRUE(m.empty()); m.insert(std::make_pair(2, 12)); ASSERT_FALSE(m.empty()); m.clear(); ASSERT_TRUE(m.empty()); } TEST(LinkedHashMapTest, Erase) { QuicheLinkedHashMap<int, int> m; ASSERT_EQ(0u, m.size()); EXPECT_EQ(0u, m.erase(2)); m.insert(std::make_pair(2, 12)); ASSERT_EQ(1u, m.size()); EXPECT_EQ(1u, m.erase(2)); EXPECT_EQ(0u, m.size()); EXPECT_EQ(0u, m.erase(2)); EXPECT_EQ(0u, m.size()); } TEST(LinkedHashMapTest, Erase2) { QuicheLinkedHashMap<int, int> m; ASSERT_EQ(0u, m.size()); EXPECT_EQ(0u, m.erase(2)); m.insert(std::make_pair(2, 12)); m.insert(std::make_pair(1, 11)); m.insert(std::make_pair(3, 13)); m.insert(std::make_pair(4, 14)); ASSERT_EQ(4u, m.size()); EXPECT_EQ(1u, m.erase(1)); EXPECT_EQ(1u, m.erase(3)); EXPECT_EQ(2u, m.size()); QuicheLinkedHashMap<int, int>::iterator it = m.begin(); ASSERT_TRUE(it != m.end()); EXPECT_EQ(12, it->second); ++it; ASSERT_TRUE(it != m.end()); EXPECT_EQ(14, it->second); ++it; ASSERT_TRUE(it == m.end()); EXPECT_EQ(0u, m.erase(1)); ASSERT_EQ(2u, m.size()); EXPECT_EQ(1u, m.erase(2)); EXPECT_EQ(1u, m.erase(4)); ASSERT_EQ(0u, m.size()); EXPECT_EQ(0u, m.erase(1)); ASSERT_EQ(0u, m.size()); } TEST(LinkedHashMapTest, Erase3) { QuicheLinkedHashMap<int, int> m; m.insert(std::make_pair(1, 11)); m.insert(std::make_pair(2, 12)); m.insert(std::make_pair(3, 13)); m.insert(std::make_pair(4, 14)); QuicheLinkedHashMap<int, int>::iterator it2 = m.find(2); QuicheLinkedHashMap<int, int>::iterator it4 = m.find(4); EXPECT_EQ(m.erase(it2, it4), m.find(4)); EXPECT_EQ(2u, m.size()); QuicheLinkedHashMap<int, int>::iterator it = m.begin(); ASSERT_TRUE(it != m.end()); EXPECT_EQ(11, it->second); ++it; ASSERT_TRUE(it != m.end()); EXPECT_EQ(14, it->second); ++it; ASSERT_TRUE(it == m.end()); EXPECT_EQ(m.erase(m.begin()), m.find(4)); it = m.begin(); ASSERT_TRUE(it != m.end()); EXPECT_EQ(14, it->second); ++it; ASSERT_TRUE(it == m.end()); } TEST(LinkedHashMapTest, Insertion) { QuicheLinkedHashMap<int, int> m; ASSERT_EQ(0u, m.size()); std::pair<QuicheLinkedHashMap<int, int>::iterator, bool> result; result = m.insert(std::make_pair(2, 12)); ASSERT_EQ(1u, m.size()); EXPECT_TRUE(result.second); EXPECT_EQ(2, result.first->first); EXPECT_EQ(12, result.first->second); result = m.insert(std::make_pair(1, 11)); ASSERT_EQ(2u, m.size()); EXPECT_TRUE(result.second); EXPECT_EQ(1, result.first->first); EXPECT_EQ(11, result.first->second); result = m.insert(std::make_pair(3, 13)); QuicheLinkedHashMap<int, int>::iterator result_iterator = result.first; ASSERT_EQ(3u, m.size()); EXPECT_TRUE(result.second); EXPECT_EQ(3, result.first->first); EXPECT_EQ(13, result.first->second); result = m.insert(std::make_pair(3, 13)); EXPECT_EQ(3u, m.size()); EXPECT_FALSE(result.second) << "No insertion should have occurred."; EXPECT_TRUE(result_iterator == result.first) << "Duplicate insertion should have given us the original iterator."; } static std::pair<int, int> Pair(int i, int j) { return {i, j}; } TEST(LinkedHashMapTest, Front) { QuicheLinkedHashMap<int, int> m; m.insert(std::make_pair(2, 12)); m.insert(std::make_pair(1, 11)); m.insert(std::make_pair(3, 13)); EXPECT_EQ(3u, m.size()); EXPECT_EQ(Pair(2, 12), m.front()); m.pop_front(); EXPECT_EQ(2u, m.size()); EXPECT_EQ(Pair(1, 11), m.front()); m.pop_front(); EXPECT_EQ(1u, m.size()); EXPECT_EQ(Pair(3, 13), m.front()); m.pop_front(); EXPECT_TRUE(m.empty()); } TEST(LinkedHashMapTest, Find) { QuicheLinkedHashMap<int, int> m; EXPECT_TRUE(m.end() == m.find(1)) << "We shouldn't find anything in an empty map."; m.insert(std::make_pair(2, 12)); EXPECT_TRUE(m.end() == m.find(1)) << "We shouldn't find an element that doesn't exist in the map."; std::pair<QuicheLinkedHashMap<int, int>::iterator, bool> result = m.insert(std::make_pair(1, 11)); ASSERT_TRUE(result.second); ASSERT_TRUE(m.end() != result.first); EXPECT_TRUE(result.first == m.find(1)) << "We should have found an element we know exists in the map."; EXPECT_EQ(11, result.first->second); m.insert(std::make_pair(3, 13)); QuicheLinkedHashMap<int, int>::iterator it = m.find(1); ASSERT_TRUE(m.end() != it); EXPECT_EQ(11, it->second); m.clear(); EXPECT_TRUE(m.end() == m.find(1)) << "We shouldn't find anything in a map that we've cleared."; } TEST(LinkedHashMapTest, Contains) { QuicheLinkedHashMap<int, int> m; EXPECT_FALSE(m.contains(1)) << "An empty map shouldn't contain anything."; m.insert(std::make_pair(2, 12)); EXPECT_FALSE(m.contains(1)) << "The map shouldn't contain an element that doesn't exist."; m.insert(std::make_pair(1, 11)); EXPECT_TRUE(m.contains(1)) << "The map should contain an element that we know exists."; m.clear(); EXPECT_FALSE(m.contains(1)) << "A map that we've cleared shouldn't contain anything."; } TEST(LinkedHashMapTest, Swap) { QuicheLinkedHashMap<int, int> m1; QuicheLinkedHashMap<int, int> m2; m1.insert(std::make_pair(1, 1)); m1.insert(std::make_pair(2, 2)); m2.insert(std::make_pair(3, 3)); ASSERT_EQ(2u, m1.size()); ASSERT_EQ(1u, m2.size()); m1.swap(m2); ASSERT_EQ(1u, m1.size()); ASSERT_EQ(2u, m2.size()); } TEST(LinkedHashMapTest, CustomHashAndEquality) { struct CustomIntHash { size_t operator()(int x) const { return x; } }; QuicheLinkedHashMap<int, int, CustomIntHash> m; m.insert(std::make_pair(1, 1)); EXPECT_TRUE(m.contains(1)); EXPECT_EQ(1, m[1]); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/quiche_linked_hash_map.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/quiche_linked_hash_map_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
578789e4-5367-4156-8c17-19fde5e0ba5e
cpp
google/quiche
lifetime_tracking
quiche/common/lifetime_tracking.h
quiche/common/lifetime_tracking_test.cc
#ifndef QUICHE_COMMON_LIFETIME_TRACKING_H_ #define QUICHE_COMMON_LIFETIME_TRACKING_H_ #include <memory> #include <optional> #include <utility> #include <vector> #include "absl/strings/str_format.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_stack_trace.h" namespace quiche { namespace test { class LifetimeTrackingTest; } struct QUICHE_EXPORT LifetimeInfo { bool IsDead() const { return destructor_stack.has_value(); } std::optional<std::vector<void*>> destructor_stack; }; class QUICHE_EXPORT LifetimeTracker { public: LifetimeTracker(const LifetimeTracker& other) { CopyFrom(other); } LifetimeTracker& operator=(const LifetimeTracker& other) { CopyFrom(other); return *this; } LifetimeTracker(LifetimeTracker&& other) { CopyFrom(other); } LifetimeTracker& operator=(LifetimeTracker&& other) { CopyFrom(other); return *this; } bool IsTrackedObjectDead() const { return info_->IsDead(); } template <typename Sink> friend void AbslStringify(Sink& sink, const LifetimeTracker& tracker) { if (tracker.info_->IsDead()) { absl::Format(&sink, "Tracked object has died with %v", SymbolizeStackTrace(*tracker.info_->destructor_stack)); } else { absl::Format(&sink, "Tracked object is alive."); } } private: friend class LifetimeTrackable; explicit LifetimeTracker(std::shared_ptr<const LifetimeInfo> info) : info_(std::move(info)) { QUICHE_CHECK(info_ != nullptr) << "Passed a null info pointer into the lifetime tracker"; } void CopyFrom(const LifetimeTracker& other) { info_ = other.info_; } std::shared_ptr<const LifetimeInfo> info_; }; class QUICHE_EXPORT LifetimeTrackable { public: LifetimeTrackable() = default; virtual ~LifetimeTrackable() { if (info_ != nullptr) { info_->destructor_stack = CurrentStackTrace(); } } LifetimeTrackable(const LifetimeTrackable&) : LifetimeTrackable() {} LifetimeTrackable& operator=(const LifetimeTrackable&) { return *this; } LifetimeTrackable(LifetimeTrackable&&) : LifetimeTrackable() {} LifetimeTrackable& operator=(LifetimeTrackable&&) { return *this; } LifetimeTracker NewTracker() { if (info_ == nullptr) { info_ = std::make_shared<LifetimeInfo>(); } return LifetimeTracker(info_); } private: friend class test::LifetimeTrackingTest; std::shared_ptr<LifetimeInfo> info_; }; } #endif
#include "quiche/common/lifetime_tracking.h" #include <memory> #include <string> #include <utility> #include <vector> #include "absl/strings/str_cat.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" namespace quiche { namespace test { struct ComposedTrackable { LifetimeTrackable trackable; }; struct InheritedTrackable : LifetimeTrackable {}; enum class TrackableType { kComposed, kInherited, }; std::string PrintToString(const TrackableType& type) { switch (type) { case TrackableType::kComposed: return "Composed"; case TrackableType::kInherited: return "Inherited"; default: QUICHE_LOG(FATAL) << "Unknown TrackableType: " << static_cast<int>(type); } } class LifetimeTrackingTest : public QuicheTestWithParam<TrackableType> { protected: LifetimeTrackingTest() { if (GetParam() == TrackableType::kComposed) { composed_trackable_ = std::make_unique<ComposedTrackable>(); } else { inherited_trackable_ = std::make_unique<InheritedTrackable>(); } } LifetimeTrackable& GetTrackable() { if (composed_trackable_ != nullptr) { return composed_trackable_->trackable; } else { return *inherited_trackable_; } } const std::shared_ptr<LifetimeInfo>& GetLifetimeInfoFromTrackable( LifetimeTrackable& trackable) { return trackable.info_; } const std::shared_ptr<LifetimeInfo>& GetLifetimeInfoFromTrackable() { return GetLifetimeInfoFromTrackable(GetTrackable()); } void FreeTrackable() { composed_trackable_ = nullptr; inherited_trackable_ = nullptr; } std::unique_ptr<ComposedTrackable> composed_trackable_; std::unique_ptr<InheritedTrackable> inherited_trackable_; }; TEST_P(LifetimeTrackingTest, TrackableButNeverTracked) { EXPECT_EQ(GetLifetimeInfoFromTrackable(), nullptr); } TEST_P(LifetimeTrackingTest, SingleTrackerQueryLiveness) { LifetimeTracker tracker = GetTrackable().NewTracker(); EXPECT_FALSE(tracker.IsTrackedObjectDead()); EXPECT_THAT(absl::StrCat(tracker), testing::HasSubstr("Tracked object is alive")); FreeTrackable(); EXPECT_TRUE(tracker.IsTrackedObjectDead()); EXPECT_THAT(absl::StrCat(tracker), testing::HasSubstr("Tracked object has died")); } TEST_P(LifetimeTrackingTest, MultiTrackersQueryLiveness) { LifetimeTracker tracker1 = GetTrackable().NewTracker(); LifetimeTracker tracker2 = GetTrackable().NewTracker(); LifetimeTracker tracker3 = tracker2; LifetimeTracker tracker4 = std::move(tracker3); LifetimeTracker tracker5(std::move(tracker4)); LifetimeTrackable another_trackable; LifetimeTracker tracker6 = another_trackable.NewTracker(); LifetimeTracker tracker7 = another_trackable.NewTracker(); tracker6 = tracker2; tracker7 = std::move(tracker2); EXPECT_FALSE(tracker1.IsTrackedObjectDead()); EXPECT_FALSE( tracker2.IsTrackedObjectDead()); EXPECT_FALSE( tracker3.IsTrackedObjectDead()); EXPECT_FALSE( tracker4.IsTrackedObjectDead()); EXPECT_FALSE(tracker5.IsTrackedObjectDead()); EXPECT_FALSE(tracker6.IsTrackedObjectDead()); EXPECT_FALSE(tracker7.IsTrackedObjectDead()); FreeTrackable(); EXPECT_TRUE(tracker1.IsTrackedObjectDead()); EXPECT_TRUE( tracker2.IsTrackedObjectDead()); EXPECT_TRUE( tracker3.IsTrackedObjectDead()); EXPECT_TRUE( tracker4.IsTrackedObjectDead()); EXPECT_TRUE(tracker5.IsTrackedObjectDead()); EXPECT_TRUE(tracker6.IsTrackedObjectDead()); EXPECT_TRUE(tracker7.IsTrackedObjectDead()); } TEST_P(LifetimeTrackingTest, CopyTrackableIsNoop) { LifetimeTracker tracker = GetTrackable().NewTracker(); const LifetimeInfo* info = GetLifetimeInfoFromTrackable().get(); EXPECT_NE(info, nullptr); LifetimeTrackable trackable2(GetTrackable()); EXPECT_EQ(GetLifetimeInfoFromTrackable(trackable2), nullptr); LifetimeTrackable trackable3; trackable3 = GetTrackable(); EXPECT_EQ(GetLifetimeInfoFromTrackable(trackable3), nullptr); EXPECT_EQ(GetLifetimeInfoFromTrackable().get(), info); } TEST_P(LifetimeTrackingTest, MoveTrackableIsNoop) { LifetimeTracker tracker = GetTrackable().NewTracker(); const LifetimeInfo* info = GetLifetimeInfoFromTrackable().get(); EXPECT_NE(info, nullptr); LifetimeTrackable trackable2(std::move(GetTrackable())); EXPECT_EQ(GetLifetimeInfoFromTrackable(trackable2), nullptr); LifetimeTrackable trackable3; trackable3 = std::move(GetTrackable()); EXPECT_EQ(GetLifetimeInfoFromTrackable(trackable3), nullptr); EXPECT_EQ(GetLifetimeInfoFromTrackable().get(), info); } TEST_P(LifetimeTrackingTest, ObjectDiedDueToVectorRealloc) { if (GetParam() == TrackableType::kComposed) { return; } std::vector<InheritedTrackable> trackables; InheritedTrackable& trackable = trackables.emplace_back(); LifetimeTracker tracker = trackable.NewTracker(); EXPECT_FALSE(tracker.IsTrackedObjectDead()); for (int i = 0; i < 1000; ++i) { trackables.emplace_back(); } EXPECT_TRUE(tracker.IsTrackedObjectDead()); } INSTANTIATE_TEST_SUITE_P(Tests, LifetimeTrackingTest, testing::Values(TrackableType::kComposed, TrackableType::kInherited), testing::PrintToStringParamName()); } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/lifetime_tracking.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/lifetime_tracking_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
a766a7d9-fcbf-441a-9870-f271207b1bd0
cpp
google/quiche
wire_serialization
quiche/common/wire_serialization.h
quiche/common/wire_serialization_test.cc
#ifndef QUICHE_COMMON_WIRE_SERIALIZATION_H_ #define QUICHE_COMMON_WIRE_SERIALIZATION_H_ #include <cstddef> #include <cstdint> #include <optional> #include <tuple> #include <type_traits> #include <utility> #include "absl/base/attributes.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_buffer_allocator.h" #include "quiche/common/quiche_data_writer.h" #include "quiche/common/quiche_status_utils.h" namespace quiche { template <typename T> class QUICHE_NO_EXPORT SerializeIntoWriterStatus { public: static_assert(std::is_trivially_copyable_v<T> && sizeof(T) <= 32, "The types passed into SerializeInto() APIs are passed by " "value; if your type has non-trivial copy costs, it should be " "wrapped into a type that carries a pointer"); using Type = decltype(std::declval<T>().SerializeIntoWriter( std::declval<QuicheDataWriter&>())); static constexpr bool kIsBool = std::is_same_v<Type, bool>; static constexpr bool kIsStatus = std::is_same_v<Type, absl::Status>; static_assert( kIsBool || kIsStatus, "SerializeIntoWriter() has to return either a bool or an absl::Status"); static ABSL_ATTRIBUTE_ALWAYS_INLINE Type OkValue() { if constexpr (kIsStatus) { return absl::OkStatus(); } else { return true; } } }; inline ABSL_ATTRIBUTE_ALWAYS_INLINE bool IsWriterStatusOk(bool status) { return status; } inline ABSL_ATTRIBUTE_ALWAYS_INLINE bool IsWriterStatusOk( const absl::Status& status) { return status.ok(); } template <typename T> class QUICHE_EXPORT WireFixedSizeIntBase { public: using DataType = T; static_assert(std::is_integral_v<DataType>, "WireFixedSizeIntBase is only usable with integral types"); explicit WireFixedSizeIntBase(T value) { value_ = value; } size_t GetLengthOnWire() const { return sizeof(T); } T value() const { return value_; } private: T value_; }; class QUICHE_EXPORT WireUint8 : public WireFixedSizeIntBase<uint8_t> { public: using WireFixedSizeIntBase::WireFixedSizeIntBase; bool SerializeIntoWriter(QuicheDataWriter& writer) const { return writer.WriteUInt8(value()); } }; class QUICHE_EXPORT WireUint16 : public WireFixedSizeIntBase<uint16_t> { public: using WireFixedSizeIntBase::WireFixedSizeIntBase; bool SerializeIntoWriter(QuicheDataWriter& writer) const { return writer.WriteUInt16(value()); } }; class QUICHE_EXPORT WireUint32 : public WireFixedSizeIntBase<uint32_t> { public: using WireFixedSizeIntBase::WireFixedSizeIntBase; bool SerializeIntoWriter(QuicheDataWriter& writer) const { return writer.WriteUInt32(value()); } }; class QUICHE_EXPORT WireUint64 : public WireFixedSizeIntBase<uint64_t> { public: using WireFixedSizeIntBase::WireFixedSizeIntBase; bool SerializeIntoWriter(QuicheDataWriter& writer) const { return writer.WriteUInt64(value()); } }; class QUICHE_EXPORT WireVarInt62 { public: using DataType = uint64_t; explicit WireVarInt62(uint64_t value) { value_ = value; } template <typename T> explicit WireVarInt62(T value) { static_assert(std::is_enum_v<T> || std::is_convertible_v<T, uint64_t>); value_ = static_cast<uint64_t>(value); } size_t GetLengthOnWire() const { return QuicheDataWriter::GetVarInt62Len(value_); } bool SerializeIntoWriter(QuicheDataWriter& writer) const { return writer.WriteVarInt62(value_); } private: uint64_t value_; }; class QUICHE_EXPORT WireBytes { public: using DataType = absl::string_view; explicit WireBytes(absl::string_view value) { value_ = value; } size_t GetLengthOnWire() { return value_.size(); } bool SerializeIntoWriter(QuicheDataWriter& writer) { return writer.WriteStringPiece(value_); } private: absl::string_view value_; }; template <class LengthWireType> class QUICHE_EXPORT WireStringWithLengthPrefix { public: using DataType = absl::string_view; explicit WireStringWithLengthPrefix(absl::string_view value) { value_ = value; } size_t GetLengthOnWire() { return LengthWireType(value_.size()).GetLengthOnWire() + value_.size(); } absl::Status SerializeIntoWriter(QuicheDataWriter& writer) { if (!LengthWireType(value_.size()).SerializeIntoWriter(writer)) { return absl::InternalError("Failed to serialize the length prefix"); } if (!writer.WriteStringPiece(value_)) { return absl::InternalError("Failed to serialize the string proper"); } return absl::OkStatus(); } private: absl::string_view value_; }; using WireStringWithVarInt62Length = WireStringWithLengthPrefix<WireVarInt62>; template <typename WireType, typename InnerType = typename WireType::DataType> class QUICHE_EXPORT WireOptional { public: using DataType = std::optional<InnerType>; using Status = SerializeIntoWriterStatus<WireType>; explicit WireOptional(DataType value) { value_ = value; } size_t GetLengthOnWire() const { return value_.has_value() ? WireType(*value_).GetLengthOnWire() : 0; } typename Status::Type SerializeIntoWriter(QuicheDataWriter& writer) const { if (value_.has_value()) { return WireType(*value_).SerializeIntoWriter(writer); } return Status::OkValue(); } private: DataType value_; }; template <typename WireType, typename SpanElementType = typename WireType::DataType> class QUICHE_EXPORT WireSpan { public: using DataType = absl::Span<const SpanElementType>; explicit WireSpan(DataType value) { value_ = value; } size_t GetLengthOnWire() const { size_t total = 0; for (const SpanElementType& value : value_) { total += WireType(value).GetLengthOnWire(); } return total; } absl::Status SerializeIntoWriter(QuicheDataWriter& writer) const { for (size_t i = 0; i < value_.size(); i++) { auto status = WireType(value_[i]).SerializeIntoWriter(writer); if (IsWriterStatusOk(status)) { continue; } if constexpr (SerializeIntoWriterStatus<WireType>::kIsStatus) { return AppendToStatus(std::move(status), " while serializing the value #", i); } else { return absl::InternalError( absl::StrCat("Failed to serialize vector value #", i)); } } return absl::OkStatus(); } private: DataType value_; }; namespace wire_serialization_internal { template <typename T> auto SerializeIntoWriterWrapper(QuicheDataWriter& writer, int argno, T data) { #if defined(NDEBUG) (void)argno; (void)data; return data.SerializeIntoWriter(writer); #else const size_t initial_offset = writer.length(); const size_t expected_size = data.GetLengthOnWire(); auto result = data.SerializeIntoWriter(writer); const size_t final_offset = writer.length(); if (IsWriterStatusOk(result)) { QUICHE_DCHECK_EQ(initial_offset + expected_size, final_offset) << "while serializing field #" << argno; } return result; #endif } template <typename T> std::enable_if_t<SerializeIntoWriterStatus<T>::kIsBool, absl::Status> SerializeIntoWriterCore(QuicheDataWriter& writer, int argno, T data) { const bool success = SerializeIntoWriterWrapper(writer, argno, data); if (!success) { return absl::InternalError( absl::StrCat("Failed to serialize field #", argno)); } return absl::OkStatus(); } template <typename T> std::enable_if_t<SerializeIntoWriterStatus<T>::kIsStatus, absl::Status> SerializeIntoWriterCore(QuicheDataWriter& writer, int argno, T data) { return AppendToStatus(SerializeIntoWriterWrapper(writer, argno, data), " while serializing field #", argno); } template <typename T1, typename... Ts> absl::Status SerializeIntoWriterCore(QuicheDataWriter& writer, int argno, T1 data1, Ts... rest) { QUICHE_RETURN_IF_ERROR(SerializeIntoWriterCore(writer, argno, data1)); return SerializeIntoWriterCore(writer, argno + 1, rest...); } inline absl::Status SerializeIntoWriterCore(QuicheDataWriter&, int) { return absl::OkStatus(); } } template <typename... Ts> absl::Status SerializeIntoWriter(QuicheDataWriter& writer, Ts... data) { return wire_serialization_internal::SerializeIntoWriterCore( writer, 0, data...); } template <typename T> size_t ComputeLengthOnWire(T data) { return data.GetLengthOnWire(); } template <typename T1, typename... Ts> size_t ComputeLengthOnWire(T1 data1, Ts... rest) { return data1.GetLengthOnWire() + ComputeLengthOnWire(rest...); } inline size_t ComputeLengthOnWire() { return 0; } template <typename... Ts> absl::StatusOr<QuicheBuffer> SerializeIntoBuffer( QuicheBufferAllocator* allocator, Ts... data) { size_t buffer_size = ComputeLengthOnWire(data...); if (buffer_size == 0) { return QuicheBuffer(); } QuicheBuffer buffer(allocator, buffer_size); QuicheDataWriter writer(buffer.size(), buffer.data()); QUICHE_RETURN_IF_ERROR(SerializeIntoWriter(writer, data...)); if (writer.remaining() != 0) { return absl::InternalError(absl::StrCat( "Excess ", writer.remaining(), " bytes allocated while serializing")); } return buffer; } template <typename... Ts> absl::StatusOr<std::string> SerializeIntoString(Ts... data) { size_t buffer_size = ComputeLengthOnWire(data...); if (buffer_size == 0) { return std::string(); } std::string buffer; buffer.resize(buffer_size); QuicheDataWriter writer(buffer.size(), buffer.data()); QUICHE_RETURN_IF_ERROR(SerializeIntoWriter(writer, data...)); if (writer.remaining() != 0) { return absl::InternalError(absl::StrCat( "Excess ", writer.remaining(), " bytes allocated while serializing")); } return buffer; } } #endif
#include "quiche/common/wire_serialization.h" #include <array> #include <limits> #include <optional> #include <string> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_expect_bug.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/quiche_buffer_allocator.h" #include "quiche/common/quiche_endian.h" #include "quiche/common/quiche_status_utils.h" #include "quiche/common/simple_buffer_allocator.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace quiche::test { namespace { using ::testing::ElementsAre; constexpr uint64_t kInvalidVarInt = std::numeric_limits<uint64_t>::max(); template <typename... Ts> absl::StatusOr<quiche::QuicheBuffer> SerializeIntoSimpleBuffer(Ts... data) { return SerializeIntoBuffer(quiche::SimpleBufferAllocator::Get(), data...); } template <typename... Ts> void ExpectEncoding(const std::string& description, absl::string_view expected, Ts... data) { absl::StatusOr<quiche::QuicheBuffer> actual = SerializeIntoSimpleBuffer(data...); QUICHE_ASSERT_OK(actual); quiche::test::CompareCharArraysWithHexError(description, actual->data(), actual->size(), expected.data(), expected.size()); } template <typename... Ts> void ExpectEncodingHex(const std::string& description, absl::string_view expected_hex, Ts... data) { std::string expected; ASSERT_TRUE(absl::HexStringToBytes(expected_hex, &expected)); ExpectEncoding(description, expected, data...); } TEST(SerializationTest, SerializeStrings) { absl::StatusOr<quiche::QuicheBuffer> one_string = SerializeIntoSimpleBuffer(WireBytes("test")); QUICHE_ASSERT_OK(one_string); EXPECT_EQ(one_string->AsStringView(), "test"); absl::StatusOr<quiche::QuicheBuffer> two_strings = SerializeIntoSimpleBuffer(WireBytes("Hello"), WireBytes("World")); QUICHE_ASSERT_OK(two_strings); EXPECT_EQ(two_strings->AsStringView(), "HelloWorld"); } TEST(SerializationTest, SerializeIntegers) { ExpectEncodingHex("one uint8_t value", "42", WireUint8(0x42)); ExpectEncodingHex("two uint8_t values", "ab01", WireUint8(0xab), WireUint8(0x01)); ExpectEncodingHex("one uint16_t value", "1234", WireUint16(0x1234)); ExpectEncodingHex("one uint32_t value", "12345678", WireUint32(0x12345678)); ExpectEncodingHex("one uint64_t value", "123456789abcdef0", WireUint64(UINT64_C(0x123456789abcdef0))); ExpectEncodingHex("mix of values", "aabbcc000000dd", WireUint8(0xaa), WireUint16(0xbbcc), WireUint32(0xdd)); } TEST(SerializationTest, SerializeLittleEndian) { char buffer[4]; QuicheDataWriter writer(sizeof(buffer), buffer, quiche::Endianness::HOST_BYTE_ORDER); QUICHE_ASSERT_OK( SerializeIntoWriter(writer, WireUint16(0x1234), WireUint16(0xabcd))); absl::string_view actual(writer.data(), writer.length()); std::string expected; ASSERT_TRUE(absl::HexStringToBytes("3412cdab", &expected)); EXPECT_EQ(actual, expected); } TEST(SerializationTest, SerializeVarInt62) { ExpectEncodingHex("1-byte varint", "25", WireVarInt62(37)); ExpectEncodingHex("2-byte varint", "7bbd", WireVarInt62(15293)); ExpectEncodingHex("4-byte varint", "9d7f3e7d", WireVarInt62(494878333)); ExpectEncodingHex("8-byte varint", "c2197c5eff14e88c", WireVarInt62(UINT64_C(151288809941952652))); } TEST(SerializationTest, SerializeStringWithVarInt62Length) { ExpectEncodingHex("short string", "0474657374", WireStringWithVarInt62Length("test")); const std::string long_string(15293, 'a'); ExpectEncoding("long string", absl::StrCat("\x7b\xbd", long_string), WireStringWithVarInt62Length(long_string)); ExpectEncodingHex("empty string", "00", WireStringWithVarInt62Length("")); } TEST(SerializationTest, SerializeOptionalValues) { std::optional<uint8_t> has_no_value; std::optional<uint8_t> has_value = 0x42; ExpectEncodingHex("optional without value", "00", WireUint8(0), WireOptional<WireUint8>(has_no_value)); ExpectEncodingHex("optional with value", "0142", WireUint8(1), WireOptional<WireUint8>(has_value)); ExpectEncodingHex("empty data", "", WireOptional<WireUint8>(has_no_value)); std::optional<std::string> has_no_string; std::optional<std::string> has_string = "\x42"; ExpectEncodingHex("optional no string", "", WireOptional<WireStringWithVarInt62Length>(has_no_string)); ExpectEncodingHex("optional string", "0142", WireOptional<WireStringWithVarInt62Length>(has_string)); } enum class TestEnum { kValue1 = 0x17, kValue2 = 0x19, }; TEST(SerializationTest, SerializeEnumValue) { ExpectEncodingHex("enum value", "17", WireVarInt62(TestEnum::kValue1)); } TEST(SerializationTest, SerializeLotsOfValues) { ExpectEncodingHex("ten values", "00010203040506070809", WireUint8(0), WireUint8(1), WireUint8(2), WireUint8(3), WireUint8(4), WireUint8(5), WireUint8(6), WireUint8(7), WireUint8(8), WireUint8(9)); } TEST(SerializationTest, FailDueToLackOfSpace) { char buffer[4]; QuicheDataWriter writer(sizeof(buffer), buffer); QUICHE_EXPECT_OK(SerializeIntoWriter(writer, WireUint32(0))); ASSERT_EQ(writer.remaining(), 0u); EXPECT_THAT( SerializeIntoWriter(writer, WireUint32(0)), StatusIs(absl::StatusCode::kInternal, "Failed to serialize field #0")); EXPECT_THAT( SerializeIntoWriter(writer, WireStringWithVarInt62Length("test")), StatusIs( absl::StatusCode::kInternal, "Failed to serialize the length prefix while serializing field #0")); } TEST(SerializationTest, FailDueToInvalidValue) { EXPECT_QUICHE_BUG( ExpectEncoding("invalid varint", "", WireVarInt62(kInvalidVarInt)), "too big for VarInt62"); } TEST(SerializationTest, InvalidValueCausesPartialWrite) { char buffer[3] = {'\0'}; QuicheDataWriter writer(sizeof(buffer), buffer); QUICHE_EXPECT_OK(SerializeIntoWriter(writer, WireBytes("a"))); EXPECT_THAT( SerializeIntoWriter(writer, WireBytes("b"), WireBytes("A considerably long string, writing which " "will most likely cause ASAN to crash"), WireBytes("c")), StatusIs(absl::StatusCode::kInternal, "Failed to serialize field #1")); EXPECT_THAT(buffer, ElementsAre('a', 'b', '\0')); QUICHE_EXPECT_OK(SerializeIntoWriter(writer, WireBytes("z"))); EXPECT_EQ(buffer[2], 'z'); } TEST(SerializationTest, SerializeVector) { std::vector<absl::string_view> strs = {"foo", "test", "bar"}; absl::StatusOr<quiche::QuicheBuffer> serialized = SerializeIntoSimpleBuffer(WireSpan<WireBytes>(absl::MakeSpan(strs))); QUICHE_ASSERT_OK(serialized); EXPECT_EQ(serialized->AsStringView(), "footestbar"); } struct AwesomeStruct { uint64_t awesome_number; std::string awesome_text; }; class WireAwesomeStruct { public: using DataType = AwesomeStruct; WireAwesomeStruct(const AwesomeStruct& awesome) : awesome_(awesome) {} size_t GetLengthOnWire() { return quiche::ComputeLengthOnWire(WireUint16(awesome_.awesome_number), WireBytes(awesome_.awesome_text)); } absl::Status SerializeIntoWriter(QuicheDataWriter& writer) { return AppendToStatus(::quiche::SerializeIntoWriter( writer, WireUint16(awesome_.awesome_number), WireBytes(awesome_.awesome_text)), " while serializing AwesomeStruct"); } private: const AwesomeStruct& awesome_; }; TEST(SerializationTest, CustomStruct) { AwesomeStruct awesome; awesome.awesome_number = 0xabcd; awesome.awesome_text = "test"; ExpectEncodingHex("struct", "abcd74657374", WireAwesomeStruct(awesome)); } TEST(SerializationTest, CustomStructSpan) { std::array<AwesomeStruct, 2> awesome; awesome[0].awesome_number = 0xabcd; awesome[0].awesome_text = "test"; awesome[1].awesome_number = 0x1234; awesome[1].awesome_text = std::string(3, '\0'); ExpectEncodingHex("struct", "abcd746573741234000000", WireSpan<WireAwesomeStruct>(absl::MakeSpan(awesome))); } class WireFormatterThatWritesTooLittle { public: using DataType = absl::string_view; explicit WireFormatterThatWritesTooLittle(absl::string_view s) : s_(s) {} size_t GetLengthOnWire() const { return s_.size(); } bool SerializeIntoWriter(QuicheDataWriter& writer) { return writer.WriteStringPiece(s_.substr(0, s_.size() - 1)); } private: absl::string_view s_; }; TEST(SerializationTest, CustomStructWritesTooLittle) { absl::Status status; #if defined(NDEBUG) constexpr absl::string_view kStr = "\xaa\xbb\xcc\xdd"; status = SerializeIntoSimpleBuffer(WireFormatterThatWritesTooLittle(kStr)) .status(); EXPECT_THAT(status, StatusIs(absl::StatusCode::kInternal, ::testing::HasSubstr("Excess 1 bytes"))); #elif GTEST_HAS_DEATH_TEST constexpr absl::string_view kStr = "\xaa\xbb\xcc\xdd"; EXPECT_QUICHE_DEBUG_DEATH( status = SerializeIntoSimpleBuffer(WireFormatterThatWritesTooLittle(kStr)) .status(), "while serializing field #0"); EXPECT_THAT(status, StatusIs(absl::StatusCode::kOk)); #endif } TEST(SerializationTest, Empty) { ExpectEncodingHex("nothing", ""); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/wire_serialization.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/wire_serialization_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
0d6c250b-f682-4d42-9ca4-a86d11d951ce
cpp
google/quiche
quiche_circular_deque
quiche/common/quiche_circular_deque.h
quiche/common/quiche_circular_deque_test.cc
#ifndef QUICHE_COMMON_QUICHE_CIRCULAR_DEQUE_H_ #define QUICHE_COMMON_QUICHE_CIRCULAR_DEQUE_H_ #include <algorithm> #include <cstddef> #include <cstring> #include <iterator> #include <memory> #include <ostream> #include <type_traits> #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quiche { template <typename T, size_t MinCapacityIncrement = 3, typename Allocator = std::allocator<T>> class QUICHE_NO_EXPORT QuicheCircularDeque { using AllocatorTraits = std::allocator_traits<Allocator>; template <typename Pointee> class QUICHE_NO_EXPORT basic_iterator { using size_type = typename AllocatorTraits::size_type; public: using iterator_category = std::random_access_iterator_tag; using value_type = typename AllocatorTraits::value_type; using difference_type = typename AllocatorTraits::difference_type; using pointer = Pointee*; using reference = Pointee&; basic_iterator() = default; basic_iterator( const basic_iterator<value_type>& it) : deque_(it.deque_), index_(it.index_) {} basic_iterator& operator=(const basic_iterator<value_type>& it) { if (this != &it) { deque_ = it.deque_; index_ = it.index_; } return *this; } reference operator*() const { return *deque_->index_to_address(index_); } pointer operator->() const { return deque_->index_to_address(index_); } reference operator[](difference_type i) { return *(*this + i); } basic_iterator& operator++() { Increment(); return *this; } basic_iterator operator++(int) { basic_iterator result = *this; Increment(); return result; } basic_iterator operator--() { Decrement(); return *this; } basic_iterator operator--(int) { basic_iterator result = *this; Decrement(); return result; } friend basic_iterator operator+(const basic_iterator& it, difference_type delta) { basic_iterator result = it; result.IncrementBy(delta); return result; } basic_iterator& operator+=(difference_type delta) { IncrementBy(delta); return *this; } friend basic_iterator operator-(const basic_iterator& it, difference_type delta) { basic_iterator result = it; result.IncrementBy(-delta); return result; } basic_iterator& operator-=(difference_type delta) { IncrementBy(-delta); return *this; } friend difference_type operator-(const basic_iterator& lhs, const basic_iterator& rhs) { return lhs.ExternalPosition() - rhs.ExternalPosition(); } friend bool operator==(const basic_iterator& lhs, const basic_iterator& rhs) { return lhs.index_ == rhs.index_; } friend bool operator!=(const basic_iterator& lhs, const basic_iterator& rhs) { return !(lhs == rhs); } friend bool operator<(const basic_iterator& lhs, const basic_iterator& rhs) { return lhs.ExternalPosition() < rhs.ExternalPosition(); } friend bool operator<=(const basic_iterator& lhs, const basic_iterator& rhs) { return !(lhs > rhs); } friend bool operator>(const basic_iterator& lhs, const basic_iterator& rhs) { return lhs.ExternalPosition() > rhs.ExternalPosition(); } friend bool operator>=(const basic_iterator& lhs, const basic_iterator& rhs) { return !(lhs < rhs); } private: basic_iterator(const QuicheCircularDeque* deque, size_type index) : deque_(deque), index_(index) {} void Increment() { QUICHE_DCHECK_LE(ExternalPosition() + 1, deque_->size()); index_ = deque_->index_next(index_); } void Decrement() { QUICHE_DCHECK_GE(ExternalPosition(), 1u); index_ = deque_->index_prev(index_); } void IncrementBy(difference_type delta) { if (delta >= 0) { QUICHE_DCHECK_LE(static_cast<size_type>(ExternalPosition() + delta), deque_->size()); } else { QUICHE_DCHECK_GE(ExternalPosition(), static_cast<size_type>(-delta)); } index_ = deque_->index_increment_by(index_, delta); } size_type ExternalPosition() const { if (index_ >= deque_->begin_) { return index_ - deque_->begin_; } return index_ + deque_->data_capacity() - deque_->begin_; } friend class QuicheCircularDeque; const QuicheCircularDeque* deque_ = nullptr; size_type index_ = 0; }; public: using allocator_type = typename AllocatorTraits::allocator_type; using value_type = typename AllocatorTraits::value_type; using size_type = typename AllocatorTraits::size_type; using difference_type = typename AllocatorTraits::difference_type; using reference = value_type&; using const_reference = const value_type&; using pointer = typename AllocatorTraits::pointer; using const_pointer = typename AllocatorTraits::const_pointer; using iterator = basic_iterator<T>; using const_iterator = basic_iterator<const T>; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; QuicheCircularDeque() : QuicheCircularDeque(allocator_type()) {} explicit QuicheCircularDeque(const allocator_type& alloc) : allocator_and_data_(alloc) {} QuicheCircularDeque(size_type count, const T& value, const Allocator& alloc = allocator_type()) : allocator_and_data_(alloc) { resize(count, value); } explicit QuicheCircularDeque(size_type count, const Allocator& alloc = allocator_type()) : allocator_and_data_(alloc) { resize(count); } template < class InputIt, typename = std::enable_if_t<std::is_base_of< std::input_iterator_tag, typename std::iterator_traits<InputIt>::iterator_category>::value>> QuicheCircularDeque(InputIt first, InputIt last, const Allocator& alloc = allocator_type()) : allocator_and_data_(alloc) { AssignRange(first, last); } QuicheCircularDeque(const QuicheCircularDeque& other) : QuicheCircularDeque( other, AllocatorTraits::select_on_container_copy_construction( other.allocator_and_data_.allocator())) {} QuicheCircularDeque(const QuicheCircularDeque& other, const allocator_type& alloc) : allocator_and_data_(alloc) { assign(other.begin(), other.end()); } QuicheCircularDeque(QuicheCircularDeque&& other) : begin_(other.begin_), end_(other.end_), allocator_and_data_(std::move(other.allocator_and_data_)) { other.begin_ = other.end_ = 0; other.allocator_and_data_.data = nullptr; other.allocator_and_data_.data_capacity = 0; } QuicheCircularDeque(QuicheCircularDeque&& other, const allocator_type& alloc) : allocator_and_data_(alloc) { MoveRetainAllocator(std::move(other)); } QuicheCircularDeque(std::initializer_list<T> init, const allocator_type& alloc = allocator_type()) : QuicheCircularDeque(init.begin(), init.end(), alloc) {} QuicheCircularDeque& operator=(const QuicheCircularDeque& other) { if (this == &other) { return *this; } if (AllocatorTraits::propagate_on_container_copy_assignment::value && (allocator_and_data_.allocator() != other.allocator_and_data_.allocator())) { DestroyAndDeallocateAll(); begin_ = end_ = 0; allocator_and_data_ = AllocatorAndData(other.allocator_and_data_.allocator()); } assign(other.begin(), other.end()); return *this; } QuicheCircularDeque& operator=(QuicheCircularDeque&& other) { if (this == &other) { return *this; } if (AllocatorTraits::propagate_on_container_move_assignment::value) { this->~QuicheCircularDeque(); new (this) QuicheCircularDeque(std::move(other)); } else { MoveRetainAllocator(std::move(other)); } return *this; } ~QuicheCircularDeque() { DestroyAndDeallocateAll(); } void assign(size_type count, const T& value) { ClearRetainCapacity(); reserve(count); for (size_t i = 0; i < count; ++i) { emplace_back(value); } } template < class InputIt, typename = std::enable_if_t<std::is_base_of< std::input_iterator_tag, typename std::iterator_traits<InputIt>::iterator_category>::value>> void assign(InputIt first, InputIt last) { AssignRange(first, last); } void assign(std::initializer_list<T> ilist) { assign(ilist.begin(), ilist.end()); } reference at(size_type pos) { QUICHE_DCHECK(pos < size()) << "pos:" << pos << ", size():" << size(); size_type index = begin_ + pos; if (index < data_capacity()) { return *index_to_address(index); } return *index_to_address(index - data_capacity()); } const_reference at(size_type pos) const { return const_cast<QuicheCircularDeque*>(this)->at(pos); } reference operator[](size_type pos) { return at(pos); } const_reference operator[](size_type pos) const { return at(pos); } reference front() { QUICHE_DCHECK(!empty()); return *index_to_address(begin_); } const_reference front() const { return const_cast<QuicheCircularDeque*>(this)->front(); } reference back() { QUICHE_DCHECK(!empty()); return *(index_to_address(end_ == 0 ? data_capacity() - 1 : end_ - 1)); } const_reference back() const { return const_cast<QuicheCircularDeque*>(this)->back(); } iterator begin() { return iterator(this, begin_); } const_iterator begin() const { return const_iterator(this, begin_); } const_iterator cbegin() const { return const_iterator(this, begin_); } iterator end() { return iterator(this, end_); } const_iterator end() const { return const_iterator(this, end_); } const_iterator cend() const { return const_iterator(this, end_); } reverse_iterator rbegin() { return reverse_iterator(end()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } const_reverse_iterator crbegin() const { return rbegin(); } reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } const_reverse_iterator crend() const { return rend(); } size_type capacity() const { return data_capacity() == 0 ? 0 : data_capacity() - 1; } void reserve(size_type new_cap) { if (new_cap > capacity()) { Relocate(new_cap); } } void clear() { ClearRetainCapacity(); } bool empty() const { return begin_ == end_; } size_type size() const { if (begin_ <= end_) { return end_ - begin_; } return data_capacity() + end_ - begin_; } void resize(size_type count) { ResizeInternal(count); } void resize(size_type count, const value_type& value) { ResizeInternal(count, value); } void push_front(const T& value) { emplace_front(value); } void push_front(T&& value) { emplace_front(std::move(value)); } template <class... Args> reference emplace_front(Args&&... args) { MaybeExpandCapacity(1); begin_ = index_prev(begin_); new (index_to_address(begin_)) T(std::forward<Args>(args)...); return front(); } void push_back(const T& value) { emplace_back(value); } void push_back(T&& value) { emplace_back(std::move(value)); } template <class... Args> reference emplace_back(Args&&... args) { MaybeExpandCapacity(1); new (index_to_address(end_)) T(std::forward<Args>(args)...); end_ = index_next(end_); return back(); } void pop_front() { QUICHE_DCHECK(!empty()); DestroyByIndex(begin_); begin_ = index_next(begin_); MaybeShrinkCapacity(); } size_type pop_front_n(size_type count) { size_type num_elements_to_pop = std::min(count, size()); size_type new_begin = index_increment_by(begin_, num_elements_to_pop); DestroyRange(begin_, new_begin); begin_ = new_begin; MaybeShrinkCapacity(); return num_elements_to_pop; } void pop_back() { QUICHE_DCHECK(!empty()); end_ = index_prev(end_); DestroyByIndex(end_); MaybeShrinkCapacity(); } size_type pop_back_n(size_type count) { size_type num_elements_to_pop = std::min(count, size()); size_type new_end = index_increment_by(end_, -num_elements_to_pop); DestroyRange(new_end, end_); end_ = new_end; MaybeShrinkCapacity(); return num_elements_to_pop; } void swap(QuicheCircularDeque& other) { using std::swap; swap(begin_, other.begin_); swap(end_, other.end_); if (AllocatorTraits::propagate_on_container_swap::value) { swap(allocator_and_data_, other.allocator_and_data_); } else { QUICHE_DCHECK(get_allocator() == other.get_allocator()) << "Undefined swap behavior"; swap(allocator_and_data_.data, other.allocator_and_data_.data); swap(allocator_and_data_.data_capacity, other.allocator_and_data_.data_capacity); } } friend void swap(QuicheCircularDeque& lhs, QuicheCircularDeque& rhs) { lhs.swap(rhs); } allocator_type get_allocator() const { return allocator_and_data_.allocator(); } friend bool operator==(const QuicheCircularDeque& lhs, const QuicheCircularDeque& rhs) { return std::equal(lhs.begin(), lhs.end(), rhs.begin(), rhs.end()); } friend bool operator!=(const QuicheCircularDeque& lhs, const QuicheCircularDeque& rhs) { return !(lhs == rhs); } friend QUICHE_NO_EXPORT std::ostream& operator<<( std::ostream& os, const QuicheCircularDeque& dq) { os << "{"; for (size_type pos = 0; pos != dq.size(); ++pos) { if (pos != 0) { os << ","; } os << " " << dq[pos]; } os << " }"; return os; } private: void MoveRetainAllocator(QuicheCircularDeque&& other) { if (get_allocator() == other.get_allocator()) { DestroyAndDeallocateAll(); begin_ = other.begin_; end_ = other.end_; allocator_and_data_.data = other.allocator_and_data_.data; allocator_and_data_.data_capacity = other.allocator_and_data_.data_capacity; other.begin_ = other.end_ = 0; other.allocator_and_data_.data = nullptr; other.allocator_and_data_.data_capacity = 0; } else { ClearRetainCapacity(); for (auto& elem : other) { push_back(std::move(elem)); } other.clear(); } } template < typename InputIt, typename = std::enable_if_t<std::is_base_of< std::input_iterator_tag, typename std::iterator_traits<InputIt>::iterator_category>::value>> void AssignRange(InputIt first, InputIt last) { ClearRetainCapacity(); if (std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits<InputIt>::iterator_category>::value) { reserve(std::distance(first, last)); } for (; first != last; ++first) { emplace_back(*first); } } void DestroyAndDeallocateAll() { DestroyRange(begin_, end_); if (data_capacity() > 0) { QUICHE_DCHECK_NE(nullptr, allocator_and_data_.data); AllocatorTraits::deallocate(allocator_and_data_.allocator(), allocator_and_data_.data, data_capacity()); } } void ClearRetainCapacity() { DestroyRange(begin_, end_); begin_ = end_ = 0; } void MaybeShrinkCapacity() { } void MaybeExpandCapacity(size_t num_additional_elements) { size_t new_size = size() + num_additional_elements; if (capacity() >= new_size) { return; } size_t min_additional_capacity = std::max(MinCapacityIncrement, capacity() / 4); size_t new_capacity = std::max(new_size, capacity() + min_additional_capacity); Relocate(new_capacity); } void Relocate(size_t new_capacity) { const size_t num_elements = size(); QUICHE_DCHECK_GT(new_capacity, num_elements) << "new_capacity:" << new_capacity << ", num_elements:" << num_elements; size_t new_data_capacity = new_capacity + 1; pointer new_data = AllocatorTraits::allocate( allocator_and_data_.allocator(), new_data_capacity); if (begin_ < end_) { RelocateUnwrappedRange(begin_, end_, new_data); } else if (begin_ > end_) { const size_t num_elements_before_wrap = data_capacity() - begin_; RelocateUnwrappedRange(begin_, data_capacity(), new_data); RelocateUnwrappedRange(0, end_, new_data + num_elements_before_wrap); } if (data_capacity()) { AllocatorTraits::deallocate(allocator_and_data_.allocator(), allocator_and_data_.data, data_capacity()); } allocator_and_data_.data = new_data; allocator_and_data_.data_capacity = new_data_capacity; begin_ = 0; end_ = num_elements; } template <typename T_ = T> typename std::enable_if<std::is_trivially_copyable<T_>::value, void>::type RelocateUnwrappedRange(size_type begin, size_type end, pointer dest) const { QUICHE_DCHECK_LE(begin, end) << "begin:" << begin << ", end:" << end; pointer src = index_to_address(begin); QUICHE_DCHECK_NE(src, nullptr); memcpy(dest, src, sizeof(T) * (end - begin)); DestroyRange(begin, end); } template <typename T_ = T> typename std::enable_if<!std::is_trivially_copyable<T_>::value && std::is_move_constructible<T_>::value, void>::type RelocateUnwrappedRange(size_type begin, size_type end, pointer dest) const { QUICHE_DCHECK_LE(begin, end) << "begin:" << begin << ", end:" << end; pointer src = index_to_address(begin); pointer src_end = index_to_address(end); while (src != src_end) { new (dest) T(std::move(*src)); DestroyByAddress(src); ++dest; ++src; } } template <typename T_ = T> typename std::enable_if<!std::is_trivially_copyable<T_>::value && !std::is_move_constructible<T_>::value, void>::type RelocateUnwrappedRange(size_type begin, size_type end, pointer dest) const { QUICHE_DCHECK_LE(begin, end) << "begin:" << begin << ", end:" << end; pointer src = index_to_address(begin); pointer src_end = index_to_address(end); while (src != src_end) { new (dest) T(*src); DestroyByAddress(src); ++dest; ++src; } } template <class... U> void ResizeInternal(size_type count, U&&... u) { if (count > size()) { MaybeExpandCapacity(count - size()); while (size() < count) { emplace_back(std::forward<U>(u)...); } } else { size_type new_end = (begin_ + count) % data_capacity(); DestroyRange(new_end, end_); end_ = new_end; MaybeShrinkCapacity(); } } void DestroyRange(size_type begin, size_type end) const { if (std::is_trivially_destructible<T>::value) { return; } if (end >= begin) { DestroyUnwrappedRange(begin, end); } else { DestroyUnwrappedRange(begin, data_capacity()); DestroyUnwrappedRange(0, end); } } void DestroyUnwrappedRange(size_type begin, size_type end) const { QUICHE_DCHECK_LE(begin, end) << "begin:" << begin << ", end:" << end; for (; begin != end; ++begin) { DestroyByIndex(begin); } } void DestroyByIndex(size_type index) const { DestroyByAddress(index_to_address(index)); } void DestroyByAddress(pointer address) const { if (std::is_trivially_destructible<T>::value) { return; } address->~T(); } size_type data_capacity() const { return allocator_and_data_.data_capacity; } pointer index_to_address(size_type index) const { return allocator_and_data_.data + index; } size_type index_prev(size_type index) const { return index == 0 ? data_capacity() - 1 : index - 1; } size_type index_next(size_type index) const { return index == data_capacity() - 1 ? 0 : index + 1; } size_type index_increment_by(size_type index, difference_type delta) const { if (delta == 0) { return index; } QUICHE_DCHECK_LT(static_cast<size_type>(std::abs(delta)), data_capacity()); return (index + data_capacity() + delta) % data_capacity(); } struct QUICHE_NO_EXPORT AllocatorAndData : private allocator_type { explicit AllocatorAndData(const allocator_type& alloc) : allocator_type(alloc) {} const allocator_type& allocator() const { return *this; } allocator_type& allocator() { return *this; } pointer data = nullptr; size_type data_capacity = 0; }; size_type begin_ = 0; size_type end_ = 0; AllocatorAndData allocator_and_data_; }; } #endif
#include "quiche/common/quiche_circular_deque.h" #include <cstddef> #include <cstdint> #include <list> #include <memory> #include <ostream> #include <type_traits> #include <utility> #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" using testing::ElementsAre; namespace quiche { namespace test { namespace { template <typename T, template <typename> class BaseAllocator = std::allocator> class CountingAllocator : public BaseAllocator<T> { using BaseType = BaseAllocator<T>; public: using propagate_on_container_copy_assignment = std::true_type; using propagate_on_container_move_assignment = std::true_type; using propagate_on_container_swap = std::true_type; T* allocate(std::size_t n) { ++shared_counts_->allocate_count; return BaseType::allocate(n); } void deallocate(T* ptr, std::size_t n) { ++shared_counts_->deallocate_count; return BaseType::deallocate(ptr, n); } size_t allocate_count() const { return shared_counts_->allocate_count; } size_t deallocate_count() const { return shared_counts_->deallocate_count; } friend bool operator==(const CountingAllocator& lhs, const CountingAllocator& rhs) { return lhs.shared_counts_ == rhs.shared_counts_; } friend bool operator!=(const CountingAllocator& lhs, const CountingAllocator& rhs) { return !(lhs == rhs); } private: struct Counts { size_t allocate_count = 0; size_t deallocate_count = 0; }; std::shared_ptr<Counts> shared_counts_ = std::make_shared<Counts>(); }; template <typename T, typename propagate_on_copy_assignment, typename propagate_on_move_assignment, typename propagate_on_swap, bool equality_result, template <typename> class BaseAllocator = std::allocator> struct ConfigurableAllocator : public BaseAllocator<T> { using propagate_on_container_copy_assignment = propagate_on_copy_assignment; using propagate_on_container_move_assignment = propagate_on_move_assignment; using propagate_on_container_swap = propagate_on_swap; friend bool operator==(const ConfigurableAllocator& , const ConfigurableAllocator& ) { return equality_result; } friend bool operator!=(const ConfigurableAllocator& lhs, const ConfigurableAllocator& rhs) { return !(lhs == rhs); } }; template <typename Deque> void ShiftRight(Deque* dq, bool emplace) { auto back = *(&dq->back()); dq->pop_back(); if (emplace) { dq->emplace_front(back); } else { dq->push_front(back); } } template <typename Deque> void ShiftLeft(Deque* dq, bool emplace) { auto front = *(&dq->front()); dq->pop_front(); if (emplace) { dq->emplace_back(front); } else { dq->push_back(front); } } class QuicheCircularDequeTest : public QuicheTest {}; TEST_F(QuicheCircularDequeTest, Empty) { QuicheCircularDeque<int> dq; EXPECT_TRUE(dq.empty()); EXPECT_EQ(0u, dq.size()); dq.clear(); dq.push_back(10); EXPECT_FALSE(dq.empty()); EXPECT_EQ(1u, dq.size()); EXPECT_EQ(10, dq.front()); EXPECT_EQ(10, dq.back()); dq.pop_front(); EXPECT_TRUE(dq.empty()); EXPECT_EQ(0u, dq.size()); EXPECT_QUICHE_DEBUG_DEATH(dq.front(), ""); EXPECT_QUICHE_DEBUG_DEATH(dq.back(), ""); EXPECT_QUICHE_DEBUG_DEATH(dq.at(0), ""); EXPECT_QUICHE_DEBUG_DEATH(dq[0], ""); } TEST_F(QuicheCircularDequeTest, Constructor) { QuicheCircularDeque<int> dq; EXPECT_TRUE(dq.empty()); std::allocator<int> alloc; QuicheCircularDeque<int> dq1(alloc); EXPECT_TRUE(dq1.empty()); QuicheCircularDeque<int> dq2(8, 100, alloc); EXPECT_THAT(dq2, ElementsAre(100, 100, 100, 100, 100, 100, 100, 100)); QuicheCircularDeque<int> dq3(5, alloc); EXPECT_THAT(dq3, ElementsAre(0, 0, 0, 0, 0)); QuicheCircularDeque<int> dq4_rand_iter(dq3.begin(), dq3.end(), alloc); EXPECT_THAT(dq4_rand_iter, ElementsAre(0, 0, 0, 0, 0)); EXPECT_EQ(dq4_rand_iter, dq3); std::list<int> dq4_src = {4, 4, 4, 4}; QuicheCircularDeque<int> dq4_bidi_iter(dq4_src.begin(), dq4_src.end()); EXPECT_THAT(dq4_bidi_iter, ElementsAre(4, 4, 4, 4)); QuicheCircularDeque<int> dq5(dq4_bidi_iter); EXPECT_THAT(dq5, ElementsAre(4, 4, 4, 4)); EXPECT_EQ(dq5, dq4_bidi_iter); QuicheCircularDeque<int> dq6(dq5, alloc); EXPECT_THAT(dq6, ElementsAre(4, 4, 4, 4)); EXPECT_EQ(dq6, dq5); QuicheCircularDeque<int> dq7(std::move(*&dq6)); EXPECT_THAT(dq7, ElementsAre(4, 4, 4, 4)); EXPECT_TRUE(dq6.empty()); QuicheCircularDeque<int> dq8_equal_allocator(std::move(*&dq7), alloc); EXPECT_THAT(dq8_equal_allocator, ElementsAre(4, 4, 4, 4)); EXPECT_TRUE(dq7.empty()); QuicheCircularDeque<int, 3, CountingAllocator<int>> dq8_temp = {5, 6, 7, 8, 9}; QuicheCircularDeque<int, 3, CountingAllocator<int>> dq8_unequal_allocator( std::move(*&dq8_temp), CountingAllocator<int>()); EXPECT_THAT(dq8_unequal_allocator, ElementsAre(5, 6, 7, 8, 9)); EXPECT_TRUE(dq8_temp.empty()); QuicheCircularDeque<int> dq9({3, 4, 5, 6, 7}, alloc); EXPECT_THAT(dq9, ElementsAre(3, 4, 5, 6, 7)); } TEST_F(QuicheCircularDequeTest, Assign) { QuicheCircularDeque<int, 3, CountingAllocator<int>> dq; dq.assign(7, 1); EXPECT_THAT(dq, ElementsAre(1, 1, 1, 1, 1, 1, 1)); EXPECT_EQ(1u, dq.get_allocator().allocate_count()); QuicheCircularDeque<int, 3, CountingAllocator<int>> dq2; dq2.assign(dq.begin(), dq.end()); EXPECT_THAT(dq2, ElementsAre(1, 1, 1, 1, 1, 1, 1)); EXPECT_EQ(1u, dq2.get_allocator().allocate_count()); EXPECT_TRUE(std::equal(dq.begin(), dq.end(), dq2.begin(), dq2.end())); dq2.assign({2, 2, 2, 2, 2, 2}); EXPECT_THAT(dq2, ElementsAre(2, 2, 2, 2, 2, 2)); std::list<int> dq3_src = {3, 3, 3, 3, 3}; QuicheCircularDeque<int, 3, CountingAllocator<int>> dq3; dq3.assign(dq3_src.begin(), dq3_src.end()); EXPECT_THAT(dq3, ElementsAre(3, 3, 3, 3, 3)); EXPECT_LT(1u, dq3.get_allocator().allocate_count()); dq3 = *&dq3; EXPECT_THAT(dq3, ElementsAre(3, 3, 3, 3, 3)); QuicheCircularDeque< int, 3, ConfigurableAllocator<int, std::true_type, std::true_type, std::true_type, false>> dq4, dq5; dq4.assign(dq3.begin(), dq3.end()); dq5 = dq4; EXPECT_THAT(dq5, ElementsAre(3, 3, 3, 3, 3)); QuicheCircularDeque< int, 3, ConfigurableAllocator<int, std::false_type, std::true_type, std::true_type, true>> dq6, dq7; dq6.assign(dq3.begin(), dq3.end()); dq7 = dq6; EXPECT_THAT(dq7, ElementsAre(3, 3, 3, 3, 3)); dq3 = std::move(*&dq3); EXPECT_THAT(dq3, ElementsAre(3, 3, 3, 3, 3)); ASSERT_TRUE(decltype(dq3.get_allocator()):: propagate_on_container_move_assignment::value); decltype(dq3) dq8; dq8 = std::move(*&dq3); EXPECT_THAT(dq8, ElementsAre(3, 3, 3, 3, 3)); EXPECT_TRUE(dq3.empty()); QuicheCircularDeque< int, 3, ConfigurableAllocator<int, std::true_type, std::false_type, std::true_type, true>> dq9, dq10; dq9.assign(dq8.begin(), dq8.end()); dq10.assign(dq2.begin(), dq2.end()); dq9 = std::move(*&dq10); EXPECT_THAT(dq9, ElementsAre(2, 2, 2, 2, 2, 2)); EXPECT_TRUE(dq10.empty()); QuicheCircularDeque< int, 3, ConfigurableAllocator<int, std::true_type, std::false_type, std::true_type, false>> dq11, dq12; dq11.assign(dq8.begin(), dq8.end()); dq12.assign(dq2.begin(), dq2.end()); dq11 = std::move(*&dq12); EXPECT_THAT(dq11, ElementsAre(2, 2, 2, 2, 2, 2)); EXPECT_TRUE(dq12.empty()); } TEST_F(QuicheCircularDequeTest, Access) { QuicheCircularDeque<int, 3, CountingAllocator<int>> dq; dq.push_back(10); EXPECT_EQ(dq.front(), 10); EXPECT_EQ(dq.back(), 10); EXPECT_EQ(dq.at(0), 10); EXPECT_EQ(dq[0], 10); dq.front() = 12; EXPECT_EQ(dq.front(), 12); EXPECT_EQ(dq.back(), 12); EXPECT_EQ(dq.at(0), 12); EXPECT_EQ(dq[0], 12); const auto& dqref = dq; EXPECT_EQ(dqref.front(), 12); EXPECT_EQ(dqref.back(), 12); EXPECT_EQ(dqref.at(0), 12); EXPECT_EQ(dqref[0], 12); dq.pop_front(); EXPECT_TRUE(dqref.empty()); dq.push_back(15); dq.push_front(5); dq.push_back(25); EXPECT_EQ(dq.size(), dq.capacity()); EXPECT_THAT(dq, ElementsAre(5, 15, 25)); EXPECT_LT(&dq.front(), &dq.back()); EXPECT_EQ(dq.front(), 5); EXPECT_EQ(dq.back(), 25); EXPECT_EQ(dq.at(0), 5); EXPECT_EQ(dq.at(1), 15); EXPECT_EQ(dq.at(2), 25); EXPECT_EQ(dq[0], 5); EXPECT_EQ(dq[1], 15); EXPECT_EQ(dq[2], 25); dq.pop_front(); dq.push_back(35); EXPECT_THAT(dq, ElementsAre(15, 25, 35)); EXPECT_LT(&dq.front(), &dq.back()); EXPECT_EQ(dq.front(), 15); EXPECT_EQ(dq.back(), 35); EXPECT_EQ(dq.at(0), 15); EXPECT_EQ(dq.at(1), 25); EXPECT_EQ(dq.at(2), 35); EXPECT_EQ(dq[0], 15); EXPECT_EQ(dq[1], 25); EXPECT_EQ(dq[2], 35); dq.pop_front(); dq.push_back(45); EXPECT_THAT(dq, ElementsAre(25, 35, 45)); EXPECT_GT(&dq.front(), &dq.back()); EXPECT_EQ(dq.front(), 25); EXPECT_EQ(dq.back(), 45); EXPECT_EQ(dq.at(0), 25); EXPECT_EQ(dq.at(1), 35); EXPECT_EQ(dq.at(2), 45); EXPECT_EQ(dq[0], 25); EXPECT_EQ(dq[1], 35); EXPECT_EQ(dq[2], 45); dq.pop_front(); dq.push_back(55); EXPECT_THAT(dq, ElementsAre(35, 45, 55)); EXPECT_GT(&dq.front(), &dq.back()); EXPECT_EQ(dq.front(), 35); EXPECT_EQ(dq.back(), 55); EXPECT_EQ(dq.at(0), 35); EXPECT_EQ(dq.at(1), 45); EXPECT_EQ(dq.at(2), 55); EXPECT_EQ(dq[0], 35); EXPECT_EQ(dq[1], 45); EXPECT_EQ(dq[2], 55); dq.pop_front(); dq.push_back(65); EXPECT_THAT(dq, ElementsAre(45, 55, 65)); EXPECT_LT(&dq.front(), &dq.back()); EXPECT_EQ(dq.front(), 45); EXPECT_EQ(dq.back(), 65); EXPECT_EQ(dq.at(0), 45); EXPECT_EQ(dq.at(1), 55); EXPECT_EQ(dq.at(2), 65); EXPECT_EQ(dq[0], 45); EXPECT_EQ(dq[1], 55); EXPECT_EQ(dq[2], 65); EXPECT_EQ(1u, dq.get_allocator().allocate_count()); } TEST_F(QuicheCircularDequeTest, Iterate) { QuicheCircularDeque<int> dq; EXPECT_EQ(dq.begin(), dq.end()); EXPECT_EQ(dq.cbegin(), dq.cend()); EXPECT_EQ(dq.rbegin(), dq.rend()); EXPECT_EQ(dq.crbegin(), dq.crend()); dq.emplace_back(2); QuicheCircularDeque<int>::const_iterator citer = dq.begin(); EXPECT_NE(citer, dq.end()); EXPECT_EQ(*citer, 2); ++citer; EXPECT_EQ(citer, dq.end()); EXPECT_EQ(*dq.begin(), 2); EXPECT_EQ(*dq.cbegin(), 2); EXPECT_EQ(*dq.rbegin(), 2); EXPECT_EQ(*dq.crbegin(), 2); dq.emplace_front(1); QuicheCircularDeque<int>::const_reverse_iterator criter = dq.rbegin(); EXPECT_NE(criter, dq.rend()); EXPECT_EQ(*criter, 2); ++criter; EXPECT_NE(criter, dq.rend()); EXPECT_EQ(*criter, 1); ++criter; EXPECT_EQ(criter, dq.rend()); EXPECT_EQ(*dq.begin(), 1); EXPECT_EQ(*dq.cbegin(), 1); EXPECT_EQ(*dq.rbegin(), 2); EXPECT_EQ(*dq.crbegin(), 2); dq.push_back(3); int expected_value = 1; for (QuicheCircularDeque<int>::iterator it = dq.begin(); it != dq.end(); ++it) { EXPECT_EQ(expected_value++, *it); } expected_value = 1; for (QuicheCircularDeque<int>::const_iterator it = dq.cbegin(); it != dq.cend(); ++it) { EXPECT_EQ(expected_value++, *it); } expected_value = 3; for (QuicheCircularDeque<int>::reverse_iterator it = dq.rbegin(); it != dq.rend(); ++it) { EXPECT_EQ(expected_value--, *it); } expected_value = 3; for (QuicheCircularDeque<int>::const_reverse_iterator it = dq.crbegin(); it != dq.crend(); ++it) { EXPECT_EQ(expected_value--, *it); } } TEST_F(QuicheCircularDequeTest, Iterator) { EXPECT_EQ(QuicheCircularDeque<int>::iterator(), QuicheCircularDeque<int>::iterator()); EXPECT_EQ(QuicheCircularDeque<int>::const_iterator(), QuicheCircularDeque<int>::const_iterator()); EXPECT_EQ(QuicheCircularDeque<int>::reverse_iterator(), QuicheCircularDeque<int>::reverse_iterator()); EXPECT_EQ(QuicheCircularDeque<int>::const_reverse_iterator(), QuicheCircularDeque<int>::const_reverse_iterator()); QuicheCircularDeque<QuicheCircularDeque<int>, 3> dqdq = { {1, 2}, {10, 20, 30}, {100, 200, 300, 400}}; decltype(dqdq)::iterator iter = dqdq.begin(); EXPECT_EQ(iter->size(), 2u); EXPECT_THAT(*iter, ElementsAre(1, 2)); decltype(dqdq)::const_iterator citer = dqdq.cbegin() + 1; EXPECT_NE(*iter, *citer); EXPECT_EQ(citer->size(), 3u); int x = 10; for (auto it = citer->begin(); it != citer->end(); ++it) { EXPECT_EQ(*it, x); x += 10; } EXPECT_LT(iter, citer); EXPECT_LE(iter, iter); EXPECT_GT(citer, iter); EXPECT_GE(citer, citer); iter += 2; EXPECT_NE(*iter, *citer); EXPECT_EQ(iter->size(), 4u); for (int i = 1; i <= 4; ++i) { EXPECT_EQ(iter->begin()[i - 1], i * 100); } EXPECT_LT(citer, iter); EXPECT_LE(iter, iter); EXPECT_GT(iter, citer); EXPECT_GE(citer, citer); iter -= 1; EXPECT_EQ(*iter, *citer); EXPECT_EQ(iter->size(), 3u); x = 10; for (auto it = iter->begin(); it != iter->end();) { EXPECT_EQ(*(it++), x); x += 10; } x = 30; for (auto it = iter->begin() + 2; it != iter->begin();) { EXPECT_EQ(*(it--), x); x -= 10; } } TEST_F(QuicheCircularDequeTest, Resize) { QuicheCircularDeque<int, 3, CountingAllocator<int>> dq; dq.resize(8); EXPECT_THAT(dq, ElementsAre(0, 0, 0, 0, 0, 0, 0, 0)); EXPECT_EQ(1u, dq.get_allocator().allocate_count()); dq.resize(10, 5); EXPECT_THAT(dq, ElementsAre(0, 0, 0, 0, 0, 0, 0, 0, 5, 5)); QuicheCircularDeque<int, 3, CountingAllocator<int>> dq2 = dq; for (size_t new_size = dq.size(); new_size != 0; --new_size) { dq.resize(new_size); EXPECT_TRUE( std::equal(dq.begin(), dq.end(), dq2.begin(), dq2.begin() + new_size)); } dq.resize(0); EXPECT_TRUE(dq.empty()); ASSERT_EQ(dq2.size(), dq2.capacity()); while (dq2.size() < dq2.capacity()) { dq2.push_back(5); } ASSERT_LT(&dq2.front(), &dq2.back()); dq2.pop_back(); dq2.push_front(-5); ASSERT_GT(&dq2.front(), &dq2.back()); EXPECT_EQ(-5, dq2.front()); EXPECT_EQ(5, dq2.back()); dq2.resize(dq2.size() + 1, 10); ASSERT_LT(&dq2.front(), &dq2.back()); EXPECT_EQ(-5, dq2.front()); EXPECT_EQ(10, dq2.back()); EXPECT_EQ(5, *(dq2.rbegin() + 1)); } namespace { class Foo { public: Foo() : Foo(0xF00) {} explicit Foo(int i) : i_(new int(i)) {} ~Foo() { if (i_ != nullptr) { delete i_; } } Foo(const Foo& other) : i_(new int(*other.i_)) {} Foo(Foo&& other) = delete; void Set(int i) { *i_ = i; } int i() const { return *i_; } friend bool operator==(const Foo& lhs, const Foo& rhs) { return lhs.i() == rhs.i(); } friend std::ostream& operator<<(std::ostream& os, const Foo& foo) { return os << "Foo(" << foo.i() << ")"; } private: int* i_ = nullptr; }; } TEST_F(QuicheCircularDequeTest, RelocateNonTriviallyCopyable) { { using MoveConstructible = std::unique_ptr<Foo>; ASSERT_FALSE(std::is_trivially_copyable<MoveConstructible>::value); ASSERT_TRUE(std::is_move_constructible<MoveConstructible>::value); QuicheCircularDeque<MoveConstructible, 3, CountingAllocator<MoveConstructible>> dq1; dq1.resize(3); EXPECT_EQ(dq1.size(), dq1.capacity()); EXPECT_EQ(1u, dq1.get_allocator().allocate_count()); dq1.emplace_back(new Foo(0xF1)); EXPECT_EQ(4u, dq1.size()); EXPECT_EQ(2u, dq1.get_allocator().allocate_count()); EXPECT_EQ(dq1[0], nullptr); EXPECT_EQ(dq1[1], nullptr); EXPECT_EQ(dq1[2], nullptr); EXPECT_EQ(dq1[3]->i(), 0xF1); } { using NonMoveConstructible = Foo; ASSERT_FALSE(std::is_trivially_copyable<NonMoveConstructible>::value); ASSERT_FALSE(std::is_move_constructible<NonMoveConstructible>::value); QuicheCircularDeque<NonMoveConstructible, 3, CountingAllocator<NonMoveConstructible>> dq2; dq2.resize(3); EXPECT_EQ(dq2.size(), dq2.capacity()); EXPECT_EQ(1u, dq2.get_allocator().allocate_count()); dq2.emplace_back(0xF1); EXPECT_EQ(4u, dq2.size()); EXPECT_EQ(2u, dq2.get_allocator().allocate_count()); EXPECT_EQ(dq2[0].i(), 0xF00); EXPECT_EQ(dq2[1].i(), 0xF00); EXPECT_EQ(dq2[2].i(), 0xF00); EXPECT_EQ(dq2[3].i(), 0xF1); } } TEST_F(QuicheCircularDequeTest, PushPop) { { QuicheCircularDeque<Foo, 4, CountingAllocator<Foo>> dq(4); for (size_t i = 0; i < dq.size(); ++i) { dq[i].Set(i + 1); } QUICHE_LOG(INFO) << "dq initialized to " << dq; EXPECT_THAT(dq, ElementsAre(Foo(1), Foo(2), Foo(3), Foo(4))); ShiftLeft(&dq, false); QUICHE_LOG(INFO) << "shift left once : " << dq; EXPECT_THAT(dq, ElementsAre(Foo(2), Foo(3), Foo(4), Foo(1))); ShiftLeft(&dq, true); QUICHE_LOG(INFO) << "shift left twice: " << dq; EXPECT_THAT(dq, ElementsAre(Foo(3), Foo(4), Foo(1), Foo(2))); ASSERT_GT(&dq.front(), &dq.back()); } { QuicheCircularDeque<Foo, 4, CountingAllocator<Foo>> dq1(4); for (size_t i = 0; i < dq1.size(); ++i) { dq1[i].Set(i + 1); } QUICHE_LOG(INFO) << "dq1 initialized to " << dq1; EXPECT_THAT(dq1, ElementsAre(Foo(1), Foo(2), Foo(3), Foo(4))); ShiftRight(&dq1, false); QUICHE_LOG(INFO) << "shift right once : " << dq1; EXPECT_THAT(dq1, ElementsAre(Foo(4), Foo(1), Foo(2), Foo(3))); ShiftRight(&dq1, true); QUICHE_LOG(INFO) << "shift right twice: " << dq1; EXPECT_THAT(dq1, ElementsAre(Foo(3), Foo(4), Foo(1), Foo(2))); ASSERT_GT(&dq1.front(), &dq1.back()); } { QuicheCircularDeque<Foo, 4, CountingAllocator<Foo>> dq2(5); for (size_t i = 0; i < dq2.size(); ++i) { dq2[i].Set(i + 1); } EXPECT_THAT(dq2, ElementsAre(Foo(1), Foo(2), Foo(3), Foo(4), Foo(5))); EXPECT_EQ(2u, dq2.pop_front_n(2)); EXPECT_THAT(dq2, ElementsAre(Foo(3), Foo(4), Foo(5))); EXPECT_EQ(3u, dq2.pop_front_n(100)); EXPECT_TRUE(dq2.empty()); } { QuicheCircularDeque<Foo, 4, CountingAllocator<Foo>> dq3(6); for (size_t i = 0; i < dq3.size(); ++i) { dq3[i].Set(i + 1); } EXPECT_THAT(dq3, ElementsAre(Foo(1), Foo(2), Foo(3), Foo(4), Foo(5), Foo(6))); ShiftRight(&dq3, true); ShiftRight(&dq3, true); ShiftRight(&dq3, true); EXPECT_THAT(dq3, ElementsAre(Foo(4), Foo(5), Foo(6), Foo(1), Foo(2), Foo(3))); EXPECT_EQ(2u, dq3.pop_back_n(2)); EXPECT_THAT(dq3, ElementsAre(Foo(4), Foo(5), Foo(6), Foo(1))); EXPECT_EQ(2u, dq3.pop_back_n(2)); EXPECT_THAT(dq3, ElementsAre(Foo(4), Foo(5))); } } TEST_F(QuicheCircularDequeTest, Allocation) { CountingAllocator<int> alloc; { QuicheCircularDeque<int, 3, CountingAllocator<int>> dq(alloc); EXPECT_EQ(alloc, dq.get_allocator()); EXPECT_EQ(0u, dq.size()); EXPECT_EQ(0u, dq.capacity()); EXPECT_EQ(0u, alloc.allocate_count()); EXPECT_EQ(0u, alloc.deallocate_count()); for (int i = 1; i <= 18; ++i) { SCOPED_TRACE(testing::Message() << "i=" << i << ", capacity_b4_push=" << dq.capacity()); dq.push_back(i); EXPECT_EQ(i, static_cast<int>(dq.size())); const size_t capacity = 3 + (i - 1) / 3 * 3; EXPECT_EQ(capacity, dq.capacity()); EXPECT_EQ(capacity / 3, alloc.allocate_count()); EXPECT_EQ(capacity / 3 - 1, alloc.deallocate_count()); } dq.push_back(19); EXPECT_EQ(22u, dq.capacity()); EXPECT_EQ(7u, alloc.allocate_count()); EXPECT_EQ(6u, alloc.deallocate_count()); } EXPECT_EQ(7u, alloc.deallocate_count()); } } } } namespace { template <typename T> using SwappableAllocator = quiche::test::ConfigurableAllocator< T, std::true_type, std::true_type, std::true_type, true>; template <typename T> using UnswappableEqualAllocator = quiche::test::ConfigurableAllocator< T, std::true_type, std::true_type, std::false_type, true>; template <typename T> using UnswappableUnequalAllocator = quiche::test::ConfigurableAllocator< T, std::true_type, std::true_type, std::false_type, false>; using quiche::test::QuicheCircularDequeTest; TEST_F(QuicheCircularDequeTest, Swap) { using std::swap; quiche::QuicheCircularDeque<int64_t, 3, SwappableAllocator<int64_t>> dq1, dq2; dq1.push_back(10); dq1.push_back(11); dq2.push_back(20); swap(dq1, dq2); EXPECT_THAT(dq1, ElementsAre(20)); EXPECT_THAT(dq2, ElementsAre(10, 11)); quiche::QuicheCircularDeque<char, 3, UnswappableEqualAllocator<char>> dq3, dq4; dq3 = {1, 2, 3, 4, 5}; dq4 = {6, 7, 8, 9, 0}; swap(dq3, dq4); EXPECT_THAT(dq3, ElementsAre(6, 7, 8, 9, 0)); EXPECT_THAT(dq4, ElementsAre(1, 2, 3, 4, 5)); quiche::QuicheCircularDeque<int, 3, UnswappableUnequalAllocator<int>> dq5, dq6; dq6.push_front(4); dq5.assign(dq6.begin(), dq6.end()); EXPECT_THAT(dq5, ElementsAre(4)); EXPECT_QUICHE_DEBUG_DEATH(swap(dq5, dq6), "Undefined swap behavior"); } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/quiche_circular_deque.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/quiche_circular_deque_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
4d1025af-be87-4f2f-be05-74e276e9db38
cpp
google/quiche
print_elements
quiche/common/print_elements.h
quiche/common/print_elements_test.cc
#ifndef QUICHE_COMMON_PRINT_ELEMENTS_H_ #define QUICHE_COMMON_PRINT_ELEMENTS_H_ #include <ostream> #include <sstream> #include <string> #include "quiche/common/platform/api/quiche_export.h" namespace quiche { template <typename T> QUICHE_NO_EXPORT inline std::string PrintElements(const T& container) { std::stringstream debug_string; debug_string << "{"; auto it = container.cbegin(); if (it != container.cend()) { debug_string << *it; ++it; while (it != container.cend()) { debug_string << ", " << *it; ++it; } } debug_string << "}"; return debug_string.str(); } } #endif
#include "quiche/common/print_elements.h" #include <deque> #include <list> #include <string> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/common/platform/api/quiche_test.h" using quic::QuicIetfTransportErrorCodes; namespace quiche { namespace test { namespace { TEST(PrintElementsTest, Empty) { std::vector<std::string> empty{}; EXPECT_EQ("{}", PrintElements(empty)); } TEST(PrintElementsTest, StdContainers) { std::vector<std::string> one{"foo"}; EXPECT_EQ("{foo}", PrintElements(one)); std::list<std::string> two{"foo", "bar"}; EXPECT_EQ("{foo, bar}", PrintElements(two)); std::deque<absl::string_view> three{"foo", "bar", "baz"}; EXPECT_EQ("{foo, bar, baz}", PrintElements(three)); } TEST(PrintElementsTest, CustomPrinter) { std::vector<QuicIetfTransportErrorCodes> empty{}; EXPECT_EQ("{}", PrintElements(empty)); std::list<QuicIetfTransportErrorCodes> one{ QuicIetfTransportErrorCodes::NO_IETF_QUIC_ERROR}; EXPECT_EQ("{NO_IETF_QUIC_ERROR}", PrintElements(one)); std::vector<QuicIetfTransportErrorCodes> two{ QuicIetfTransportErrorCodes::FLOW_CONTROL_ERROR, QuicIetfTransportErrorCodes::STREAM_LIMIT_ERROR}; EXPECT_EQ("{FLOW_CONTROL_ERROR, STREAM_LIMIT_ERROR}", PrintElements(two)); std::list<QuicIetfTransportErrorCodes> three{ QuicIetfTransportErrorCodes::CONNECTION_ID_LIMIT_ERROR, QuicIetfTransportErrorCodes::PROTOCOL_VIOLATION, QuicIetfTransportErrorCodes::INVALID_TOKEN}; EXPECT_EQ("{CONNECTION_ID_LIMIT_ERROR, PROTOCOL_VIOLATION, INVALID_TOKEN}", PrintElements(three)); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/print_elements.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/print_elements_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
8113d2ce-c1e9-467e-9112-386cd6cca64a
cpp
google/quiche
quiche_intrusive_list
quiche/common/quiche_intrusive_list.h
quiche/common/quiche_intrusive_list_test.cc
#ifndef QUICHE_COMMON_QUICHE_INTRUSIVE_LIST_H_ #define QUICHE_COMMON_QUICHE_INTRUSIVE_LIST_H_ #include <stddef.h> #include <cstddef> #include <iterator> #include "quiche/common/platform/api/quiche_export.h" namespace quiche { template <typename T, typename ListID> class QuicheIntrusiveList; template <typename T, typename ListID = void> class QUICHE_EXPORT QuicheIntrusiveLink { protected: QuicheIntrusiveLink() : next_(nullptr), prev_(nullptr) {} #ifndef SWIG QuicheIntrusiveLink(const QuicheIntrusiveLink&) = delete; QuicheIntrusiveLink& operator=(const QuicheIntrusiveLink&) = delete; #endif private: friend class QuicheIntrusiveList<T, ListID>; T* cast_to_derived() { return static_cast<T*>(this); } const T* cast_to_derived() const { return static_cast<const T*>(this); } QuicheIntrusiveLink* next_; QuicheIntrusiveLink* prev_; }; template <typename T, typename ListID = void> class QUICHE_EXPORT QuicheIntrusiveList { template <typename QualifiedT, typename QualifiedLinkT> class iterator_impl; public: typedef T value_type; typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type& reference; typedef const value_type& const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef QuicheIntrusiveLink<T, ListID> link_type; typedef iterator_impl<T, link_type> iterator; typedef iterator_impl<const T, const link_type> const_iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; typedef std::reverse_iterator<iterator> reverse_iterator; QuicheIntrusiveList() { clear(); } #ifndef SWIG QuicheIntrusiveList(QuicheIntrusiveList&& src) noexcept { clear(); if (src.empty()) return; sentinel_link_.next_ = src.sentinel_link_.next_; sentinel_link_.prev_ = src.sentinel_link_.prev_; sentinel_link_.prev_->next_ = &sentinel_link_; sentinel_link_.next_->prev_ = &sentinel_link_; src.clear(); } #endif iterator begin() { return iterator(sentinel_link_.next_); } const_iterator begin() const { return const_iterator(sentinel_link_.next_); } iterator end() { return iterator(&sentinel_link_); } const_iterator end() const { return const_iterator(&sentinel_link_); } reverse_iterator rbegin() { return reverse_iterator(end()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } bool empty() const { return (sentinel_link_.next_ == &sentinel_link_); } size_type size() const { return std::distance(begin(), end()); } size_type max_size() const { return size_type(-1); } reference front() { return *begin(); } const_reference front() const { return *begin(); } reference back() { return *(--end()); } const_reference back() const { return *(--end()); } static iterator insert(iterator position, T* obj) { return insert_link(position.link(), obj); } void push_front(T* obj) { insert(begin(), obj); } void push_back(T* obj) { insert(end(), obj); } static iterator erase(T* obj) { link_type* obj_link = obj; obj_link->next_->prev_ = obj_link->prev_; obj_link->prev_->next_ = obj_link->next_; link_type* next_link = obj_link->next_; obj_link->next_ = nullptr; obj_link->prev_ = nullptr; return iterator(next_link); } static iterator erase(iterator position) { return erase(position.operator->()); } void pop_front() { erase(begin()); } void pop_back() { erase(--end()); } static bool is_linked(const T* obj) { return obj->link_type::next_ != nullptr; } void clear() { sentinel_link_.next_ = sentinel_link_.prev_ = &sentinel_link_; } void swap(QuicheIntrusiveList& x) { QuicheIntrusiveList tmp; tmp.splice(tmp.begin(), *this); this->splice(this->begin(), x); x.splice(x.begin(), tmp); } void splice(iterator pos, QuicheIntrusiveList& src) { splice(pos, src.begin(), src.end()); } void splice(iterator pos, iterator i) { splice(pos, i, std::next(i)); } void splice(iterator pos, iterator first, iterator last) { if (first == last) return; link_type* const last_prev = last.link()->prev_; first.link()->prev_->next_ = last.operator->(); last.link()->prev_ = first.link()->prev_; first.link()->prev_ = pos.link()->prev_; pos.link()->prev_->next_ = first.operator->(); last_prev->next_ = pos.operator->(); pos.link()->prev_ = last_prev; } private: static iterator insert_link(link_type* next_link, T* obj) { link_type* obj_link = obj; obj_link->next_ = next_link; link_type* const initial_next_prev = next_link->prev_; obj_link->prev_ = initial_next_prev; initial_next_prev->next_ = obj_link; next_link->prev_ = obj_link; return iterator(obj_link); } template <typename QualifiedT, typename QualifiedLinkT> class QUICHE_EXPORT iterator_impl { public: using iterator_category = std::bidirectional_iterator_tag; using value_type = QualifiedT; using difference_type = std::ptrdiff_t; using pointer = QualifiedT*; using reference = QualifiedT&; iterator_impl() = default; iterator_impl(QualifiedLinkT* link) : link_(link) {} iterator_impl(const iterator_impl& x) = default; iterator_impl& operator=(const iterator_impl& x) = default; template <typename U, typename V> iterator_impl(const iterator_impl<U, V>& x) : link_(x.link_) {} template <typename U, typename V> bool operator==(const iterator_impl<U, V>& x) const { return link_ == x.link_; } template <typename U, typename V> bool operator!=(const iterator_impl<U, V>& x) const { return link_ != x.link_; } reference operator*() const { return *operator->(); } pointer operator->() const { return link_->cast_to_derived(); } QualifiedLinkT* link() const { return link_; } #ifndef SWIG iterator_impl& operator++() { link_ = link_->next_; return *this; } iterator_impl operator++(int ) { iterator_impl tmp = *this; ++*this; return tmp; } iterator_impl& operator--() { link_ = link_->prev_; return *this; } iterator_impl operator--(int ) { iterator_impl tmp = *this; --*this; return tmp; } #endif private: template <typename U, typename V> friend class iterator_impl; QualifiedLinkT* link_ = nullptr; }; link_type sentinel_link_; QuicheIntrusiveList(const QuicheIntrusiveList&); void operator=(const QuicheIntrusiveList&); }; } #endif
#include "quiche/common/quiche_intrusive_list.h" #include <algorithm> #include <iterator> #include <list> #include <string> #include <utility> #include "quiche/common/platform/api/quiche_test.h" namespace quiche { namespace test { struct ListId2 {}; struct TestItem : public QuicheIntrusiveLink<TestItem>, public QuicheIntrusiveLink<TestItem, ListId2> { int n; }; typedef QuicheIntrusiveList<TestItem> TestList; typedef std::list<TestItem *> CanonicalList; void swap(TestItem &a, TestItem &b) { using std::swap; swap(a.n, b.n); } class IntrusiveListTest : public quiche::test::QuicheTest { protected: void CheckLists() { CheckLists(l1, ll1); if (quiche::test::QuicheTest::HasFailure()) return; CheckLists(l2, ll2); } void CheckLists(const TestList &list_a, const CanonicalList &list_b) { ASSERT_EQ(list_a.size(), list_b.size()); TestList::const_iterator it_a = list_a.begin(); CanonicalList::const_iterator it_b = list_b.begin(); while (it_a != list_a.end()) { EXPECT_EQ(&*it_a++, *it_b++); } EXPECT_EQ(list_a.end(), it_a); EXPECT_EQ(list_b.end(), it_b); } void PrepareLists(int num_elems_1, int num_elems_2 = 0) { FillLists(&l1, &ll1, e, num_elems_1); FillLists(&l2, &ll2, e + num_elems_1, num_elems_2); } void FillLists(TestList *list_a, CanonicalList *list_b, TestItem *elems, int num_elems) { list_a->clear(); list_b->clear(); for (int i = 0; i < num_elems; ++i) { list_a->push_back(elems + i); list_b->push_back(elems + i); } CheckLists(*list_a, *list_b); } TestItem e[10]; TestList l1, l2; CanonicalList ll1, ll2; }; TEST(NewIntrusiveListTest, Basic) { TestList list1; EXPECT_EQ(sizeof(QuicheIntrusiveLink<TestItem>), sizeof(void *) * 2); for (int i = 0; i < 10; ++i) { TestItem *e = new TestItem; e->n = i; list1.push_front(e); } EXPECT_EQ(list1.size(), 10u); std::reverse(list1.begin(), list1.end()); EXPECT_EQ(list1.size(), 10u); const TestList &clist1 = list1; int i = 0; TestList::iterator iter = list1.begin(); for (; iter != list1.end(); ++iter, ++i) { EXPECT_EQ(iter->n, i); } EXPECT_EQ(iter, clist1.end()); EXPECT_NE(iter, clist1.begin()); i = 0; iter = list1.begin(); for (; iter != list1.end(); ++iter, ++i) { EXPECT_EQ(iter->n, i); } EXPECT_EQ(iter, clist1.end()); EXPECT_NE(iter, clist1.begin()); EXPECT_EQ(list1.front().n, 0); EXPECT_EQ(list1.back().n, 9); TestList list2; list2.swap(list1); EXPECT_EQ(list1.size(), 0u); EXPECT_EQ(list2.size(), 10u); const TestList &clist2 = list2; TestList::reverse_iterator riter = list2.rbegin(); i = 9; for (; riter != list2.rend(); ++riter, --i) { EXPECT_EQ(riter->n, i); } EXPECT_EQ(riter, clist2.rend()); EXPECT_NE(riter, clist2.rbegin()); riter = list2.rbegin(); i = 9; for (; riter != list2.rend(); ++riter, --i) { EXPECT_EQ(riter->n, i); } EXPECT_EQ(riter, clist2.rend()); EXPECT_NE(riter, clist2.rbegin()); while (!list2.empty()) { TestItem *e = &list2.front(); list2.pop_front(); delete e; } } TEST(NewIntrusiveListTest, Erase) { TestList l; TestItem *e[10]; for (int i = 0; i < 10; ++i) { e[i] = new TestItem; l.push_front(e[i]); } for (int i = 0; i < 10; ++i) { EXPECT_EQ(l.size(), (10u - i)); TestList::iterator iter = l.erase(e[i]); EXPECT_NE(iter, TestList::iterator(e[i])); EXPECT_EQ(l.size(), (10u - i - 1)); delete e[i]; } } TEST(NewIntrusiveListTest, Insert) { TestList l; TestList::iterator iter = l.end(); TestItem *e[10]; for (int i = 9; i >= 0; --i) { e[i] = new TestItem; iter = l.insert(iter, e[i]); EXPECT_EQ(&(*iter), e[i]); } EXPECT_EQ(l.size(), 10u); iter = l.begin(); for (TestItem *item : e) { EXPECT_EQ(&(*iter), item); iter = l.erase(item); delete item; } } TEST(NewIntrusiveListTest, Move) { { TestList src; TestList dest(std::move(src)); EXPECT_TRUE(dest.empty()); } { TestItem e; TestList src; src.push_front(&e); TestList dest(std::move(src)); EXPECT_TRUE(src.empty()); ASSERT_THAT(dest.size(), 1); EXPECT_THAT(&dest.front(), &e); EXPECT_THAT(&dest.back(), &e); } { TestItem items[10]; TestList src; for (TestItem &e : items) src.push_back(&e); TestList dest(std::move(src)); EXPECT_TRUE(src.empty()); ASSERT_THAT(dest.size(), 10); int i = 0; for (TestItem &e : dest) { EXPECT_THAT(&e, &items[i++]) << " for index " << i; } } } TEST(NewIntrusiveListTest, StaticInsertErase) { TestList l; TestItem e[2]; TestList::iterator i = l.begin(); TestList::insert(i, &e[0]); TestList::insert(&e[0], &e[1]); TestList::erase(&e[0]); TestList::erase(TestList::iterator(&e[1])); EXPECT_TRUE(l.empty()); } TEST_F(IntrusiveListTest, Splice) { QuicheIntrusiveList<TestItem, ListId2> secondary_list; for (int i = 0; i < 3; ++i) { secondary_list.push_back(&e[i]); } for (int l1_count = 0; l1_count < 3; ++l1_count) { for (int l2_count = 0; l2_count < 3; ++l2_count) { for (int pos = 0; pos <= l1_count; ++pos) { for (int first = 0; first <= l2_count; ++first) { for (int last = first; last <= l2_count; ++last) { PrepareLists(l1_count, l2_count); l1.splice(std::next(l1.begin(), pos), std::next(l2.begin(), first), std::next(l2.begin(), last)); ll1.splice(std::next(ll1.begin(), pos), ll2, std::next(ll2.begin(), first), std::next(ll2.begin(), last)); CheckLists(); ASSERT_EQ(3u, secondary_list.size()); for (int i = 0; i < 3; ++i) { EXPECT_EQ(&e[i], &*std::next(secondary_list.begin(), i)); } } } } } } } struct BaseLinkId {}; struct DerivedLinkId {}; struct AbstractBase : public QuicheIntrusiveLink<AbstractBase, BaseLinkId> { virtual ~AbstractBase() = 0; virtual std::string name() { return "AbstractBase"; } }; AbstractBase::~AbstractBase() {} struct DerivedClass : public QuicheIntrusiveLink<DerivedClass, DerivedLinkId>, public AbstractBase { ~DerivedClass() override {} std::string name() override { return "DerivedClass"; } }; struct VirtuallyDerivedBaseClass : public virtual AbstractBase { ~VirtuallyDerivedBaseClass() override = 0; std::string name() override { return "VirtuallyDerivedBaseClass"; } }; VirtuallyDerivedBaseClass::~VirtuallyDerivedBaseClass() {} struct VirtuallyDerivedClassA : public QuicheIntrusiveLink<VirtuallyDerivedClassA, DerivedLinkId>, public virtual VirtuallyDerivedBaseClass { ~VirtuallyDerivedClassA() override {} std::string name() override { return "VirtuallyDerivedClassA"; } }; struct NonceClass { virtual ~NonceClass() {} int data_; }; struct VirtuallyDerivedClassB : public QuicheIntrusiveLink<VirtuallyDerivedClassB, DerivedLinkId>, public virtual NonceClass, public virtual VirtuallyDerivedBaseClass { ~VirtuallyDerivedClassB() override {} std::string name() override { return "VirtuallyDerivedClassB"; } }; struct VirtuallyDerivedClassC : public QuicheIntrusiveLink<VirtuallyDerivedClassC, DerivedLinkId>, public virtual AbstractBase, public virtual NonceClass, public virtual VirtuallyDerivedBaseClass { ~VirtuallyDerivedClassC() override {} std::string name() override { return "VirtuallyDerivedClassC"; } }; namespace templated_base_link { template <typename T> struct AbstractBase : public QuicheIntrusiveLink<T> { virtual ~AbstractBase() = 0; }; template <typename T> AbstractBase<T>::~AbstractBase() {} struct DerivedClass : public AbstractBase<DerivedClass> { int n; }; } TEST(NewIntrusiveListTest, HandleInheritanceHierarchies) { { QuicheIntrusiveList<DerivedClass, DerivedLinkId> list; DerivedClass elements[2]; EXPECT_TRUE(list.empty()); list.push_back(&elements[0]); EXPECT_EQ(1u, list.size()); list.push_back(&elements[1]); EXPECT_EQ(2u, list.size()); list.pop_back(); EXPECT_EQ(1u, list.size()); list.pop_back(); EXPECT_TRUE(list.empty()); } { QuicheIntrusiveList<VirtuallyDerivedClassA, DerivedLinkId> list; VirtuallyDerivedClassA elements[2]; EXPECT_TRUE(list.empty()); list.push_back(&elements[0]); EXPECT_EQ(1u, list.size()); list.push_back(&elements[1]); EXPECT_EQ(2u, list.size()); list.pop_back(); EXPECT_EQ(1u, list.size()); list.pop_back(); EXPECT_TRUE(list.empty()); } { QuicheIntrusiveList<VirtuallyDerivedClassC, DerivedLinkId> list; VirtuallyDerivedClassC elements[2]; EXPECT_TRUE(list.empty()); list.push_back(&elements[0]); EXPECT_EQ(1u, list.size()); list.push_back(&elements[1]); EXPECT_EQ(2u, list.size()); list.pop_back(); EXPECT_EQ(1u, list.size()); list.pop_back(); EXPECT_TRUE(list.empty()); } { QuicheIntrusiveList<AbstractBase, BaseLinkId> list; DerivedClass d1; VirtuallyDerivedClassA d2; VirtuallyDerivedClassB d3; VirtuallyDerivedClassC d4; EXPECT_TRUE(list.empty()); list.push_back(&d1); EXPECT_EQ(1u, list.size()); list.push_back(&d2); EXPECT_EQ(2u, list.size()); list.push_back(&d3); EXPECT_EQ(3u, list.size()); list.push_back(&d4); EXPECT_EQ(4u, list.size()); QuicheIntrusiveList<AbstractBase, BaseLinkId>::iterator it = list.begin(); EXPECT_EQ("DerivedClass", (it++)->name()); EXPECT_EQ("VirtuallyDerivedClassA", (it++)->name()); EXPECT_EQ("VirtuallyDerivedClassB", (it++)->name()); EXPECT_EQ("VirtuallyDerivedClassC", (it++)->name()); } { QuicheIntrusiveList<templated_base_link::DerivedClass> list; templated_base_link::DerivedClass elements[2]; EXPECT_TRUE(list.empty()); list.push_back(&elements[0]); EXPECT_EQ(1u, list.size()); list.push_back(&elements[1]); EXPECT_EQ(2u, list.size()); list.pop_back(); EXPECT_EQ(1u, list.size()); list.pop_back(); EXPECT_TRUE(list.empty()); } } class IntrusiveListTagTypeTest : public quiche::test::QuicheTest { protected: struct Tag {}; class Element : public QuicheIntrusiveLink<Element, Tag> {}; }; TEST_F(IntrusiveListTagTypeTest, TagTypeListID) { QuicheIntrusiveList<Element, Tag> list; { Element e; list.push_back(&e); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/quiche_intrusive_list.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/quiche_intrusive_list_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
bdecb66a-e4c2-4a63-858d-085c8dc2db48
cpp
google/quiche
quiche_callbacks
quiche/common/quiche_callbacks.h
quiche/common/quiche_callbacks_test.cc
#ifndef QUICHE_COMMON_QUICHE_CALLBACKS_H_ #define QUICHE_COMMON_QUICHE_CALLBACKS_H_ #include <type_traits> #include "absl/functional/any_invocable.h" #include "absl/functional/function_ref.h" #include "quiche/common/platform/api/quiche_export.h" namespace quiche { namespace callbacks_internal { template <class Sig> class QUICHE_EXPORT SignatureChanger {}; template <typename ReturnType, typename... Args> class QUICHE_NO_EXPORT SignatureChanger<ReturnType(Args...)> { public: using Rvalue = ReturnType(Args...) &&; using Const = ReturnType(Args...) const; }; } template <class T> using UnretainedCallback = absl::FunctionRef<T>; template <class T> using SingleUseCallback = absl::AnyInvocable< typename callbacks_internal::SignatureChanger<T>::Rvalue>; static_assert(std::is_same_v<SingleUseCallback<void(int, int &, int &&)>, absl::AnyInvocable<void(int, int &, int &&) &&>>); template <class T> using MultiUseCallback = absl::AnyInvocable<typename callbacks_internal::SignatureChanger<T>::Const>; static_assert( std::is_same_v<MultiUseCallback<void()>, absl::AnyInvocable<void() const>>); } #endif
#include "quiche/common/quiche_callbacks.h" #include <memory> #include <utility> #include <vector> #include "quiche/common/platform/api/quiche_test.h" namespace quiche { namespace { void Apply(const std::vector<int>& container, UnretainedCallback<void(int)> function) { for (int n : container) { function(n); } } TEST(QuicheCallbacksTest, UnretainedCallback) { std::vector<int> nums = {1, 2, 3, 4}; int sum = 0; Apply(nums, [&sum](int n) { sum += n; }); EXPECT_EQ(sum, 10); } TEST(QuicheCallbacksTest, SingleUseCallback) { int called = 0; SingleUseCallback<void()> callback = [&called]() { called++; }; EXPECT_EQ(called, 0); SingleUseCallback<void()> new_callback = std::move(callback); EXPECT_EQ(called, 0); std::move(new_callback)(); EXPECT_EQ(called, 1); EXPECT_QUICHE_DEBUG_DEATH( std::move(new_callback)(), "AnyInvocable"); } class SetFlagOnDestruction { public: SetFlagOnDestruction(bool* flag) : flag_(flag) {} ~SetFlagOnDestruction() { *flag_ = true; } private: bool* flag_; }; TEST(QuicheCallbacksTest, SingleUseCallbackOwnership) { bool deleted = false; auto flag_setter = std::make_unique<SetFlagOnDestruction>(&deleted); { SingleUseCallback<void()> callback = [setter = std::move(flag_setter)]() {}; EXPECT_FALSE(deleted); } EXPECT_TRUE(deleted); } TEST(QuicheCallbacksTest, MultiUseCallback) { int called = 0; MultiUseCallback<void()> callback = [&called]() { called++; }; EXPECT_EQ(called, 0); callback(); EXPECT_EQ(called, 1); callback(); callback(); EXPECT_EQ(called, 3); } TEST(QuicheCallbacksTest, MultiUseCallbackOwnership) { bool deleted = false; auto flag_setter = std::make_unique<SetFlagOnDestruction>(&deleted); { MultiUseCallback<void()> callback = [setter = std::move(flag_setter)]() {}; EXPECT_FALSE(deleted); } EXPECT_TRUE(deleted); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/quiche_callbacks.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/quiche_callbacks_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
23685236-e6b3-4b48-baa2-5eeb90ec2264
cpp
google/quiche
quiche_endian
quiche/common/quiche_endian.h
quiche/common/quiche_endian_test.cc
#ifndef QUICHE_COMMON_QUICHE_ENDIAN_H_ #define QUICHE_COMMON_QUICHE_ENDIAN_H_ #include <algorithm> #include <cstdint> #include <type_traits> #include "quiche/common/platform/api/quiche_export.h" namespace quiche { enum Endianness { NETWORK_BYTE_ORDER, HOST_BYTE_ORDER }; class QUICHE_EXPORT QuicheEndian { public: #if defined(__clang__) || \ (defined(__GNUC__) && \ ((__GNUC__ == 4 && __GNUC_MINOR__ >= 8) || __GNUC__ >= 5)) static uint16_t HostToNet16(uint16_t x) { return __builtin_bswap16(x); } static uint32_t HostToNet32(uint32_t x) { return __builtin_bswap32(x); } static uint64_t HostToNet64(uint64_t x) { return __builtin_bswap64(x); } #else static uint16_t HostToNet16(uint16_t x) { return PortableByteSwap(x); } static uint32_t HostToNet32(uint32_t x) { return PortableByteSwap(x); } static uint64_t HostToNet64(uint64_t x) { return PortableByteSwap(x); } #endif static uint16_t NetToHost16(uint16_t x) { return HostToNet16(x); } static uint32_t NetToHost32(uint32_t x) { return HostToNet32(x); } static uint64_t NetToHost64(uint64_t x) { return HostToNet64(x); } template <typename T> static T PortableByteSwap(T input) { static_assert(std::is_unsigned<T>::value, "T has to be uintNN_t"); union { T number; char bytes[sizeof(T)]; } value; value.number = input; std::reverse(&value.bytes[0], &value.bytes[sizeof(T)]); return value.number; } }; enum QuicheVariableLengthIntegerLength : uint8_t { VARIABLE_LENGTH_INTEGER_LENGTH_0 = 0, VARIABLE_LENGTH_INTEGER_LENGTH_1 = 1, VARIABLE_LENGTH_INTEGER_LENGTH_2 = 2, VARIABLE_LENGTH_INTEGER_LENGTH_4 = 4, VARIABLE_LENGTH_INTEGER_LENGTH_8 = 8, kQuicheDefaultLongHeaderLengthLength = VARIABLE_LENGTH_INTEGER_LENGTH_2, }; } #endif
#include "quiche/common/quiche_endian.h" #include "quiche/common/platform/api/quiche_test.h" namespace quiche { namespace test { namespace { const uint16_t k16BitTestData = 0xaabb; const uint16_t k16BitSwappedTestData = 0xbbaa; const uint32_t k32BitTestData = 0xaabbccdd; const uint32_t k32BitSwappedTestData = 0xddccbbaa; const uint64_t k64BitTestData = 0xaabbccdd44332211; const uint64_t k64BitSwappedTestData = 0x11223344ddccbbaa; class QuicheEndianTest : public QuicheTest {}; TEST_F(QuicheEndianTest, Portable) { EXPECT_EQ(k16BitSwappedTestData, QuicheEndian::PortableByteSwap(k16BitTestData)); EXPECT_EQ(k32BitSwappedTestData, QuicheEndian::PortableByteSwap(k32BitTestData)); EXPECT_EQ(k64BitSwappedTestData, QuicheEndian::PortableByteSwap(k64BitTestData)); } TEST_F(QuicheEndianTest, HostToNet) { EXPECT_EQ(k16BitSwappedTestData, quiche::QuicheEndian::HostToNet16(k16BitTestData)); EXPECT_EQ(k32BitSwappedTestData, quiche::QuicheEndian::HostToNet32(k32BitTestData)); EXPECT_EQ(k64BitSwappedTestData, quiche::QuicheEndian::HostToNet64(k64BitTestData)); } TEST_F(QuicheEndianTest, NetToHost) { EXPECT_EQ(k16BitTestData, quiche::QuicheEndian::NetToHost16(k16BitSwappedTestData)); EXPECT_EQ(k32BitTestData, quiche::QuicheEndian::NetToHost32(k32BitSwappedTestData)); EXPECT_EQ(k64BitTestData, quiche::QuicheEndian::NetToHost64(k64BitSwappedTestData)); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/quiche_endian.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/quiche_endian_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
1e2fd98c-981e-43d2-8f71-65c64b1a1825
cpp
google/quiche
mock_streams
quiche/common/test_tools/mock_streams.h
quiche/common/test_tools/mock_streams_test.cc
#ifndef QUICHE_COMMON_TEST_TOOLS_MOCK_STREAMS_H_ #define QUICHE_COMMON_TEST_TOOLS_MOCK_STREAMS_H_ #include <algorithm> #include <cstddef> #include <string> #include <utility> #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/quiche_stream.h" namespace quiche::test { class MockWriteStream : public quiche::WriteStream { public: MockWriteStream() { ON_CALL(*this, CanWrite()).WillByDefault(testing::Return(true)); ON_CALL(*this, Writev(testing::_, testing::_)) .WillByDefault([&](absl::Span<const absl::string_view> data, const StreamWriteOptions& options) { return AppendToData(data, options); }); } MOCK_METHOD(absl::Status, Writev, (absl::Span<const absl::string_view> data, const StreamWriteOptions& options), (override)); MOCK_METHOD(bool, CanWrite, (), (const, override)); absl::Status AppendToData(absl::Span<const absl::string_view> data, const StreamWriteOptions& options) { for (absl::string_view fragment : data) { data_.append(fragment.data(), fragment.size()); } ProcessOptions(options); return absl::OkStatus(); } void ProcessOptions(const StreamWriteOptions& options) { fin_written_ |= options.send_fin(); } std::string& data() { return data_; } bool fin_written() { return fin_written_; } private: std::string data_; bool fin_written_ = false; }; class ReadStreamFromString : public ReadStream { public: explicit ReadStreamFromString(std::string* data) : data_(data) {} ReadResult Read(absl::Span<char> buffer) override { size_t data_to_copy = std::min(buffer.size(), data_->size()); std::copy(data_->begin(), data_->begin() + data_to_copy, buffer.begin()); *data_ = data_->substr(data_to_copy); return ReadResult{data_to_copy, data_->empty() && fin_}; } ReadResult Read(std::string* output) override { size_t bytes = data_->size(); output->append(std::move(*data_)); data_->clear(); return ReadResult{bytes, fin_}; } size_t ReadableBytes() const override { return data_->size(); } virtual PeekResult PeekNextReadableRegion() const override { PeekResult result; result.peeked_data = *data_; result.fin_next = data_->empty() && fin_; result.all_data_received = fin_; return result; } bool SkipBytes(size_t bytes) override { *data_ = data_->substr(bytes); return data_->empty() && fin_; } void set_fin() { fin_ = true; } private: std::string* data_; bool fin_ = false; }; } #endif
#include "quiche/common/test_tools/mock_streams.h" #include <array> #include <string> #include "absl/types/span.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/quiche_stream.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace quiche::test { namespace { using ::testing::ElementsAre; using ::testing::IsEmpty; TEST(MockWriteStreamTest, DefaultWrite) { MockWriteStream stream; QUICHE_EXPECT_OK(quiche::WriteIntoStream(stream, "test")); EXPECT_EQ(stream.data(), "test"); EXPECT_FALSE(stream.fin_written()); } TEST(ReadStreamFromStringTest, ReadIntoSpan) { std::string source = "abcdef"; std::array<char, 3> buffer; ReadStreamFromString stream(&source); EXPECT_EQ(stream.ReadableBytes(), 6); stream.Read(absl::MakeSpan(buffer)); EXPECT_THAT(buffer, ElementsAre('a', 'b', 'c')); EXPECT_EQ(stream.ReadableBytes(), 3); stream.Read(absl::MakeSpan(buffer)); EXPECT_THAT(buffer, ElementsAre('d', 'e', 'f')); EXPECT_EQ(stream.ReadableBytes(), 0); EXPECT_THAT(source, IsEmpty()); } TEST(ReadStreamFromStringTest, ReadIntoString) { std::string source = "abcdef"; std::string destination; ReadStreamFromString stream(&source); stream.Read(&destination); EXPECT_EQ(destination, "abcdef"); EXPECT_THAT(source, IsEmpty()); } TEST(ReadStreamFromStringTest, PeekAndSkip) { std::string source = "abcdef"; ReadStreamFromString stream(&source); EXPECT_EQ(stream.PeekNextReadableRegion().peeked_data, "abcdef"); stream.SkipBytes(2); EXPECT_EQ(stream.PeekNextReadableRegion().peeked_data, "cdef"); EXPECT_EQ(source, "cdef"); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/test_tools/mock_streams.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/test_tools/mock_streams_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
8c9a6d30-6696-4abf-84bf-5fb88854d093
cpp
google/quiche
quiche_time_utils
quiche/common/platform/api/quiche_time_utils.h
quiche/common/platform/api/quiche_time_utils_test.cc
#ifndef QUICHE_COMMON_PLATFORM_API_QUICHE_TIME_UTILS_H_ #define QUICHE_COMMON_PLATFORM_API_QUICHE_TIME_UTILS_H_ #include <cstdint> #include "quiche_platform_impl/quiche_time_utils_impl.h" namespace quiche { inline std::optional<int64_t> QuicheUtcDateTimeToUnixSeconds( int year, int month, int day, int hour, int minute, int second) { return QuicheUtcDateTimeToUnixSecondsImpl(year, month, day, hour, minute, second); } } #endif
#include "quiche/common/platform/api/quiche_time_utils.h" #include <optional> #include "quiche/common/platform/api/quiche_test.h" namespace quiche { namespace { TEST(QuicheTimeUtilsTest, Basic) { EXPECT_EQ(1, QuicheUtcDateTimeToUnixSeconds(1970, 1, 1, 0, 0, 1)); EXPECT_EQ(365 * 86400, QuicheUtcDateTimeToUnixSeconds(1971, 1, 1, 0, 0, 0)); EXPECT_EQ(1152966896, QuicheUtcDateTimeToUnixSeconds(2006, 7, 15, 12, 34, 56)); EXPECT_EQ(1591130001, QuicheUtcDateTimeToUnixSeconds(2020, 6, 2, 20, 33, 21)); EXPECT_EQ(std::nullopt, QuicheUtcDateTimeToUnixSeconds(1970, 2, 29, 0, 0, 1)); EXPECT_NE(std::nullopt, QuicheUtcDateTimeToUnixSeconds(1972, 2, 29, 0, 0, 1)); } TEST(QuicheTimeUtilsTest, Bounds) { EXPECT_EQ(std::nullopt, QuicheUtcDateTimeToUnixSeconds(1970, 1, 32, 0, 0, 1)); EXPECT_EQ(std::nullopt, QuicheUtcDateTimeToUnixSeconds(1970, 4, 31, 0, 0, 1)); EXPECT_EQ(std::nullopt, QuicheUtcDateTimeToUnixSeconds(1970, 1, 0, 0, 0, 1)); EXPECT_EQ(std::nullopt, QuicheUtcDateTimeToUnixSeconds(1970, 13, 1, 0, 0, 1)); EXPECT_EQ(std::nullopt, QuicheUtcDateTimeToUnixSeconds(1970, 0, 1, 0, 0, 1)); EXPECT_EQ(std::nullopt, QuicheUtcDateTimeToUnixSeconds(1970, 1, 1, 24, 0, 0)); EXPECT_EQ(std::nullopt, QuicheUtcDateTimeToUnixSeconds(1970, 1, 1, 0, 60, 0)); } TEST(QuicheTimeUtilsTest, LeapSecond) { EXPECT_EQ(QuicheUtcDateTimeToUnixSeconds(2015, 6, 30, 23, 59, 60), QuicheUtcDateTimeToUnixSeconds(2015, 7, 1, 0, 0, 0)); EXPECT_EQ(QuicheUtcDateTimeToUnixSeconds(2015, 6, 30, 25, 59, 60), std::nullopt); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/platform/api/quiche_time_utils.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/platform/api/quiche_time_utils_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
c1b32f96-8037-495e-84ce-029851f2e85d
cpp
google/quiche
quiche_stack_trace
quiche/common/platform/api/quiche_stack_trace.h
quiche/common/platform/api/quiche_stack_trace_test.cc
#ifndef QUICHE_COMMON_PLATFORM_API_QUICHE_STACK_TRACE_H_ #define QUICHE_COMMON_PLATFORM_API_QUICHE_STACK_TRACE_H_ #include <string> #include <vector> #include "absl/types/span.h" #include "quiche_platform_impl/quiche_stack_trace_impl.h" namespace quiche { inline std::vector<void*> CurrentStackTrace() { return CurrentStackTraceImpl(); } inline std::string SymbolizeStackTrace(absl::Span<void* const> stacktrace) { return SymbolizeStackTraceImpl(stacktrace); } inline std::string QuicheStackTrace() { return QuicheStackTraceImpl(); } inline bool QuicheShouldRunStackTraceTest() { return QuicheShouldRunStackTraceTestImpl(); } } #endif
#include "quiche/common/platform/api/quiche_stack_trace.h" #include <cstdint> #include <string> #include "absl/base/attributes.h" #include "absl/base/optimization.h" #include "absl/strings/str_cat.h" #include "quiche/common/platform/api/quiche_test.h" namespace quiche { namespace test { namespace { bool ShouldRunTest() { #if defined(ABSL_HAVE_ATTRIBUTE_NOINLINE) return QuicheShouldRunStackTraceTest(); #else return false; #endif } ABSL_ATTRIBUTE_NOINLINE std::string QuicheDesignatedStackTraceTestFunction() { std::string result = QuicheStackTrace(); ABSL_BLOCK_TAIL_CALL_OPTIMIZATION(); return result; } ABSL_ATTRIBUTE_NOINLINE std::string QuicheDesignatedTwoStepStackTraceTestFunction() { std::string result = SymbolizeStackTrace(CurrentStackTrace()); ABSL_BLOCK_TAIL_CALL_OPTIMIZATION(); return result; } TEST(QuicheStackTraceTest, GetStackTrace) { if (!ShouldRunTest()) { return; } std::string stacktrace = QuicheDesignatedStackTraceTestFunction(); EXPECT_THAT(stacktrace, testing::HasSubstr("QuicheDesignatedStackTraceTestFunction")); } TEST(QuicheStackTraceTest, GetStackTraceInTwoSteps) { if (!ShouldRunTest()) { return; } std::string stacktrace = QuicheDesignatedTwoStepStackTraceTestFunction(); EXPECT_THAT(stacktrace, testing::HasSubstr( "QuicheDesignatedTwoStepStackTraceTestFunction")); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/platform/api/quiche_stack_trace.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/platform/api/quiche_stack_trace_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
741a8acf-0983-4e02-8eed-1d05cff25054
cpp
google/quiche
quiche_url_utils
quiche/common/platform/api/quiche_url_utils.h
quiche/common/platform/api/quiche_url_utils_test.cc
#ifndef QUICHE_COMMON_PLATFORM_API_QUICHE_URL_UTILS_H_ #define QUICHE_COMMON_PLATFORM_API_QUICHE_URL_UTILS_H_ #include <optional> #include <string> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/strings/string_view.h" #include "quiche_platform_impl/quiche_url_utils_impl.h" namespace quiche { inline bool ExpandURITemplate( const std::string& uri_template, const absl::flat_hash_map<std::string, std::string>& parameters, std::string* target, absl::flat_hash_set<std::string>* vars_found = nullptr) { return ExpandURITemplateImpl(uri_template, parameters, target, vars_found); } inline std::optional<std::string> AsciiUrlDecode(absl::string_view input) { return AsciiUrlDecodeImpl(input); } } #endif
#include "quiche/common/platform/api/quiche_url_utils.h" #include <optional> #include <set> #include <string> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "quiche/common/platform/api/quiche_test.h" namespace quiche { namespace { void ValidateExpansion( const std::string& uri_template, const absl::flat_hash_map<std::string, std::string>& parameters, const std::string& expected_expansion, const absl::flat_hash_set<std::string>& expected_vars_found) { absl::flat_hash_set<std::string> vars_found; std::string target; ASSERT_TRUE( ExpandURITemplate(uri_template, parameters, &target, &vars_found)); EXPECT_EQ(expected_expansion, target); EXPECT_EQ(vars_found, expected_vars_found); } TEST(QuicheUrlUtilsTest, Basic) { ValidateExpansion("/{foo}/{bar}/", {{"foo", "123"}, {"bar", "456"}}, "/123/456/", {"foo", "bar"}); } TEST(QuicheUrlUtilsTest, ExtraParameter) { ValidateExpansion("/{foo}/{bar}/{baz}/", {{"foo", "123"}, {"bar", "456"}}, "/123/456 } TEST(QuicheUrlUtilsTest, MissingParameter) { ValidateExpansion("/{foo}/{baz}/", {{"foo", "123"}, {"bar", "456"}}, "/123 {"foo"}); } TEST(QuicheUrlUtilsTest, RepeatedParameter) { ValidateExpansion("/{foo}/{bar}/{foo}/", {{"foo", "123"}, {"bar", "456"}}, "/123/456/123/", {"foo", "bar"}); } TEST(QuicheUrlUtilsTest, URLEncoding) { ValidateExpansion("/{foo}/{bar}/", {{"foo", "123"}, {"bar", ":"}}, "/123/%3A/", {"foo", "bar"}); } void ValidateUrlDecode(const std::string& input, const std::optional<std::string>& expected_output) { std::optional<std::string> decode_result = AsciiUrlDecode(input); if (!expected_output.has_value()) { EXPECT_FALSE(decode_result.has_value()); return; } ASSERT_TRUE(decode_result.has_value()); EXPECT_EQ(decode_result.value(), expected_output); } TEST(QuicheUrlUtilsTest, DecodeNoChange) { ValidateUrlDecode("foobar", "foobar"); } TEST(QuicheUrlUtilsTest, DecodeReplace) { ValidateUrlDecode("%7Bfoobar%7D", "{foobar}"); } TEST(QuicheUrlUtilsTest, DecodeFail) { ValidateUrlDecode("%FF", std::nullopt); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/platform/api/quiche_url_utils.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/platform/api/quiche_url_utils_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
2d10528f-a1a6-4888-a5d3-6ca40943cf7b
cpp
google/quiche
quiche_lower_case_string
quiche/common/platform/api/quiche_lower_case_string.h
quiche/common/platform/api/quiche_lower_case_string_test.cc
#ifndef QUICHE_COMMON_PLATFORM_API_QUICHE_LOWER_CASE_STRING_H_ #define QUICHE_COMMON_PLATFORM_API_QUICHE_LOWER_CASE_STRING_H_ #include "quiche_platform_impl/quiche_lower_case_string_impl.h" namespace quiche { using QuicheLowerCaseString = QuicheLowerCaseStringImpl; } #endif
#include "quiche/common/platform/api/quiche_lower_case_string.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_test.h" namespace quiche::test { namespace { TEST(QuicheLowerCaseString, Basic) { QuicheLowerCaseString empty(""); EXPECT_EQ("", empty.get()); QuicheLowerCaseString from_lower_case("foo"); EXPECT_EQ("foo", from_lower_case.get()); QuicheLowerCaseString from_mixed_case("BaR"); EXPECT_EQ("bar", from_mixed_case.get()); const absl::string_view kData = "FooBar"; QuicheLowerCaseString from_string_view(kData); EXPECT_EQ("foobar", from_string_view.get()); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/platform/api/quiche_lower_case_string.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/platform/api/quiche_lower_case_string_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
275d8910-5c63-4163-bbf3-e993c68436c4
cpp
google/quiche
quiche_mem_slice
quiche/common/platform/api/quiche_mem_slice.h
quiche/common/platform/api/quiche_mem_slice_test.cc
#ifndef QUICHE_COMMON_PLATFORM_API_QUICHE_MEM_SLICE_H_ #define QUICHE_COMMON_PLATFORM_API_QUICHE_MEM_SLICE_H_ #include <cstddef> #include <memory> #include <utility> #include "quiche_platform_impl/quiche_mem_slice_impl.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/quiche_buffer_allocator.h" #include "quiche/common/quiche_callbacks.h" namespace quiche { class QUICHE_EXPORT QuicheMemSlice { public: QuicheMemSlice() = default; explicit QuicheMemSlice(QuicheBuffer buffer) : impl_(std::move(buffer)) {} QuicheMemSlice(std::unique_ptr<char[]> buffer, size_t length) : impl_(std::move(buffer), length) {} QuicheMemSlice(const char* buffer, size_t length, quiche::SingleUseCallback<void(const char*)> done_callback) : impl_(buffer, length, std::move(done_callback)) {} struct InPlace {}; template <typename... Args> explicit QuicheMemSlice(InPlace, Args&&... args) : impl_{std::forward<Args>(args)...} {} QuicheMemSlice(const QuicheMemSlice& other) = delete; QuicheMemSlice& operator=(const QuicheMemSlice& other) = delete; QuicheMemSlice(QuicheMemSlice&& other) = default; QuicheMemSlice& operator=(QuicheMemSlice&& other) = default; ~QuicheMemSlice() = default; void Reset() { impl_.Reset(); } const char* data() const { return impl_.data(); } size_t length() const { return impl_.length(); } absl::string_view AsStringView() const { return absl::string_view(data(), length()); } bool empty() const { return impl_.empty(); } private: QuicheMemSliceImpl impl_; }; } #endif
#include "quiche/common/platform/api/quiche_mem_slice.h" #include <cstring> #include <memory> #include <utility> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/quiche_buffer_allocator.h" #include "quiche/common/quiche_callbacks.h" #include "quiche/common/simple_buffer_allocator.h" namespace quiche { namespace test { namespace { class QuicheMemSliceTest : public QuicheTest { public: QuicheMemSliceTest() { size_t length = 1024; slice_ = QuicheMemSlice(QuicheBuffer(&allocator_, length)); orig_data_ = slice_.data(); orig_length_ = slice_.length(); } SimpleBufferAllocator allocator_; QuicheMemSlice slice_; const char* orig_data_; size_t orig_length_; }; TEST_F(QuicheMemSliceTest, MoveConstruct) { QuicheMemSlice moved(std::move(slice_)); EXPECT_EQ(moved.data(), orig_data_); EXPECT_EQ(moved.length(), orig_length_); EXPECT_EQ(nullptr, slice_.data()); EXPECT_EQ(0u, slice_.length()); EXPECT_TRUE(slice_.empty()); } TEST_F(QuicheMemSliceTest, MoveAssign) { QuicheMemSlice moved; moved = std::move(slice_); EXPECT_EQ(moved.data(), orig_data_); EXPECT_EQ(moved.length(), orig_length_); EXPECT_EQ(nullptr, slice_.data()); EXPECT_EQ(0u, slice_.length()); EXPECT_TRUE(slice_.empty()); } TEST_F(QuicheMemSliceTest, MoveAssignNonEmpty) { const absl::string_view data("foo"); auto buffer = std::make_unique<char[]>(data.length()); std::memcpy(buffer.get(), data.data(), data.length()); QuicheMemSlice moved(std::move(buffer), data.length()); EXPECT_EQ(data, moved.AsStringView()); moved = std::move(slice_); EXPECT_EQ(moved.data(), orig_data_); EXPECT_EQ(moved.length(), orig_length_); EXPECT_EQ(nullptr, slice_.data()); EXPECT_EQ(0u, slice_.length()); EXPECT_TRUE(slice_.empty()); } TEST_F(QuicheMemSliceTest, SliceCustomDoneCallback) { const absl::string_view data("foo"); bool deleted = false; char* buffer = new char[data.length()]; std::memcpy(buffer, data.data(), data.length()); { QuicheMemSlice slice(buffer, data.length(), [&deleted](const char* data) { deleted = true; delete[] data; }); EXPECT_EQ(data, slice.AsStringView()); } EXPECT_TRUE(deleted); } TEST_F(QuicheMemSliceTest, Reset) { EXPECT_EQ(slice_.data(), orig_data_); EXPECT_EQ(slice_.length(), orig_length_); EXPECT_FALSE(slice_.empty()); slice_.Reset(); EXPECT_EQ(slice_.length(), 0u); EXPECT_TRUE(slice_.empty()); } TEST_F(QuicheMemSliceTest, SliceAllocatedOnHeap) { auto buffer = std::make_unique<char[]>(128); char* orig_data = buffer.get(); size_t used_length = 105; QuicheMemSlice slice = QuicheMemSlice(std::move(buffer), used_length); QuicheMemSlice moved = std::move(slice); EXPECT_EQ(moved.data(), orig_data); EXPECT_EQ(moved.length(), used_length); } TEST_F(QuicheMemSliceTest, SliceFromBuffer) { const absl::string_view kTestString = "RFC 9000 Release Celebration Memorial Test String"; auto buffer = QuicheBuffer::Copy(&allocator_, kTestString); QuicheMemSlice slice(std::move(buffer)); EXPECT_EQ(buffer.data(), nullptr); EXPECT_EQ(buffer.size(), 0u); EXPECT_EQ(slice.AsStringView(), kTestString); EXPECT_EQ(slice.length(), kTestString.length()); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/platform/api/quiche_mem_slice.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/platform/api/quiche_mem_slice_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
bb1a565c-5ae5-49b5-809b-1b2af956689f
cpp
google/quiche
quiche_reference_counted
quiche/common/platform/api/quiche_reference_counted.h
quiche/common/platform/api/quiche_reference_counted_test.cc
#ifndef QUICHE_COMMON_PLATFORM_API_QUICHE_REFERENCE_COUNTED_H_ #define QUICHE_COMMON_PLATFORM_API_QUICHE_REFERENCE_COUNTED_H_ #include "quiche_platform_impl/quiche_reference_counted_impl.h" #include "quiche/common/platform/api/quiche_export.h" namespace quiche { class QUICHE_EXPORT QuicheReferenceCounted : public QuicheReferenceCountedImpl { public: QuicheReferenceCounted() {} protected: ~QuicheReferenceCounted() override {} }; template <class T> class QUICHE_NO_EXPORT QuicheReferenceCountedPointer { public: QuicheReferenceCountedPointer() = default; explicit QuicheReferenceCountedPointer(T* p) : impl_(p) {} QuicheReferenceCountedPointer(std::nullptr_t) : impl_(nullptr) {} template <typename U> QuicheReferenceCountedPointer( const QuicheReferenceCountedPointer<U>& other) : impl_(other.impl()) {} QuicheReferenceCountedPointer(const QuicheReferenceCountedPointer& other) : impl_(other.impl()) {} template <typename U> QuicheReferenceCountedPointer( QuicheReferenceCountedPointer<U>&& other) : impl_(std::move(other.impl())) {} QuicheReferenceCountedPointer(QuicheReferenceCountedPointer&& other) : impl_(std::move(other.impl())) {} ~QuicheReferenceCountedPointer() = default; QuicheReferenceCountedPointer& operator=( const QuicheReferenceCountedPointer& other) { impl_ = other.impl(); return *this; } template <typename U> QuicheReferenceCountedPointer<T>& operator=( const QuicheReferenceCountedPointer<U>& other) { impl_ = other.impl(); return *this; } QuicheReferenceCountedPointer& operator=( QuicheReferenceCountedPointer&& other) { impl_ = std::move(other.impl()); return *this; } template <typename U> QuicheReferenceCountedPointer<T>& operator=( QuicheReferenceCountedPointer<U>&& other) { impl_ = std::move(other.impl()); return *this; } T& operator*() const { return *impl_; } T* operator->() const { return impl_.get(); } explicit operator bool() const { return static_cast<bool>(impl_); } QuicheReferenceCountedPointer<T>& operator=(T* p) { impl_ = p; return *this; } T* get() const { return impl_.get(); } QuicheReferenceCountedPointerImpl<T>& impl() { return impl_; } const QuicheReferenceCountedPointerImpl<T>& impl() const { return impl_; } friend bool operator==(const QuicheReferenceCountedPointer& a, const QuicheReferenceCountedPointer& b) { return a.get() == b.get(); } friend bool operator!=(const QuicheReferenceCountedPointer& a, const QuicheReferenceCountedPointer& b) { return a.get() != b.get(); } friend bool operator==(const QuicheReferenceCountedPointer& a, std::nullptr_t) { return a.get() == nullptr; } friend bool operator==(std::nullptr_t, const QuicheReferenceCountedPointer& b) { return nullptr == b.get(); } friend bool operator!=(const QuicheReferenceCountedPointer& a, std::nullptr_t) { return a.get() != nullptr; } friend bool operator!=(std::nullptr_t, const QuicheReferenceCountedPointer& b) { return nullptr != b.get(); } private: QuicheReferenceCountedPointerImpl<T> impl_; }; } #endif
#include "quiche/common/platform/api/quiche_reference_counted.h" #include <utility> #include "quiche/common/platform/api/quiche_test.h" namespace quiche { namespace test { namespace { class Base : public QuicheReferenceCounted { public: explicit Base(bool* destroyed) : destroyed_(destroyed) { *destroyed_ = false; } protected: ~Base() override { *destroyed_ = true; } private: bool* destroyed_; }; class Derived : public Base { public: explicit Derived(bool* destroyed) : Base(destroyed) {} private: ~Derived() override {} }; class QuicheReferenceCountedTest : public QuicheTest {}; TEST_F(QuicheReferenceCountedTest, DefaultConstructor) { QuicheReferenceCountedPointer<Base> a; EXPECT_EQ(nullptr, a); EXPECT_EQ(nullptr, a.get()); EXPECT_FALSE(a); } TEST_F(QuicheReferenceCountedTest, ConstructFromRawPointer) { bool destroyed = false; { QuicheReferenceCountedPointer<Base> a(new Base(&destroyed)); EXPECT_FALSE(destroyed); } EXPECT_TRUE(destroyed); } TEST_F(QuicheReferenceCountedTest, RawPointerAssignment) { bool destroyed = false; { QuicheReferenceCountedPointer<Base> a; Base* rct = new Base(&destroyed); a = rct; EXPECT_FALSE(destroyed); } EXPECT_TRUE(destroyed); } TEST_F(QuicheReferenceCountedTest, PointerCopy) { bool destroyed = false; { QuicheReferenceCountedPointer<Base> a(new Base(&destroyed)); { QuicheReferenceCountedPointer<Base> b(a); EXPECT_EQ(a, b); EXPECT_FALSE(destroyed); } EXPECT_FALSE(destroyed); } EXPECT_TRUE(destroyed); } TEST_F(QuicheReferenceCountedTest, PointerCopyAssignment) { bool destroyed = false; { QuicheReferenceCountedPointer<Base> a(new Base(&destroyed)); { QuicheReferenceCountedPointer<Base> b = a; EXPECT_EQ(a, b); EXPECT_FALSE(destroyed); } EXPECT_FALSE(destroyed); } EXPECT_TRUE(destroyed); } TEST_F(QuicheReferenceCountedTest, PointerCopyFromOtherType) { bool destroyed = false; { QuicheReferenceCountedPointer<Derived> a(new Derived(&destroyed)); { QuicheReferenceCountedPointer<Base> b(a); EXPECT_EQ(a.get(), b.get()); EXPECT_FALSE(destroyed); } EXPECT_FALSE(destroyed); } EXPECT_TRUE(destroyed); } TEST_F(QuicheReferenceCountedTest, PointerCopyAssignmentFromOtherType) { bool destroyed = false; { QuicheReferenceCountedPointer<Derived> a(new Derived(&destroyed)); { QuicheReferenceCountedPointer<Base> b = a; EXPECT_EQ(a.get(), b.get()); EXPECT_FALSE(destroyed); } EXPECT_FALSE(destroyed); } EXPECT_TRUE(destroyed); } TEST_F(QuicheReferenceCountedTest, PointerMove) { bool destroyed = false; QuicheReferenceCountedPointer<Base> a(new Derived(&destroyed)); EXPECT_FALSE(destroyed); QuicheReferenceCountedPointer<Base> b(std::move(a)); EXPECT_FALSE(destroyed); EXPECT_NE(nullptr, b); EXPECT_EQ(nullptr, a); b = nullptr; EXPECT_TRUE(destroyed); } TEST_F(QuicheReferenceCountedTest, PointerMoveAssignment) { bool destroyed = false; QuicheReferenceCountedPointer<Base> a(new Derived(&destroyed)); EXPECT_FALSE(destroyed); QuicheReferenceCountedPointer<Base> b = std::move(a); EXPECT_FALSE(destroyed); EXPECT_NE(nullptr, b); EXPECT_EQ(nullptr, a); b = nullptr; EXPECT_TRUE(destroyed); } TEST_F(QuicheReferenceCountedTest, PointerMoveFromOtherType) { bool destroyed = false; QuicheReferenceCountedPointer<Derived> a(new Derived(&destroyed)); EXPECT_FALSE(destroyed); QuicheReferenceCountedPointer<Base> b(std::move(a)); EXPECT_FALSE(destroyed); EXPECT_NE(nullptr, b); EXPECT_EQ(nullptr, a); b = nullptr; EXPECT_TRUE(destroyed); } TEST_F(QuicheReferenceCountedTest, PointerMoveAssignmentFromOtherType) { bool destroyed = false; QuicheReferenceCountedPointer<Derived> a(new Derived(&destroyed)); EXPECT_FALSE(destroyed); QuicheReferenceCountedPointer<Base> b = std::move(a); EXPECT_FALSE(destroyed); EXPECT_NE(nullptr, b); EXPECT_EQ(nullptr, a); b = nullptr; EXPECT_TRUE(destroyed); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/platform/api/quiche_reference_counted.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/platform/api/quiche_reference_counted_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
732627c3-ac7c-45b8-b76f-447446958de6
cpp
google/quiche
load_balancer_server_id_map
quiche/quic/load_balancer/load_balancer_server_id_map.h
quiche/quic/load_balancer/load_balancer_server_id_map_test.cc
#ifndef QUICHE_QUIC_LOAD_BALANCER_LOAD_BALANCER_SERVER_ID_MAP_H_ #define QUICHE_QUIC_LOAD_BALANCER_LOAD_BALANCER_SERVER_ID_MAP_H_ #include <cstdint> #include <memory> #include <optional> #include "absl/container/flat_hash_map.h" #include "quiche/quic/load_balancer/load_balancer_server_id.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" namespace quic { template <typename T> class QUIC_EXPORT_PRIVATE LoadBalancerServerIdMap { public: static std::shared_ptr<LoadBalancerServerIdMap> Create(uint8_t server_id_len); std::optional<const T> Lookup(LoadBalancerServerId server_id) const; const T* LookupNoCopy(LoadBalancerServerId server_id) const; void AddOrReplace(LoadBalancerServerId server_id, T value); void Erase(const LoadBalancerServerId server_id) { server_id_table_.erase(server_id); } uint8_t server_id_len() const { return server_id_len_; } private: LoadBalancerServerIdMap(uint8_t server_id_len) : server_id_len_(server_id_len) {} const uint8_t server_id_len_; absl::flat_hash_map<LoadBalancerServerId, T> server_id_table_; }; template <typename T> std::shared_ptr<LoadBalancerServerIdMap<T>> LoadBalancerServerIdMap<T>::Create( const uint8_t server_id_len) { if (server_id_len == 0 || server_id_len > kLoadBalancerMaxServerIdLen) { QUIC_BUG(quic_bug_434893339_01) << "Tried to configure map with server ID length " << static_cast<int>(server_id_len); return nullptr; } return std::make_shared<LoadBalancerServerIdMap<T>>( LoadBalancerServerIdMap(server_id_len)); } template <typename T> std::optional<const T> LoadBalancerServerIdMap<T>::Lookup( const LoadBalancerServerId server_id) const { if (server_id.length() != server_id_len_) { QUIC_BUG(quic_bug_434893339_02) << "Lookup with a " << static_cast<int>(server_id.length()) << " byte server ID, map requires " << static_cast<int>(server_id_len_); return std::optional<T>(); } auto it = server_id_table_.find(server_id); return (it != server_id_table_.end()) ? it->second : std::optional<const T>(); } template <typename T> const T* LoadBalancerServerIdMap<T>::LookupNoCopy( const LoadBalancerServerId server_id) const { if (server_id.length() != server_id_len_) { QUIC_BUG(quic_bug_434893339_02) << "Lookup with a " << static_cast<int>(server_id.length()) << " byte server ID, map requires " << static_cast<int>(server_id_len_); return nullptr; } auto it = server_id_table_.find(server_id); return (it != server_id_table_.end()) ? &it->second : nullptr; } template <typename T> void LoadBalancerServerIdMap<T>::AddOrReplace( const LoadBalancerServerId server_id, T value) { if (server_id.length() == server_id_len_) { server_id_table_[server_id] = value; } else { QUIC_BUG(quic_bug_434893339_03) << "Server ID of " << static_cast<int>(server_id.length()) << " bytes; this map requires " << static_cast<int>(server_id_len_); } } } #endif
#include "quiche/quic/load_balancer/load_balancer_server_id_map.h" #include <cstdint> #include <optional> #include "absl/types/span.h" #include "quiche/quic/load_balancer/load_balancer_server_id.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { namespace { constexpr uint8_t kServerId[] = {0xed, 0x79, 0x3a, 0x51}; class LoadBalancerServerIdMapTest : public QuicTest { public: const LoadBalancerServerId valid_server_id_ = LoadBalancerServerId(kServerId); const LoadBalancerServerId invalid_server_id_ = LoadBalancerServerId(absl::Span<const uint8_t>(kServerId, 3)); }; TEST_F(LoadBalancerServerIdMapTest, CreateWithBadServerIdLength) { EXPECT_QUIC_BUG(EXPECT_EQ(LoadBalancerServerIdMap<int>::Create(0), nullptr), "Tried to configure map with server ID length 0"); EXPECT_QUIC_BUG(EXPECT_EQ(LoadBalancerServerIdMap<int>::Create(16), nullptr), "Tried to configure map with server ID length 16"); } TEST_F(LoadBalancerServerIdMapTest, AddOrReplaceWithBadServerIdLength) { int record = 1; auto pool = LoadBalancerServerIdMap<int>::Create(4); EXPECT_NE(pool, nullptr); EXPECT_QUIC_BUG(pool->AddOrReplace(invalid_server_id_, record), "Server ID of 3 bytes; this map requires 4"); } TEST_F(LoadBalancerServerIdMapTest, LookupWithBadServerIdLength) { int record = 1; auto pool = LoadBalancerServerIdMap<int>::Create(4); EXPECT_NE(pool, nullptr); pool->AddOrReplace(valid_server_id_, record); EXPECT_QUIC_BUG(EXPECT_FALSE(pool->Lookup(invalid_server_id_).has_value()), "Lookup with a 3 byte server ID, map requires 4"); EXPECT_QUIC_BUG(EXPECT_EQ(pool->LookupNoCopy(invalid_server_id_), nullptr), "Lookup with a 3 byte server ID, map requires 4"); } TEST_F(LoadBalancerServerIdMapTest, LookupWhenEmpty) { auto pool = LoadBalancerServerIdMap<int>::Create(4); EXPECT_NE(pool, nullptr); EXPECT_EQ(pool->LookupNoCopy(valid_server_id_), nullptr); std::optional<int> result = pool->Lookup(valid_server_id_); EXPECT_FALSE(result.has_value()); } TEST_F(LoadBalancerServerIdMapTest, AddLookup) { int record1 = 1, record2 = 2; auto pool = LoadBalancerServerIdMap<int>::Create(4); EXPECT_NE(pool, nullptr); LoadBalancerServerId other_server_id({0x01, 0x02, 0x03, 0x04}); EXPECT_TRUE(other_server_id.IsValid()); pool->AddOrReplace(valid_server_id_, record1); pool->AddOrReplace(other_server_id, record2); std::optional<int> result = pool->Lookup(valid_server_id_); EXPECT_TRUE(result.has_value()); EXPECT_EQ(*result, record1); auto result_ptr = pool->LookupNoCopy(valid_server_id_); EXPECT_NE(result_ptr, nullptr); EXPECT_EQ(*result_ptr, record1); result = pool->Lookup(other_server_id); EXPECT_TRUE(result.has_value()); EXPECT_EQ(*result, record2); } TEST_F(LoadBalancerServerIdMapTest, AddErase) { int record = 1; auto pool = LoadBalancerServerIdMap<int>::Create(4); EXPECT_NE(pool, nullptr); pool->AddOrReplace(valid_server_id_, record); EXPECT_EQ(*pool->LookupNoCopy(valid_server_id_), record); pool->Erase(valid_server_id_); EXPECT_EQ(pool->LookupNoCopy(valid_server_id_), nullptr); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/load_balancer/load_balancer_server_id_map.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/load_balancer/load_balancer_server_id_map_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
2ab755d8-89d5-4e68-8d5d-83ff2fadfc9a
cpp
google/quiche
quic_interval
quiche/quic/core/quic_interval.h
quiche/quic/core/quic_interval_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_INTERVAL_H_ #define QUICHE_QUIC_CORE_QUIC_INTERVAL_H_ #include <stddef.h> #include <algorithm> #include <ostream> #include <type_traits> #include <utility> #include <vector> #include "quiche/quic/platform/api/quic_export.h" namespace quic { template <typename T> class QUICHE_NO_EXPORT QuicInterval { private: template <typename U> class QUICHE_NO_EXPORT DiffTypeOrVoid { private: template <typename V> static auto f(const V* v) -> decltype(*v - *v); template <typename V> static void f(...); public: using type = typename std::decay<decltype(f<U>(nullptr))>::type; }; public: QuicInterval() : min_(), max_() {} QuicInterval(const T& min, const T& max) : min_(min), max_(max) {} template <typename U1, typename U2, typename = typename std::enable_if< std::is_convertible<U1, T>::value && std::is_convertible<U2, T>::value>::type> QuicInterval(U1&& min, U2&& max) : min_(std::forward<U1>(min)), max_(std::forward<U2>(max)) {} const T& min() const { return min_; } const T& max() const { return max_; } void SetMin(const T& t) { min_ = t; } void SetMax(const T& t) { max_ = t; } void Set(const T& min, const T& max) { SetMin(min); SetMax(max); } void Clear() { *this = {}; } bool Empty() const { return min() >= max(); } typename DiffTypeOrVoid<T>::type Length() const { return (Empty() ? min() : max()) - min(); } bool Contains(const T& t) const { return min() <= t && max() > t; } bool Contains(const QuicInterval& i) const { return !Empty() && !i.Empty() && min() <= i.min() && max() >= i.max(); } bool Intersects(const QuicInterval& i) const { return !Empty() && !i.Empty() && min() < i.max() && max() > i.min(); } bool Intersects(const QuicInterval& i, QuicInterval* out) const; bool IntersectWith(const QuicInterval& i); bool Separated(const QuicInterval& other) const { if (Empty() || other.Empty()) return true; return other.max() < min() || max() < other.min(); } bool SpanningUnion(const QuicInterval& i); bool Difference(const QuicInterval& i, std::vector<QuicInterval*>* difference) const; bool Difference(const QuicInterval& i, QuicInterval* lo, QuicInterval* hi) const; friend bool operator==(const QuicInterval& a, const QuicInterval& b) { bool ae = a.Empty(); bool be = b.Empty(); if (ae && be) return true; if (ae != be) return false; return a.min() == b.min() && a.max() == b.max(); } friend bool operator!=(const QuicInterval& a, const QuicInterval& b) { return !(a == b); } friend bool operator<(const QuicInterval& a, const QuicInterval& b) { return a.min() < b.min() || (!(b.min() < a.min()) && b.max() < a.max()); } private: T min_; T max_; }; template <typename T> QuicInterval<T> MakeQuicInterval(T&& lhs, T&& rhs) { return QuicInterval<T>(std::forward<T>(lhs), std::forward<T>(rhs)); } template <typename T> auto operator<<(std::ostream& out, const QuicInterval<T>& i) -> decltype(out << i.min()) { return out << "[" << i.min() << ", " << i.max() << ")"; } template <typename T> bool QuicInterval<T>::Intersects(const QuicInterval& i, QuicInterval* out) const { if (!Intersects(i)) return false; if (out != nullptr) { *out = QuicInterval(std::max(min(), i.min()), std::min(max(), i.max())); } return true; } template <typename T> bool QuicInterval<T>::IntersectWith(const QuicInterval& i) { if (Empty()) return false; bool modified = false; if (i.min() > min()) { SetMin(i.min()); modified = true; } if (i.max() < max()) { SetMax(i.max()); modified = true; } return modified; } template <typename T> bool QuicInterval<T>::SpanningUnion(const QuicInterval& i) { if (i.Empty()) return false; if (Empty()) { *this = i; return true; } bool modified = false; if (i.min() < min()) { SetMin(i.min()); modified = true; } if (i.max() > max()) { SetMax(i.max()); modified = true; } return modified; } template <typename T> bool QuicInterval<T>::Difference(const QuicInterval& i, std::vector<QuicInterval*>* difference) const { if (Empty()) { return false; } if (i.Empty()) { difference->push_back(new QuicInterval(*this)); return false; } if (min() < i.max() && min() >= i.min() && max() > i.max()) { difference->push_back(new QuicInterval(i.max(), max())); return true; } if (max() > i.min() && max() <= i.max() && min() < i.min()) { difference->push_back(new QuicInterval(min(), i.min())); return true; } if (min() < i.min() && max() > i.max()) { difference->push_back(new QuicInterval(min(), i.min())); difference->push_back(new QuicInterval(i.max(), max())); return true; } if (min() >= i.min() && max() <= i.max()) { return true; } difference->push_back(new QuicInterval(*this)); return false; } template <typename T> bool QuicInterval<T>::Difference(const QuicInterval& i, QuicInterval* lo, QuicInterval* hi) const { *lo = {}; *hi = {}; if (Empty()) return false; if (i.Empty()) { *lo = *this; return false; } if (min() < i.max() && min() >= i.min() && max() > i.max()) { *hi = QuicInterval(i.max(), max()); return true; } if (max() > i.min() && max() <= i.max() && min() < i.min()) { *lo = QuicInterval(min(), i.min()); return true; } if (min() < i.min() && max() > i.max()) { *lo = QuicInterval(min(), i.min()); *hi = QuicInterval(i.max(), max()); return true; } if (min() >= i.min() && max() <= i.max()) { return true; } *lo = *this; return false; } } #endif
#include "quiche/quic/core/quic_interval.h" #include <ostream> #include <sstream> #include <string> #include <type_traits> #include <utility> #include <vector> #include "quiche/quic/core/quic_time.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { namespace { template <typename ForwardIterator> void STLDeleteContainerPointers(ForwardIterator begin, ForwardIterator end) { while (begin != end) { auto temp = begin; ++begin; delete *temp; } } template <typename T> void STLDeleteElements(T* container) { if (!container) return; STLDeleteContainerPointers(container->begin(), container->end()); container->clear(); } class ConstructorListener { public: ConstructorListener(int* copy_construct_counter, int* move_construct_counter) : copy_construct_counter_(copy_construct_counter), move_construct_counter_(move_construct_counter) { *copy_construct_counter_ = 0; *move_construct_counter_ = 0; } ConstructorListener(const ConstructorListener& other) { copy_construct_counter_ = other.copy_construct_counter_; move_construct_counter_ = other.move_construct_counter_; ++*copy_construct_counter_; } ConstructorListener(ConstructorListener&& other) { copy_construct_counter_ = other.copy_construct_counter_; move_construct_counter_ = other.move_construct_counter_; ++*move_construct_counter_; } bool operator<(const ConstructorListener&) { return false; } bool operator>(const ConstructorListener&) { return false; } bool operator<=(const ConstructorListener&) { return true; } bool operator>=(const ConstructorListener&) { return true; } bool operator==(const ConstructorListener&) { return true; } private: int* copy_construct_counter_; int* move_construct_counter_; }; TEST(QuicIntervalConstructorTest, Move) { int object1_copy_count, object1_move_count; ConstructorListener object1(&object1_copy_count, &object1_move_count); int object2_copy_count, object2_move_count; ConstructorListener object2(&object2_copy_count, &object2_move_count); QuicInterval<ConstructorListener> interval(object1, std::move(object2)); EXPECT_EQ(1, object1_copy_count); EXPECT_EQ(0, object1_move_count); EXPECT_EQ(0, object2_copy_count); EXPECT_EQ(1, object2_move_count); } TEST(QuicIntervalConstructorTest, ImplicitConversion) { struct WrappedInt { WrappedInt(int value) : value(value) {} bool operator<(const WrappedInt& other) { return value < other.value; } bool operator>(const WrappedInt& other) { return value > other.value; } bool operator<=(const WrappedInt& other) { return value <= other.value; } bool operator>=(const WrappedInt& other) { return value >= other.value; } bool operator==(const WrappedInt& other) { return value == other.value; } int value; }; static_assert(std::is_convertible<int, WrappedInt>::value, ""); static_assert( std::is_constructible<QuicInterval<WrappedInt>, int, int>::value, ""); QuicInterval<WrappedInt> i(10, 20); EXPECT_EQ(10, i.min().value); EXPECT_EQ(20, i.max().value); } class QuicIntervalTest : public QuicTest { protected: void TestIntersect(const QuicInterval<int64_t>& i1, const QuicInterval<int64_t>& i2, bool changes_i1, bool changes_i2, const QuicInterval<int64_t>& result) { QuicInterval<int64_t> i; i = i1; EXPECT_TRUE(i.IntersectWith(i2) == changes_i1 && i == result); i = i2; EXPECT_TRUE(i.IntersectWith(i1) == changes_i2 && i == result); } }; TEST_F(QuicIntervalTest, ConstructorsCopyAndClear) { QuicInterval<int32_t> empty; EXPECT_TRUE(empty.Empty()); QuicInterval<int32_t> d2(0, 100); EXPECT_EQ(0, d2.min()); EXPECT_EQ(100, d2.max()); EXPECT_EQ(QuicInterval<int32_t>(0, 100), d2); EXPECT_NE(QuicInterval<int32_t>(0, 99), d2); empty = d2; EXPECT_EQ(0, d2.min()); EXPECT_EQ(100, d2.max()); EXPECT_TRUE(empty == d2); EXPECT_EQ(empty, d2); EXPECT_TRUE(d2 == empty); EXPECT_EQ(d2, empty); QuicInterval<int32_t> max_less_than_min(40, 20); EXPECT_TRUE(max_less_than_min.Empty()); EXPECT_EQ(40, max_less_than_min.min()); EXPECT_EQ(20, max_less_than_min.max()); QuicInterval<int> d3(10, 20); d3.Clear(); EXPECT_TRUE(d3.Empty()); } TEST_F(QuicIntervalTest, MakeQuicInterval) { static_assert( std::is_same<QuicInterval<int>, decltype(MakeQuicInterval(0, 3))>::value, "Type is deduced incorrectly."); static_assert(std::is_same<QuicInterval<double>, decltype(MakeQuicInterval(0., 3.))>::value, "Type is deduced incorrectly."); EXPECT_EQ(MakeQuicInterval(0., 3.), QuicInterval<double>(0, 3)); } TEST_F(QuicIntervalTest, GettersSetters) { QuicInterval<int32_t> d1(100, 200); d1.SetMin(30); EXPECT_EQ(30, d1.min()); EXPECT_EQ(200, d1.max()); d1.SetMax(220); EXPECT_EQ(30, d1.min()); EXPECT_EQ(220, d1.max()); d1.Clear(); d1.Set(30, 220); EXPECT_EQ(30, d1.min()); EXPECT_EQ(220, d1.max()); QuicInterval<int32_t> d2; EXPECT_TRUE(!d1.SpanningUnion(d2)); EXPECT_EQ(30, d1.min()); EXPECT_EQ(220, d1.max()); EXPECT_TRUE(d2.SpanningUnion(d1)); EXPECT_EQ(30, d2.min()); EXPECT_EQ(220, d2.max()); d2.SetMin(40); d2.SetMax(100); EXPECT_TRUE(!d1.SpanningUnion(d2)); EXPECT_EQ(30, d1.min()); EXPECT_EQ(220, d1.max()); d2.SetMin(20); d2.SetMax(100); EXPECT_TRUE(d1.SpanningUnion(d2)); EXPECT_EQ(20, d1.min()); EXPECT_EQ(220, d1.max()); d2.SetMin(50); d2.SetMax(300); EXPECT_TRUE(d1.SpanningUnion(d2)); EXPECT_EQ(20, d1.min()); EXPECT_EQ(300, d1.max()); d2.SetMin(0); d2.SetMax(500); EXPECT_TRUE(d1.SpanningUnion(d2)); EXPECT_EQ(0, d1.min()); EXPECT_EQ(500, d1.max()); d2.SetMin(100); d2.SetMax(0); EXPECT_TRUE(!d1.SpanningUnion(d2)); EXPECT_EQ(0, d1.min()); EXPECT_EQ(500, d1.max()); EXPECT_TRUE(d2.SpanningUnion(d1)); EXPECT_EQ(0, d2.min()); EXPECT_EQ(500, d2.max()); } TEST_F(QuicIntervalTest, CoveringOps) { const QuicInterval<int64_t> empty; const QuicInterval<int64_t> d(100, 200); const QuicInterval<int64_t> d1(0, 50); const QuicInterval<int64_t> d2(50, 110); const QuicInterval<int64_t> d3(110, 180); const QuicInterval<int64_t> d4(180, 220); const QuicInterval<int64_t> d5(220, 300); const QuicInterval<int64_t> d6(100, 150); const QuicInterval<int64_t> d7(150, 200); const QuicInterval<int64_t> d8(0, 300); EXPECT_TRUE(d.Intersects(d)); EXPECT_TRUE(!empty.Intersects(d) && !d.Intersects(empty)); EXPECT_TRUE(!d.Intersects(d1) && !d1.Intersects(d)); EXPECT_TRUE(d.Intersects(d2) && d2.Intersects(d)); EXPECT_TRUE(d.Intersects(d3) && d3.Intersects(d)); EXPECT_TRUE(d.Intersects(d4) && d4.Intersects(d)); EXPECT_TRUE(!d.Intersects(d5) && !d5.Intersects(d)); EXPECT_TRUE(d.Intersects(d6) && d6.Intersects(d)); EXPECT_TRUE(d.Intersects(d7) && d7.Intersects(d)); EXPECT_TRUE(d.Intersects(d8) && d8.Intersects(d)); QuicInterval<int64_t> i; EXPECT_TRUE(d.Intersects(d, &i) && d == i); EXPECT_TRUE(!empty.Intersects(d, nullptr) && !d.Intersects(empty, nullptr)); EXPECT_TRUE(!d.Intersects(d1, nullptr) && !d1.Intersects(d, nullptr)); EXPECT_TRUE(d.Intersects(d2, &i) && i == QuicInterval<int64_t>(100, 110)); EXPECT_TRUE(d2.Intersects(d, &i) && i == QuicInterval<int64_t>(100, 110)); EXPECT_TRUE(d.Intersects(d3, &i) && i == d3); EXPECT_TRUE(d3.Intersects(d, &i) && i == d3); EXPECT_TRUE(d.Intersects(d4, &i) && i == QuicInterval<int64_t>(180, 200)); EXPECT_TRUE(d4.Intersects(d, &i) && i == QuicInterval<int64_t>(180, 200)); EXPECT_TRUE(!d.Intersects(d5, nullptr) && !d5.Intersects(d, nullptr)); EXPECT_TRUE(d.Intersects(d6, &i) && i == d6); EXPECT_TRUE(d6.Intersects(d, &i) && i == d6); EXPECT_TRUE(d.Intersects(d7, &i) && i == d7); EXPECT_TRUE(d7.Intersects(d, &i) && i == d7); EXPECT_TRUE(d.Intersects(d8, &i) && i == d); EXPECT_TRUE(d8.Intersects(d, &i) && i == d); TestIntersect(empty, d, false, true, empty); TestIntersect(d, d1, true, true, empty); TestIntersect(d1, d2, true, true, empty); TestIntersect(d, d2, true, true, QuicInterval<int64_t>(100, 110)); TestIntersect(d8, d, true, false, d); TestIntersect(d8, d1, true, false, d1); TestIntersect(d8, d5, true, false, d5); EXPECT_TRUE(!empty.Contains(d) && !d.Contains(empty)); EXPECT_TRUE(d.Contains(d)); EXPECT_TRUE(!d.Contains(d1) && !d1.Contains(d)); EXPECT_TRUE(!d.Contains(d2) && !d2.Contains(d)); EXPECT_TRUE(d.Contains(d3) && !d3.Contains(d)); EXPECT_TRUE(!d.Contains(d4) && !d4.Contains(d)); EXPECT_TRUE(!d.Contains(d5) && !d5.Contains(d)); EXPECT_TRUE(d.Contains(d6) && !d6.Contains(d)); EXPECT_TRUE(d.Contains(d7) && !d7.Contains(d)); EXPECT_TRUE(!d.Contains(d8) && d8.Contains(d)); EXPECT_TRUE(d.Contains(100)); EXPECT_TRUE(!d.Contains(200)); EXPECT_TRUE(d.Contains(150)); EXPECT_TRUE(!d.Contains(99)); EXPECT_TRUE(!d.Contains(201)); std::vector<QuicInterval<int64_t>*> diff; EXPECT_TRUE(!d.Difference(empty, &diff)); EXPECT_EQ(1u, diff.size()); EXPECT_EQ(100, diff[0]->min()); EXPECT_EQ(200, diff[0]->max()); STLDeleteElements(&diff); EXPECT_TRUE(!empty.Difference(d, &diff) && diff.empty()); EXPECT_TRUE(d.Difference(d, &diff) && diff.empty()); EXPECT_TRUE(!d.Difference(d1, &diff)); EXPECT_EQ(1u, diff.size()); EXPECT_EQ(100, diff[0]->min()); EXPECT_EQ(200, diff[0]->max()); STLDeleteElements(&diff); QuicInterval<int64_t> lo; QuicInterval<int64_t> hi; EXPECT_TRUE(d.Difference(d2, &lo, &hi)); EXPECT_TRUE(lo.Empty()); EXPECT_EQ(110, hi.min()); EXPECT_EQ(200, hi.max()); EXPECT_TRUE(d.Difference(d2, &diff)); EXPECT_EQ(1u, diff.size()); EXPECT_EQ(110, diff[0]->min()); EXPECT_EQ(200, diff[0]->max()); STLDeleteElements(&diff); EXPECT_TRUE(d.Difference(d3, &lo, &hi)); EXPECT_EQ(100, lo.min()); EXPECT_EQ(110, lo.max()); EXPECT_EQ(180, hi.min()); EXPECT_EQ(200, hi.max()); EXPECT_TRUE(d.Difference(d3, &diff)); EXPECT_EQ(2u, diff.size()); EXPECT_EQ(100, diff[0]->min()); EXPECT_EQ(110, diff[0]->max()); EXPECT_EQ(180, diff[1]->min()); EXPECT_EQ(200, diff[1]->max()); STLDeleteElements(&diff); EXPECT_TRUE(d.Difference(d4, &lo, &hi)); EXPECT_EQ(100, lo.min()); EXPECT_EQ(180, lo.max()); EXPECT_TRUE(hi.Empty()); EXPECT_TRUE(d.Difference(d4, &diff)); EXPECT_EQ(1u, diff.size()); EXPECT_EQ(100, diff[0]->min()); EXPECT_EQ(180, diff[0]->max()); STLDeleteElements(&diff); EXPECT_FALSE(d.Difference(d5, &lo, &hi)); EXPECT_EQ(100, lo.min()); EXPECT_EQ(200, lo.max()); EXPECT_TRUE(hi.Empty()); EXPECT_FALSE(d.Difference(d5, &diff)); EXPECT_EQ(1u, diff.size()); EXPECT_EQ(100, diff[0]->min()); EXPECT_EQ(200, diff[0]->max()); STLDeleteElements(&diff); EXPECT_TRUE(d.Difference(d6, &lo, &hi)); EXPECT_TRUE(lo.Empty()); EXPECT_EQ(150, hi.min()); EXPECT_EQ(200, hi.max()); EXPECT_TRUE(d.Difference(d6, &diff)); EXPECT_EQ(1u, diff.size()); EXPECT_EQ(150, diff[0]->min()); EXPECT_EQ(200, diff[0]->max()); STLDeleteElements(&diff); EXPECT_TRUE(d.Difference(d7, &lo, &hi)); EXPECT_EQ(100, lo.min()); EXPECT_EQ(150, lo.max()); EXPECT_TRUE(hi.Empty()); EXPECT_TRUE(d.Difference(d7, &diff)); EXPECT_EQ(1u, diff.size()); EXPECT_EQ(100, diff[0]->min()); EXPECT_EQ(150, diff[0]->max()); STLDeleteElements(&diff); EXPECT_TRUE(d.Difference(d8, &lo, &hi)); EXPECT_TRUE(lo.Empty()); EXPECT_TRUE(hi.Empty()); EXPECT_TRUE(d.Difference(d8, &diff) && diff.empty()); } TEST_F(QuicIntervalTest, Separated) { using QI = QuicInterval<int>; EXPECT_FALSE(QI(100, 200).Separated(QI(100, 200))); EXPECT_FALSE(QI(100, 200).Separated(QI(200, 300))); EXPECT_TRUE(QI(100, 200).Separated(QI(201, 300))); EXPECT_FALSE(QI(100, 200).Separated(QI(0, 100))); EXPECT_TRUE(QI(100, 200).Separated(QI(0, 99))); EXPECT_FALSE(QI(100, 200).Separated(QI(150, 170))); EXPECT_FALSE(QI(150, 170).Separated(QI(100, 200))); EXPECT_FALSE(QI(100, 200).Separated(QI(150, 250))); EXPECT_FALSE(QI(150, 250).Separated(QI(100, 200))); } TEST_F(QuicIntervalTest, Length) { const QuicInterval<int> empty1; const QuicInterval<int> empty2(1, 1); const QuicInterval<int> empty3(1, 0); const QuicInterval<QuicTime> empty4( QuicTime::Zero() + QuicTime::Delta::FromSeconds(1), QuicTime::Zero()); const QuicInterval<int> d1(1, 2); const QuicInterval<int> d2(0, 50); const QuicInterval<QuicTime> d3( QuicTime::Zero(), QuicTime::Zero() + QuicTime::Delta::FromSeconds(1)); const QuicInterval<QuicTime> d4( QuicTime::Zero() + QuicTime::Delta::FromSeconds(3600), QuicTime::Zero() + QuicTime::Delta::FromSeconds(5400)); EXPECT_EQ(0, empty1.Length()); EXPECT_EQ(0, empty2.Length()); EXPECT_EQ(0, empty3.Length()); EXPECT_EQ(QuicTime::Delta::Zero(), empty4.Length()); EXPECT_EQ(1, d1.Length()); EXPECT_EQ(50, d2.Length()); EXPECT_EQ(QuicTime::Delta::FromSeconds(1), d3.Length()); EXPECT_EQ(QuicTime::Delta::FromSeconds(1800), d4.Length()); } TEST_F(QuicIntervalTest, IntervalOfTypeWithNoOperatorMinus) { const QuicInterval<std::string> d1("a", "b"); const QuicInterval<std::pair<int, int>> d2({1, 2}, {4, 3}); EXPECT_EQ("a", d1.min()); EXPECT_EQ("b", d1.max()); EXPECT_EQ(std::make_pair(1, 2), d2.min()); EXPECT_EQ(std::make_pair(4, 3), d2.max()); } struct NoEquals { NoEquals(int v) : value(v) {} int value; bool operator<(const NoEquals& other) const { return value < other.value; } }; TEST_F(QuicIntervalTest, OrderedComparisonForTypeWithoutEquals) { const QuicInterval<NoEquals> d1(0, 4); const QuicInterval<NoEquals> d2(0, 3); const QuicInterval<NoEquals> d3(1, 4); const QuicInterval<NoEquals> d4(1, 5); const QuicInterval<NoEquals> d6(0, 4); EXPECT_TRUE(d1 < d2); EXPECT_TRUE(d1 < d3); EXPECT_TRUE(d1 < d4); EXPECT_FALSE(d1 < d6); } TEST_F(QuicIntervalTest, OutputReturnsOstreamRef) { std::stringstream ss; const QuicInterval<int> v(1, 2); auto return_type_is_a_ref = [](std::ostream&) {}; return_type_is_a_ref(ss << v); } struct NotOstreamable { bool operator<(const NotOstreamable&) const { return false; } bool operator>=(const NotOstreamable&) const { return true; } bool operator==(const NotOstreamable&) const { return true; } }; TEST_F(QuicIntervalTest, IntervalOfTypeWithNoOstreamSupport) { const NotOstreamable v; const QuicInterval<NotOstreamable> d(v, v); EXPECT_EQ(d, d); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_interval.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_interval_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
9850da70-eed9-4092-9462-9cdcc5013f48
cpp
google/quiche
quic_time_accumulator
quiche/quic/core/quic_time_accumulator.h
quiche/quic/core/quic_time_accumulator_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_TIME_ACCUMULATOR_H_ #define QUICHE_QUIC_CORE_QUIC_TIME_ACCUMULATOR_H_ #include "quiche/quic/core/quic_time.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { class QUICHE_EXPORT QuicTimeAccumulator { static constexpr QuicTime NotRunningSentinel() { return QuicTime::Infinite(); } public: bool IsRunning() const { return last_start_time_ != NotRunningSentinel(); } void Start(QuicTime now) { QUICHE_DCHECK(!IsRunning()); last_start_time_ = now; QUICHE_DCHECK(IsRunning()); } void Stop(QuicTime now) { QUICHE_DCHECK(IsRunning()); if (now > last_start_time_) { total_elapsed_ = total_elapsed_ + (now - last_start_time_); } last_start_time_ = NotRunningSentinel(); QUICHE_DCHECK(!IsRunning()); } QuicTime::Delta GetTotalElapsedTime() const { return total_elapsed_; } QuicTime::Delta GetTotalElapsedTime(QuicTime now) const { if (!IsRunning()) { return total_elapsed_; } if (now <= last_start_time_) { return total_elapsed_; } return total_elapsed_ + (now - last_start_time_); } private: QuicTime::Delta total_elapsed_ = QuicTime::Delta::Zero(); QuicTime last_start_time_ = NotRunningSentinel(); }; } #endif
#include "quiche/quic/core/quic_time_accumulator.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_clock.h" namespace quic { namespace test { TEST(QuicTimeAccumulator, DefaultConstruct) { MockClock clock; clock.AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); QuicTimeAccumulator acc; EXPECT_FALSE(acc.IsRunning()); clock.AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); EXPECT_EQ(QuicTime::Delta::Zero(), acc.GetTotalElapsedTime()); EXPECT_EQ(QuicTime::Delta::Zero(), acc.GetTotalElapsedTime(clock.Now())); } TEST(QuicTimeAccumulator, StartStop) { MockClock clock; clock.AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); QuicTimeAccumulator acc; acc.Start(clock.Now()); EXPECT_TRUE(acc.IsRunning()); clock.AdvanceTime(QuicTime::Delta::FromMilliseconds(10)); acc.Stop(clock.Now()); EXPECT_FALSE(acc.IsRunning()); clock.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), acc.GetTotalElapsedTime()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), acc.GetTotalElapsedTime(clock.Now())); acc.Start(clock.Now()); clock.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), acc.GetTotalElapsedTime()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(15), acc.GetTotalElapsedTime(clock.Now())); clock.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), acc.GetTotalElapsedTime()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(20), acc.GetTotalElapsedTime(clock.Now())); acc.Stop(clock.Now()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(20), acc.GetTotalElapsedTime()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(20), acc.GetTotalElapsedTime(clock.Now())); } TEST(QuicTimeAccumulator, ClockStepBackwards) { MockClock clock; clock.AdvanceTime(QuicTime::Delta::FromMilliseconds(100)); QuicTimeAccumulator acc; acc.Start(clock.Now()); clock.AdvanceTime(QuicTime::Delta::FromMilliseconds(-10)); acc.Stop(clock.Now()); EXPECT_EQ(QuicTime::Delta::Zero(), acc.GetTotalElapsedTime()); EXPECT_EQ(QuicTime::Delta::Zero(), acc.GetTotalElapsedTime(clock.Now())); acc.Start(clock.Now()); clock.AdvanceTime(QuicTime::Delta::FromMilliseconds(50)); acc.Stop(clock.Now()); acc.Start(clock.Now()); clock.AdvanceTime(QuicTime::Delta::FromMilliseconds(-80)); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(50), acc.GetTotalElapsedTime()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(50), acc.GetTotalElapsedTime(clock.Now())); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_time_accumulator.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_time_accumulator_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
5c2ea959-8528-49ce-afb1-9865a7548db7
cpp
google/quiche
quic_interval_set
quiche/quic/core/quic_interval_set.h
quiche/quic/core/quic_interval_set_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_INTERVAL_SET_H_ #define QUICHE_QUIC_CORE_QUIC_INTERVAL_SET_H_ #include <stddef.h> #include <algorithm> #include <initializer_list> #include <set> #include <sstream> #include <string> #include <utility> #include <vector> #include "quiche/quic/core/quic_interval.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/common/platform/api/quiche_containers.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quic { template <typename T> class QUICHE_NO_EXPORT QuicIntervalSet { public: using value_type = QuicInterval<T>; private: struct QUICHE_NO_EXPORT IntervalLess { using is_transparent = void; bool operator()(const value_type& a, const value_type& b) const; bool operator()(const value_type& a, const T& point) const; bool operator()(const value_type& a, T&& point) const; bool operator()(const T& point, const value_type& a) const; bool operator()(T&& point, const value_type& a) const; }; using Set = quiche::QuicheSmallOrderedSet<value_type, IntervalLess>; public: using const_iterator = typename Set::const_iterator; using const_reverse_iterator = typename Set::const_reverse_iterator; QuicIntervalSet() = default; explicit QuicIntervalSet(const value_type& interval) { Add(interval); } QuicIntervalSet(const T& min, const T& max) { Add(min, max); } QuicIntervalSet(std::initializer_list<value_type> il) { assign(il); } void Clear() { intervals_.clear(); } size_t Size() const { return intervals_.size(); } value_type SpanningInterval() const; void Add(const value_type& interval); void Add(const T& min, const T& max) { Add(value_type(min, max)); } void AddOptimizedForAppend(const value_type& interval) { if (Empty() || !GetQuicFlag(quic_interval_set_enable_add_optimization)) { Add(interval); return; } const_reverse_iterator last_interval = intervals_.rbegin(); if (interval.min() < last_interval->min() || interval.min() > last_interval->max()) { Add(interval); return; } if (interval.max() <= last_interval->max()) { return; } const_cast<value_type*>(&(*last_interval))->SetMax(interval.max()); } void AddOptimizedForAppend(const T& min, const T& max) { AddOptimizedForAppend(value_type(min, max)); } void PopFront() { QUICHE_DCHECK(!Empty()); intervals_.erase(intervals_.begin()); } bool TrimLessThan(const T& value) { size_t num_intervals_trimmed = 0; while (!intervals_.empty()) { const_iterator first_interval = intervals_.begin(); if (first_interval->min() >= value) { break; } ++num_intervals_trimmed; if (first_interval->max() <= value) { intervals_.erase(first_interval); continue; } const_cast<value_type*>(&(*first_interval))->SetMin(value); break; } return num_intervals_trimmed != 0; } bool Empty() const { return intervals_.empty(); } bool Contains(const T& value) const; bool Contains(const value_type& interval) const; bool Contains(const QuicIntervalSet<T>& other) const; bool Contains(const T& min, const T& max) const { return Contains(value_type(min, max)); } bool Intersects(const QuicIntervalSet& other) const; const_iterator Find(const T& value) const; const_iterator Find(const value_type& interval) const; const_iterator Find(const T& min, const T& max) const { return Find(value_type(min, max)); } const_iterator LowerBound(const T& value) const; const_iterator UpperBound(const T& value) const; bool IsDisjoint(const value_type& interval) const; void Union(const QuicIntervalSet& other); void Intersection(const QuicIntervalSet& other); void Difference(const value_type& interval); void Difference(const T& min, const T& max); void Difference(const QuicIntervalSet& other); void Complement(const T& min, const T& max); const_iterator begin() const { return intervals_.begin(); } const_iterator end() const { return intervals_.end(); } const_reverse_iterator rbegin() const { return intervals_.rbegin(); } const_reverse_iterator rend() const { return intervals_.rend(); } template <typename Iter> void assign(Iter first, Iter last) { Clear(); for (; first != last; ++first) Add(*first); } void assign(std::initializer_list<value_type> il) { assign(il.begin(), il.end()); } std::string ToString() const; QuicIntervalSet& operator=(std::initializer_list<value_type> il) { assign(il.begin(), il.end()); return *this; } friend bool operator==(const QuicIntervalSet& a, const QuicIntervalSet& b) { return a.Size() == b.Size() && std::equal(a.begin(), a.end(), b.begin(), NonemptyIntervalEq()); } friend bool operator!=(const QuicIntervalSet& a, const QuicIntervalSet& b) { return !(a == b); } private: struct QUICHE_NO_EXPORT NonemptyIntervalEq { bool operator()(const value_type& a, const value_type& b) const { return a.min() == b.min() && a.max() == b.max(); } }; bool Valid() const; const_iterator FindIntersectionCandidate(const QuicIntervalSet& other) const; const_iterator FindIntersectionCandidate(const value_type& interval) const; template <typename X, typename Func> static bool FindNextIntersectingPairImpl(X* x, const QuicIntervalSet& y, const_iterator* mine, const_iterator* theirs, Func on_hole); bool FindNextIntersectingPair(const QuicIntervalSet& other, const_iterator* mine, const_iterator* theirs) const { return FindNextIntersectingPairImpl( this, other, mine, theirs, [](const QuicIntervalSet*, const_iterator, const_iterator end) { return end; }); } bool FindNextIntersectingPairAndEraseHoles(const QuicIntervalSet& other, const_iterator* mine, const_iterator* theirs) { return FindNextIntersectingPairImpl( this, other, mine, theirs, [](QuicIntervalSet* x, const_iterator from, const_iterator to) { return x->intervals_.erase(from, to); }); } Set intervals_; }; template <typename T> auto operator<<(std::ostream& out, const QuicIntervalSet<T>& seq) -> decltype(out << *seq.begin()) { out << "{"; for (const auto& interval : seq) { out << " " << interval; } out << " }"; return out; } template <typename T> typename QuicIntervalSet<T>::value_type QuicIntervalSet<T>::SpanningInterval() const { value_type result; if (!intervals_.empty()) { result.SetMin(intervals_.begin()->min()); result.SetMax(intervals_.rbegin()->max()); } return result; } template <typename T> void QuicIntervalSet<T>::Add(const value_type& interval) { if (interval.Empty()) return; const_iterator it = intervals_.lower_bound(interval.min()); value_type the_union = interval; if (it != intervals_.begin()) { --it; if (it->Separated(the_union)) { ++it; } } const_iterator start = it; while (it != intervals_.end() && !it->Separated(the_union)) { the_union.SpanningUnion(*it); ++it; } intervals_.erase(start, it); intervals_.insert(the_union); } template <typename T> bool QuicIntervalSet<T>::Contains(const T& value) const { const_iterator it = intervals_.upper_bound(value); if (it == intervals_.begin()) return false; --it; return it->Contains(value); } template <typename T> bool QuicIntervalSet<T>::Contains(const value_type& interval) const { const_iterator it = intervals_.upper_bound(interval.min()); if (it == intervals_.begin()) return false; --it; return it->Contains(interval); } template <typename T> bool QuicIntervalSet<T>::Contains(const QuicIntervalSet<T>& other) const { if (!SpanningInterval().Contains(other.SpanningInterval())) { return false; } for (const_iterator i = other.begin(); i != other.end(); ++i) { if (!Contains(*i)) { return false; } } return true; } template <typename T> typename QuicIntervalSet<T>::const_iterator QuicIntervalSet<T>::Find( const T& value) const { const_iterator it = intervals_.upper_bound(value); if (it == intervals_.begin()) return intervals_.end(); --it; if (it->Contains(value)) return it; else return intervals_.end(); } template <typename T> typename QuicIntervalSet<T>::const_iterator QuicIntervalSet<T>::Find( const value_type& probe) const { const_iterator it = intervals_.upper_bound(probe.min()); if (it == intervals_.begin()) return intervals_.end(); --it; if (it->Contains(probe)) return it; else return intervals_.end(); } template <typename T> typename QuicIntervalSet<T>::const_iterator QuicIntervalSet<T>::LowerBound( const T& value) const { const_iterator it = intervals_.lower_bound(value); if (it == intervals_.begin()) { return it; } --it; if (it->Contains(value)) { return it; } else { return ++it; } } template <typename T> typename QuicIntervalSet<T>::const_iterator QuicIntervalSet<T>::UpperBound( const T& value) const { return intervals_.upper_bound(value); } template <typename T> bool QuicIntervalSet<T>::IsDisjoint(const value_type& interval) const { if (interval.Empty()) return true; const_iterator it = intervals_.upper_bound(interval.min()); if (it != intervals_.end() && interval.max() > it->min()) return false; if (it == intervals_.begin()) return true; --it; return it->max() <= interval.min(); } template <typename T> void QuicIntervalSet<T>::Union(const QuicIntervalSet& other) { for (const value_type& interval : other.intervals_) { Add(interval); } } template <typename T> typename QuicIntervalSet<T>::const_iterator QuicIntervalSet<T>::FindIntersectionCandidate( const QuicIntervalSet& other) const { return FindIntersectionCandidate(*other.intervals_.begin()); } template <typename T> typename QuicIntervalSet<T>::const_iterator QuicIntervalSet<T>::FindIntersectionCandidate( const value_type& interval) const { const_iterator mine = intervals_.upper_bound(interval.min()); if (mine != intervals_.begin()) { --mine; } return mine; } template <typename T> template <typename X, typename Func> bool QuicIntervalSet<T>::FindNextIntersectingPairImpl(X* x, const QuicIntervalSet& y, const_iterator* mine, const_iterator* theirs, Func on_hole) { QUICHE_CHECK(x != nullptr); if ((*mine == x->intervals_.end()) || (*theirs == y.intervals_.end())) { return false; } while (!(**mine).Intersects(**theirs)) { const_iterator erase_first = *mine; while (*mine != x->intervals_.end() && (**mine).max() <= (**theirs).min()) { ++(*mine); } *mine = on_hole(x, erase_first, *mine); if (*mine == x->intervals_.end()) { return false; } while (*theirs != y.intervals_.end() && (**theirs).max() <= (**mine).min()) { ++(*theirs); } if (*theirs == y.intervals_.end()) { on_hole(x, *mine, x->intervals_.end()); return false; } } return true; } template <typename T> void QuicIntervalSet<T>::Intersection(const QuicIntervalSet& other) { if (!SpanningInterval().Intersects(other.SpanningInterval())) { intervals_.clear(); return; } const_iterator mine = FindIntersectionCandidate(other); mine = intervals_.erase(intervals_.begin(), mine); const_iterator theirs = other.FindIntersectionCandidate(*this); while (FindNextIntersectingPairAndEraseHoles(other, &mine, &theirs)) { value_type i(*mine); intervals_.erase(mine); mine = intervals_.end(); value_type intersection; while (theirs != other.intervals_.end() && i.Intersects(*theirs, &intersection)) { std::pair<const_iterator, bool> ins = intervals_.insert(intersection); QUICHE_DCHECK(ins.second); mine = ins.first; ++theirs; } QUICHE_DCHECK(mine != intervals_.end()); --theirs; ++mine; } QUICHE_DCHECK(Valid()); } template <typename T> bool QuicIntervalSet<T>::Intersects(const QuicIntervalSet& other) const { auto mine = intervals_.begin(); auto theirs = other.intervals_.begin(); while (mine != intervals_.end() && theirs != other.intervals_.end()) { if (mine->Intersects(*theirs)) return true; else if (*mine < *theirs) ++mine; else ++theirs; } return false; } template <typename T> void QuicIntervalSet<T>::Difference(const value_type& interval) { if (!SpanningInterval().Intersects(interval)) { return; } Difference(QuicIntervalSet<T>(interval)); } template <typename T> void QuicIntervalSet<T>::Difference(const T& min, const T& max) { Difference(value_type(min, max)); } template <typename T> void QuicIntervalSet<T>::Difference(const QuicIntervalSet& other) { if (Empty()) return; Set result; const_iterator mine = intervals_.begin(); value_type myinterval = *mine; const_iterator theirs = other.intervals_.begin(); while (mine != intervals_.end()) { QUICHE_DCHECK(!myinterval.Empty()); QUICHE_DCHECK(myinterval.max() == mine->max()); if (theirs == other.intervals_.end() || myinterval.max() <= theirs->min()) { result.insert(result.end(), myinterval); myinterval.Clear(); } else if (theirs->max() <= myinterval.min()) { ++theirs; } else if (myinterval.min() < theirs->min()) { result.insert(result.end(), value_type(myinterval.min(), theirs->min())); myinterval.SetMin(theirs->max()); } else { myinterval.SetMin(theirs->max()); } if (myinterval.Empty()) { ++mine; if (mine != intervals_.end()) { myinterval = *mine; } } } std::swap(result, intervals_); QUICHE_DCHECK(Valid()); } template <typename T> void QuicIntervalSet<T>::Complement(const T& min, const T& max) { QuicIntervalSet<T> span(min, max); span.Difference(*this); intervals_.swap(span.intervals_); } template <typename T> std::string QuicIntervalSet<T>::ToString() const { std::ostringstream os; os << *this; return os.str(); } template <typename T> bool QuicIntervalSet<T>::Valid() const { const_iterator prev = end(); for (const_iterator it = begin(); it != end(); ++it) { if (it->min() >= it->max()) return false; if (prev != end() && prev->max() >= it->min()) return false; prev = it; } return true; } template <typename T> bool QuicIntervalSet<T>::IntervalLess::operator()(const value_type& a, const value_type& b) const { return a.min() < b.min(); } template <typename T> bool QuicIntervalSet<T>::IntervalLess::operator()(const value_type& a, const T& point) const { return a.min() < point; } template <typename T> bool QuicIntervalSet<T>::IntervalLess::operator()(const value_type& a, T&& point) const { return a.min() < point; } template <typename T> bool QuicIntervalSet<T>::IntervalLess::operator()(const T& point, const value_type& a) const { return point < a.min(); } template <typename T> bool QuicIntervalSet<T>::IntervalLess::operator()(T&& point, const value_type& a) const { return point < a.min(); } } #endif
#include "quiche/quic/core/quic_interval_set.h" #include <stdarg.h> #include <algorithm> #include <iostream> #include <iterator> #include <limits> #include <sstream> #include <string> #include <vector> #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { namespace { using ::testing::ElementsAreArray; class QuicIntervalSetTest : public QuicTest { protected: virtual void SetUp() { is.Add(100, 200); is.Add(300, 400); is.Add(500, 600); is.Add(700, 800); is.Add(900, 1000); is.Add(1100, 1200); is.Add(1300, 1400); is.Add(1500, 1600); is.Add(1700, 1800); is.Add(1900, 2000); is.Add(2100, 2200); other.Add(50, 70); other.Add(2250, 2270); other.Add(650, 670); other.Add(350, 360); other.Add(370, 380); other.Add(470, 530); other.Add(770, 830); other.Add(870, 900); other.Add(1200, 1230); other.Add(1270, 1830); } virtual void TearDown() { is.Clear(); EXPECT_TRUE(is.Empty()); other.Clear(); EXPECT_TRUE(other.Empty()); } QuicIntervalSet<int> is; QuicIntervalSet<int> other; }; TEST_F(QuicIntervalSetTest, IsDisjoint) { EXPECT_TRUE(is.IsDisjoint(QuicInterval<int>(0, 99))); EXPECT_TRUE(is.IsDisjoint(QuicInterval<int>(0, 100))); EXPECT_TRUE(is.IsDisjoint(QuicInterval<int>(200, 200))); EXPECT_TRUE(is.IsDisjoint(QuicInterval<int>(200, 299))); EXPECT_TRUE(is.IsDisjoint(QuicInterval<int>(400, 407))); EXPECT_TRUE(is.IsDisjoint(QuicInterval<int>(405, 499))); EXPECT_TRUE(is.IsDisjoint(QuicInterval<int>(2300, 2300))); EXPECT_TRUE( is.IsDisjoint(QuicInterval<int>(2300, std::numeric_limits<int>::max()))); EXPECT_FALSE(is.IsDisjoint(QuicInterval<int>(100, 105))); EXPECT_FALSE(is.IsDisjoint(QuicInterval<int>(199, 300))); EXPECT_FALSE(is.IsDisjoint(QuicInterval<int>(250, 450))); EXPECT_FALSE(is.IsDisjoint(QuicInterval<int>(299, 400))); EXPECT_FALSE(is.IsDisjoint(QuicInterval<int>(250, 2000))); EXPECT_FALSE( is.IsDisjoint(QuicInterval<int>(2199, std::numeric_limits<int>::max()))); EXPECT_TRUE(is.IsDisjoint(QuicInterval<int>(90, 90))); EXPECT_TRUE(is.IsDisjoint(QuicInterval<int>(100, 100))); EXPECT_TRUE(is.IsDisjoint(QuicInterval<int>(100, 90))); EXPECT_TRUE(is.IsDisjoint(QuicInterval<int>(150, 150))); EXPECT_TRUE(is.IsDisjoint(QuicInterval<int>(200, 200))); EXPECT_TRUE(is.IsDisjoint(QuicInterval<int>(400, 300))); } static bool VA_Check(const QuicIntervalSet<int>& is, int count, va_list ap) { std::vector<QuicInterval<int>> intervals(is.begin(), is.end()); if (count != static_cast<int>(intervals.size())) { QUIC_LOG(ERROR) << "Expected " << count << " intervals, got " << intervals.size() << ": " << is; return false; } if (count != static_cast<int>(is.Size())) { QUIC_LOG(ERROR) << "Expected " << count << " intervals, got Size " << is.Size() << ": " << is; return false; } bool result = true; for (int i = 0; i < count; i++) { int min = va_arg(ap, int); int max = va_arg(ap, int); if (min != intervals[i].min() || max != intervals[i].max()) { QUIC_LOG(ERROR) << "Expected: [" << min << ", " << max << ") got " << intervals[i] << " in " << is; result = false; } } return result; } static bool Check(const QuicIntervalSet<int>& is, int count, ...) { va_list ap; va_start(ap, count); const bool result = VA_Check(is, count, ap); va_end(ap); return result; } static void TestContainsAndFind(const QuicIntervalSet<int>& is, int value) { EXPECT_TRUE(is.Contains(value)) << "Set does not contain " << value; auto it = is.Find(value); EXPECT_NE(it, is.end()) << "No iterator to interval containing " << value; EXPECT_TRUE(it->Contains(value)) << "Iterator does not contain " << value; } static void TestContainsAndFind(const QuicIntervalSet<int>& is, int min, int max) { EXPECT_TRUE(is.Contains(min, max)) << "Set does not contain interval with min " << min << "and max " << max; auto it = is.Find(min, max); EXPECT_NE(it, is.end()) << "No iterator to interval with min " << min << "and max " << max; EXPECT_TRUE(it->Contains(QuicInterval<int>(min, max))) << "Iterator does not contain interval with min " << min << "and max " << max; } static void TestNotContainsAndFind(const QuicIntervalSet<int>& is, int value) { EXPECT_FALSE(is.Contains(value)) << "Set contains " << value; auto it = is.Find(value); EXPECT_EQ(it, is.end()) << "There is iterator to interval containing " << value; } static void TestNotContainsAndFind(const QuicIntervalSet<int>& is, int min, int max) { EXPECT_FALSE(is.Contains(min, max)) << "Set contains interval with min " << min << "and max " << max; auto it = is.Find(min, max); EXPECT_EQ(it, is.end()) << "There is iterator to interval with min " << min << "and max " << max; } TEST_F(QuicIntervalSetTest, AddInterval) { QuicIntervalSet<int> s; s.Add(QuicInterval<int>(0, 10)); EXPECT_TRUE(Check(s, 1, 0, 10)); } TEST_F(QuicIntervalSetTest, DecrementIterator) { auto it = is.end(); EXPECT_NE(it, is.begin()); --it; EXPECT_EQ(*it, QuicInterval<int>(2100, 2200)); ++it; EXPECT_EQ(it, is.end()); } TEST_F(QuicIntervalSetTest, AddOptimizedForAppend) { QuicIntervalSet<int> empty_one, empty_two; empty_one.AddOptimizedForAppend(QuicInterval<int>(0, 99)); EXPECT_TRUE(Check(empty_one, 1, 0, 99)); empty_two.AddOptimizedForAppend(1, 50); EXPECT_TRUE(Check(empty_two, 1, 1, 50)); QuicIntervalSet<int> iset; iset.AddOptimizedForAppend(100, 150); iset.AddOptimizedForAppend(200, 250); EXPECT_TRUE(Check(iset, 2, 100, 150, 200, 250)); iset.AddOptimizedForAppend(199, 200); EXPECT_TRUE(Check(iset, 2, 100, 150, 199, 250)); iset.AddOptimizedForAppend(251, 260); EXPECT_TRUE(Check(iset, 3, 100, 150, 199, 250, 251, 260)); iset.AddOptimizedForAppend(252, 260); EXPECT_TRUE(Check(iset, 3, 100, 150, 199, 250, 251, 260)); iset.AddOptimizedForAppend(252, 300); EXPECT_TRUE(Check(iset, 3, 100, 150, 199, 250, 251, 300)); iset.AddOptimizedForAppend(300, 350); EXPECT_TRUE(Check(iset, 3, 100, 150, 199, 250, 251, 350)); } TEST_F(QuicIntervalSetTest, PopFront) { QuicIntervalSet<int> iset{{100, 200}, {400, 500}, {700, 800}}; EXPECT_TRUE(Check(iset, 3, 100, 200, 400, 500, 700, 800)); iset.PopFront(); EXPECT_TRUE(Check(iset, 2, 400, 500, 700, 800)); iset.PopFront(); EXPECT_TRUE(Check(iset, 1, 700, 800)); iset.PopFront(); EXPECT_TRUE(iset.Empty()); } TEST_F(QuicIntervalSetTest, TrimLessThan) { QuicIntervalSet<int> iset{{100, 200}, {400, 500}, {700, 800}}; EXPECT_TRUE(Check(iset, 3, 100, 200, 400, 500, 700, 800)); EXPECT_FALSE(iset.TrimLessThan(99)); EXPECT_FALSE(iset.TrimLessThan(100)); EXPECT_TRUE(Check(iset, 3, 100, 200, 400, 500, 700, 800)); EXPECT_TRUE(iset.TrimLessThan(101)); EXPECT_TRUE(Check(iset, 3, 101, 200, 400, 500, 700, 800)); EXPECT_TRUE(iset.TrimLessThan(199)); EXPECT_TRUE(Check(iset, 3, 199, 200, 400, 500, 700, 800)); EXPECT_TRUE(iset.TrimLessThan(450)); EXPECT_TRUE(Check(iset, 2, 450, 500, 700, 800)); EXPECT_TRUE(iset.TrimLessThan(500)); EXPECT_TRUE(Check(iset, 1, 700, 800)); EXPECT_TRUE(iset.TrimLessThan(801)); EXPECT_TRUE(iset.Empty()); EXPECT_FALSE(iset.TrimLessThan(900)); EXPECT_TRUE(iset.Empty()); } TEST_F(QuicIntervalSetTest, QuicIntervalSetBasic) { QuicIntervalSet<int> iset; EXPECT_TRUE(iset.Empty()); EXPECT_EQ(0u, iset.Size()); iset.Add(100, 200); EXPECT_FALSE(iset.Empty()); EXPECT_EQ(1u, iset.Size()); iset.Add(100, 150); iset.Add(150, 200); iset.Add(130, 170); iset.Add(90, 150); iset.Add(170, 220); iset.Add(300, 400); iset.Add(250, 450); EXPECT_FALSE(iset.Empty()); EXPECT_EQ(2u, iset.Size()); EXPECT_TRUE(Check(iset, 2, 90, 220, 250, 450)); iset.Clear(); iset.Add(100, 200); iset.Add(200, 300); EXPECT_FALSE(iset.Empty()); EXPECT_EQ(1u, iset.Size()); EXPECT_TRUE(Check(iset, 1, 100, 300)); iset.Clear(); QuicIntervalSet<int> iset_add; iset.Add(100, 200); iset.Add(100, 150); iset.Add(150, 200); iset.Add(130, 170); iset_add.Add(90, 150); iset_add.Add(170, 220); iset_add.Add(300, 400); iset_add.Add(250, 450); iset.Union(iset_add); EXPECT_FALSE(iset.Empty()); EXPECT_EQ(2u, iset.Size()); EXPECT_TRUE(Check(iset, 2, 90, 220, 250, 450)); { std::vector<QuicInterval<int>> expected(iset.begin(), iset.end()); std::vector<QuicInterval<int>> actual1; std::copy(iset.begin(), iset.end(), back_inserter(actual1)); ASSERT_EQ(expected.size(), actual1.size()); std::vector<QuicInterval<int>> actual2; std::copy(iset.begin(), iset.end(), back_inserter(actual2)); ASSERT_EQ(expected.size(), actual2.size()); for (size_t i = 0; i < expected.size(); i++) { EXPECT_EQ(expected[i].min(), actual1[i].min()); EXPECT_EQ(expected[i].max(), actual1[i].max()); EXPECT_EQ(expected[i].min(), actual2[i].min()); EXPECT_EQ(expected[i].max(), actual2[i].max()); } EXPECT_THAT(std::vector<QuicInterval<int>>(iset.rbegin(), iset.rend()), ElementsAreArray(expected.rbegin(), expected.rend())); } TestNotContainsAndFind(iset, 89); TestContainsAndFind(iset, 90); TestContainsAndFind(iset, 120); TestContainsAndFind(iset, 219); TestNotContainsAndFind(iset, 220); TestNotContainsAndFind(iset, 235); TestNotContainsAndFind(iset, 249); TestContainsAndFind(iset, 250); TestContainsAndFind(iset, 300); TestContainsAndFind(iset, 449); TestNotContainsAndFind(iset, 450); TestNotContainsAndFind(iset, 451); TestNotContainsAndFind(iset, 50, 60); TestNotContainsAndFind(iset, 50, 90); TestNotContainsAndFind(iset, 50, 200); TestNotContainsAndFind(iset, 90, 90); TestContainsAndFind(iset, 90, 200); TestContainsAndFind(iset, 100, 200); TestContainsAndFind(iset, 100, 220); TestNotContainsAndFind(iset, 100, 221); TestNotContainsAndFind(iset, 220, 220); TestNotContainsAndFind(iset, 240, 300); TestContainsAndFind(iset, 250, 300); TestContainsAndFind(iset, 260, 300); TestContainsAndFind(iset, 300, 450); TestNotContainsAndFind(iset, 300, 451); QuicIntervalSet<int> iset_contains; iset_contains.Add(50, 90); EXPECT_FALSE(iset.Contains(iset_contains)); iset_contains.Clear(); iset_contains.Add(90, 200); EXPECT_TRUE(iset.Contains(iset_contains)); iset_contains.Add(100, 200); EXPECT_TRUE(iset.Contains(iset_contains)); iset_contains.Add(100, 220); EXPECT_TRUE(iset.Contains(iset_contains)); iset_contains.Add(250, 300); EXPECT_TRUE(iset.Contains(iset_contains)); iset_contains.Add(300, 450); EXPECT_TRUE(iset.Contains(iset_contains)); iset_contains.Add(300, 451); EXPECT_FALSE(iset.Contains(iset_contains)); EXPECT_FALSE(iset.Contains(QuicInterval<int>())); EXPECT_FALSE(iset.Contains(QuicIntervalSet<int>())); QuicIntervalSet<int> i2({{220, 230}}); EXPECT_FALSE(iset.Contains(i2)); } TEST_F(QuicIntervalSetTest, QuicIntervalSetContainsEmpty) { const QuicIntervalSet<int> empty; const QuicIntervalSet<int> other_empty; const QuicIntervalSet<int> non_empty({{10, 20}, {40, 50}}); EXPECT_FALSE(empty.Contains(empty)); EXPECT_FALSE(empty.Contains(other_empty)); EXPECT_FALSE(empty.Contains(non_empty)); EXPECT_FALSE(non_empty.Contains(empty)); } TEST_F(QuicIntervalSetTest, Equality) { QuicIntervalSet<int> is_copy = is; EXPECT_EQ(is, is); EXPECT_EQ(is, is_copy); EXPECT_NE(is, other); EXPECT_NE(is, QuicIntervalSet<int>()); EXPECT_EQ(QuicIntervalSet<int>(), QuicIntervalSet<int>()); } TEST_F(QuicIntervalSetTest, LowerAndUpperBound) { QuicIntervalSet<int> intervals; intervals.Add(10, 20); intervals.Add(30, 40); EXPECT_EQ(intervals.LowerBound(5)->min(), 10); EXPECT_EQ(intervals.LowerBound(10)->min(), 10); EXPECT_EQ(intervals.LowerBound(15)->min(), 10); EXPECT_EQ(intervals.LowerBound(20)->min(), 30); EXPECT_EQ(intervals.LowerBound(25)->min(), 30); EXPECT_EQ(intervals.LowerBound(30)->min(), 30); EXPECT_EQ(intervals.LowerBound(35)->min(), 30); EXPECT_EQ(intervals.LowerBound(40), intervals.end()); EXPECT_EQ(intervals.LowerBound(50), intervals.end()); EXPECT_EQ(intervals.UpperBound(5)->min(), 10); EXPECT_EQ(intervals.UpperBound(10)->min(), 30); EXPECT_EQ(intervals.UpperBound(15)->min(), 30); EXPECT_EQ(intervals.UpperBound(20)->min(), 30); EXPECT_EQ(intervals.UpperBound(25)->min(), 30); EXPECT_EQ(intervals.UpperBound(30), intervals.end()); EXPECT_EQ(intervals.UpperBound(35), intervals.end()); EXPECT_EQ(intervals.UpperBound(40), intervals.end()); EXPECT_EQ(intervals.UpperBound(50), intervals.end()); } TEST_F(QuicIntervalSetTest, SpanningInterval) { { QuicIntervalSet<int> iset; const QuicInterval<int>& ival = iset.SpanningInterval(); EXPECT_TRUE(ival.Empty()); } { QuicIntervalSet<int> iset; iset.Add(100, 200); const QuicInterval<int>& ival = iset.SpanningInterval(); EXPECT_EQ(100, ival.min()); EXPECT_EQ(200, ival.max()); } { const QuicInterval<int>& ival = is.SpanningInterval(); EXPECT_EQ(100, ival.min()); EXPECT_EQ(2200, ival.max()); } { const QuicInterval<int>& ival = other.SpanningInterval(); EXPECT_EQ(50, ival.min()); EXPECT_EQ(2270, ival.max()); } } TEST_F(QuicIntervalSetTest, QuicIntervalSetUnion) { is.Union(other); EXPECT_TRUE(Check(is, 12, 50, 70, 100, 200, 300, 400, 470, 600, 650, 670, 700, 830, 870, 1000, 1100, 1230, 1270, 1830, 1900, 2000, 2100, 2200, 2250, 2270)); } TEST_F(QuicIntervalSetTest, QuicIntervalSetIntersection) { EXPECT_TRUE(is.Intersects(other)); EXPECT_TRUE(other.Intersects(is)); is.Intersection(other); EXPECT_TRUE(Check(is, 7, 350, 360, 370, 380, 500, 530, 770, 800, 1300, 1400, 1500, 1600, 1700, 1800)); EXPECT_TRUE(is.Intersects(other)); EXPECT_TRUE(other.Intersects(is)); } TEST_F(QuicIntervalSetTest, QuicIntervalSetIntersectionBothEmpty) { QuicIntervalSet<std::string> mine, theirs; EXPECT_FALSE(mine.Intersects(theirs)); EXPECT_FALSE(theirs.Intersects(mine)); mine.Intersection(theirs); EXPECT_TRUE(mine.Empty()); EXPECT_FALSE(mine.Intersects(theirs)); EXPECT_FALSE(theirs.Intersects(mine)); } TEST_F(QuicIntervalSetTest, QuicIntervalSetIntersectionEmptyMine) { QuicIntervalSet<std::string> mine; QuicIntervalSet<std::string> theirs("a", "b"); EXPECT_FALSE(mine.Intersects(theirs)); EXPECT_FALSE(theirs.Intersects(mine)); mine.Intersection(theirs); EXPECT_TRUE(mine.Empty()); EXPECT_FALSE(mine.Intersects(theirs)); EXPECT_FALSE(theirs.Intersects(mine)); } TEST_F(QuicIntervalSetTest, QuicIntervalSetIntersectionEmptyTheirs) { QuicIntervalSet<std::string> mine("a", "b"); QuicIntervalSet<std::string> theirs; EXPECT_FALSE(mine.Intersects(theirs)); EXPECT_FALSE(theirs.Intersects(mine)); mine.Intersection(theirs); EXPECT_TRUE(mine.Empty()); EXPECT_FALSE(mine.Intersects(theirs)); EXPECT_FALSE(theirs.Intersects(mine)); } TEST_F(QuicIntervalSetTest, QuicIntervalSetIntersectionTheirsBeforeMine) { QuicIntervalSet<std::string> mine("y", "z"); QuicIntervalSet<std::string> theirs; theirs.Add("a", "b"); theirs.Add("c", "d"); EXPECT_FALSE(mine.Intersects(theirs)); EXPECT_FALSE(theirs.Intersects(mine)); mine.Intersection(theirs); EXPECT_TRUE(mine.Empty()); EXPECT_FALSE(mine.Intersects(theirs)); EXPECT_FALSE(theirs.Intersects(mine)); } TEST_F(QuicIntervalSetTest, QuicIntervalSetIntersectionMineBeforeTheirs) { QuicIntervalSet<std::string> mine; mine.Add("a", "b"); mine.Add("c", "d"); QuicIntervalSet<std::string> theirs("y", "z"); EXPECT_FALSE(mine.Intersects(theirs)); EXPECT_FALSE(theirs.Intersects(mine)); mine.Intersection(theirs); EXPECT_TRUE(mine.Empty()); EXPECT_FALSE(mine.Intersects(theirs)); EXPECT_FALSE(theirs.Intersects(mine)); } TEST_F(QuicIntervalSetTest, QuicIntervalSetIntersectionTheirsBeforeMineInt64Singletons) { QuicIntervalSet<int64_t> mine({{10, 15}}); QuicIntervalSet<int64_t> theirs({{-20, -5}}); EXPECT_FALSE(mine.Intersects(theirs)); EXPECT_FALSE(theirs.Intersects(mine)); mine.Intersection(theirs); EXPECT_TRUE(mine.Empty()); EXPECT_FALSE(mine.Intersects(theirs)); EXPECT_FALSE(theirs.Intersects(mine)); } TEST_F(QuicIntervalSetTest, QuicIntervalSetIntersectionMineBeforeTheirsIntSingletons) { QuicIntervalSet<int> mine({{10, 15}}); QuicIntervalSet<int> theirs({{90, 95}}); EXPECT_FALSE(mine.Intersects(theirs)); EXPECT_FALSE(theirs.Intersects(mine)); mine.Intersection(theirs); EXPECT_TRUE(mine.Empty()); EXPECT_FALSE(mine.Intersects(theirs)); EXPECT_FALSE(theirs.Intersects(mine)); } TEST_F(QuicIntervalSetTest, QuicIntervalSetIntersectionTheirsBetweenMine) { QuicIntervalSet<int64_t> mine({{0, 5}, {40, 50}}); QuicIntervalSet<int64_t> theirs({{10, 15}}); EXPECT_FALSE(mine.Intersects(theirs)); EXPECT_FALSE(theirs.Intersects(mine)); mine.Intersection(theirs); EXPECT_TRUE(mine.Empty()); EXPECT_FALSE(mine.Intersects(theirs)); EXPECT_FALSE(theirs.Intersects(mine)); } TEST_F(QuicIntervalSetTest, QuicIntervalSetIntersectionMineBetweenTheirs) { QuicIntervalSet<int> mine({{20, 25}}); QuicIntervalSet<int> theirs({{10, 15}, {30, 32}}); EXPECT_FALSE(mine.Intersects(theirs)); EXPECT_FALSE(theirs.Intersects(mine)); mine.Intersection(theirs); EXPECT_TRUE(mine.Empty()); EXPECT_FALSE(mine.Intersects(theirs)); EXPECT_FALSE(theirs.Intersects(mine)); } TEST_F(QuicIntervalSetTest, QuicIntervalSetIntersectionAlternatingIntervals) { QuicIntervalSet<int> mine, theirs; mine.Add(10, 20); mine.Add(40, 50); mine.Add(60, 70); theirs.Add(25, 39); theirs.Add(55, 59); theirs.Add(75, 79); EXPECT_FALSE(mine.Intersects(theirs)); EXPECT_FALSE(theirs.Intersects(mine)); mine.Intersection(theirs); EXPECT_TRUE(mine.Empty()); EXPECT_FALSE(mine.Intersects(theirs)); EXPECT_FALSE(theirs.Intersects(mine)); } TEST_F(QuicIntervalSetTest, QuicIntervalSetIntersectionAdjacentAlternatingNonIntersectingIntervals) { const QuicIntervalSet<int> x1({{0, 10}}); const QuicIntervalSet<int> y1({{-50, 0}, {10, 95}}); QuicIntervalSet<int> result1 = x1; result1.Intersection(y1); EXPECT_TRUE(result1.Empty()) << result1; const QuicIntervalSet<int16_t> x2({{0, 10}, {20, 30}, {40, 90}}); const QuicIntervalSet<int16_t> y2( {{-50, -40}, {-2, 0}, {10, 20}, {32, 40}, {90, 95}}); QuicIntervalSet<int16_t> result2 = x2; result2.Intersection(y2); EXPECT_TRUE(result2.Empty()) << result2; const QuicIntervalSet<int64_t> x3({{-1, 5}, {5, 10}}); const QuicIntervalSet<int64_t> y3({{-10, -1}, {10, 95}}); QuicIntervalSet<int64_t> result3 = x3; result3.Intersection(y3); EXPECT_TRUE(result3.Empty()) << result3; } TEST_F(QuicIntervalSetTest, QuicIntervalSetIntersectionAlternatingIntersectingIntervals) { const QuicIntervalSet<int> x1({{0, 10}}); const QuicIntervalSet<int> y1({{-50, 1}, {9, 95}}); const QuicIntervalSet<int> expected_result1({{0, 1}, {9, 10}}); QuicIntervalSet<int> result1 = x1; result1.Intersection(y1); EXPECT_EQ(result1, expected_result1); const QuicIntervalSet<int16_t> x2({{0, 10}, {20, 30}, {40, 90}}); const QuicIntervalSet<int16_t> y2( {{-50, -40}, {-2, 2}, {9, 21}, {32, 41}, {85, 95}}); const QuicIntervalSet<int16_t> expected_result2( {{0, 2}, {9, 10}, {20, 21}, {40, 41}, {85, 90}}); QuicIntervalSet<int16_t> result2 = x2; result2.Intersection(y2); EXPECT_EQ(result2, expected_result2); const QuicIntervalSet<int64_t> x3({{-1, 5}, {5, 10}}); const QuicIntervalSet<int64_t> y3({{-10, 3}, {4, 95}}); const QuicIntervalSet<int64_t> expected_result3({{-1, 3}, {4, 10}}); QuicIntervalSet<int64_t> result3 = x3; result3.Intersection(y3); EXPECT_EQ(result3, expected_result3); } TEST_F(QuicIntervalSetTest, QuicIntervalSetIntersectionIdentical) { QuicIntervalSet<int> copy(is); EXPECT_TRUE(copy.Intersects(is)); EXPECT_TRUE(is.Intersects(copy)); is.Intersection(copy); EXPECT_EQ(copy, is); } TEST_F(QuicIntervalSetTest, QuicIntervalSetIntersectionSuperset) { QuicIntervalSet<int> mine(-1, 10000); EXPECT_TRUE(mine.Intersects(is)); EXPECT_TRUE(is.Intersects(mine)); mine.Intersection(is); EXPECT_EQ(is, mine); } TEST_F(QuicIntervalSetTest, QuicIntervalSetIntersectionSubset) { QuicIntervalSet<int> copy(is); QuicIntervalSet<int> theirs(-1, 10000); EXPECT_TRUE(copy.Intersects(theirs)); EXPECT_TRUE(theirs.Intersects(copy)); is.Intersection(theirs); EXPECT_EQ(copy, is); } TEST_F(QuicIntervalSetTest, QuicIntervalSetIntersectionLargeSet) { QuicIntervalSet<int> mine, theirs; for (int i = 0; i < 1000; i += 10) { mine.Add(i, i + 9); } theirs.Add(500, 520); theirs.Add(535, 545); theirs.Add(801, 809); EXPECT_TRUE(mine.Intersects(theirs)); EXPECT_TRUE(theirs.Intersects(mine)); mine.Intersection(theirs); EXPECT_TRUE(Check(mine, 5, 500, 509, 510, 519, 535, 539, 540, 545, 801, 809)); EXPECT_TRUE(mine.Intersects(theirs)); EXPECT_TRUE(theirs.Intersects(mine)); } TEST_F(QuicIntervalSetTest, QuicIntervalSetDifference) { is.Difference(other); EXPECT_TRUE(Check(is, 10, 100, 200, 300, 350, 360, 370, 380, 400, 530, 600, 700, 770, 900, 1000, 1100, 1200, 1900, 2000, 2100, 2200)); QuicIntervalSet<int> copy = is; is.Difference(copy); EXPECT_TRUE(is.Empty()); } TEST_F(QuicIntervalSetTest, QuicIntervalSetDifferenceSingleBounds) { std::vector<QuicInterval<int>> ivals(other.begin(), other.end()); for (const QuicInterval<int>& ival : ivals) { is.Difference(ival.min(), ival.max()); } EXPECT_TRUE(Check(is, 10, 100, 200, 300, 350, 360, 370, 380, 400, 530, 600, 700, 770, 900, 1000, 1100, 1200, 1900, 2000, 2100, 2200)); } TEST_F(QuicIntervalSetTest, QuicIntervalSetDifferenceSingleInterval) { std::vector<QuicInterval<int>> ivals(other.begin(), other.end()); for (const QuicInterval<int>& ival : ivals) { is.Difference(ival); } EXPECT_TRUE(Check(is, 10, 100, 200, 300, 350, 360, 370, 380, 400, 530, 600, 700, 770, 900, 1000, 1100, 1200, 1900, 2000, 2100, 2200)); } TEST_F(QuicIntervalSetTest, QuicIntervalSetDifferenceAlternatingIntervals) { QuicIntervalSet<int> mine, theirs; mine.Add(10, 20); mine.Add(40, 50); mine.Add(60, 70); theirs.Add(25, 39); theirs.Add(55, 59); theirs.Add(75, 79); mine.Difference(theirs); EXPECT_TRUE(Check(mine, 3, 10, 20, 40, 50, 60, 70)); } TEST_F(QuicIntervalSetTest, QuicIntervalSetDifferenceEmptyMine) { QuicIntervalSet<std::string> mine, theirs; theirs.Add("a", "b"); mine.Difference(theirs); EXPECT_TRUE(mine.Empty()); } TEST_F(QuicIntervalSetTest, QuicIntervalSetDifferenceEmptyTheirs) { QuicIntervalSet<std::string> mine, theirs; mine.Add("a", "b"); mine.Difference(theirs); EXPECT_EQ(1u, mine.Size()); EXPECT_EQ("a", mine.begin()->min()); EXPECT_EQ("b", mine.begin()->max()); } TEST_F(QuicIntervalSetTest, QuicIntervalSetDifferenceTheirsBeforeMine) { QuicIntervalSet<std::string> mine, theirs; mine.Add("y", "z"); theirs.Add("a", "b"); mine.Difference(theirs); EXPECT_EQ(1u, mine.Size()); EXPECT_EQ("y", mine.begin()->min()); EXPECT_EQ("z", mine.begin()->max()); } TEST_F(QuicIntervalSetTest, QuicIntervalSetDifferenceMineBeforeTheirs) { QuicIntervalSet<std::string> mine, theirs; mine.Add("a", "b"); theirs.Add("y", "z"); mine.Difference(theirs); EXPECT_EQ(1u, mine.Size()); EXPECT_EQ("a", mine.begin()->min()); EXPECT_EQ("b", mine.begin()->max()); } TEST_F(QuicIntervalSetTest, QuicIntervalSetDifferenceIdentical) { QuicIntervalSet<std::string> mine; mine.Add("a", "b"); mine.Add("c", "d"); QuicIntervalSet<std::string> theirs(mine); mine.Difference(theirs); EXPECT_TRUE(mine.Empty()); } TEST_F(QuicIntervalSetTest, EmptyComplement) { QuicIntervalSet<int> iset; iset.Complement(100, 200); EXPECT_TRUE(Check(iset, 1, 100, 200)); } TEST(QuicIntervalSetMultipleCompactionTest, OuterCovering) { QuicIntervalSet<int> iset; iset.Add(100, 150); iset.Add(200, 250); iset.Add(300, 350); iset.Add(400, 450); EXPECT_TRUE(Check(iset, 4, 100, 150, 200, 250, 300, 350, 400, 450)); iset.Add(0, 500); EXPECT_TRUE(Check(iset, 1, 0, 500)); } TEST(QuicIntervalSetMultipleCompactionTest, InnerCovering) { QuicIntervalSet<int> iset; iset.Add(100, 150); iset.Add(200, 250); iset.Add(300, 350); iset.Add(400, 450); EXPECT_TRUE(Check(iset, 4, 100, 150, 200, 250, 300, 350, 400, 450)); iset.Add(125, 425); EXPECT_TRUE(Check(iset, 1, 100, 450)); } TEST(QuicIntervalSetMultipleCompactionTest, LeftCovering) { QuicIntervalSet<int> iset; iset.Add(100, 150); iset.Add(200, 250); iset.Add(300, 350); iset.Add(400, 450); EXPECT_TRUE(Check(iset, 4, 100, 150, 200, 250, 300, 350, 400, 450)); iset.Add(125, 500); EXPECT_TRUE(Check(iset, 1, 100, 500)); } TEST(QuicIntervalSetMultipleCompactionTest, RightCovering) { QuicIntervalSet<int> iset; iset.Add(100, 150); iset.Add(200, 250); iset.Add(300, 350); iset.Add(400, 450); EXPECT_TRUE(Check(iset, 4, 100, 150, 200, 250, 300, 350, 400, 450)); iset.Add(0, 425); EXPECT_TRUE(Check(iset, 1, 0, 450)); } static bool CheckOneComplement(int add_min, int add_max, int comp_min, int comp_max, int count, ...) { QuicIntervalSet<int> iset; iset.Add(add_min, add_max); iset.Complement(comp_min, comp_max); bool result = true; va_list ap; va_start(ap, count); if (!VA_Check(iset, count, ap)) { result = false; } va_end(ap); return result; } TEST_F(QuicIntervalSetTest, SingleIntervalComplement) { EXPECT_TRUE(CheckOneComplement(0, 10, 50, 150, 1, 50, 150)); EXPECT_TRUE(CheckOneComplement(50, 150, 0, 100, 1, 0, 50)); EXPECT_TRUE(CheckOneComplement(50, 150, 50, 150, 0)); EXPECT_TRUE(CheckOneComplement(50, 500, 100, 300, 0)); EXPECT_TRUE(CheckOneComplement(50, 500, 0, 800, 2, 0, 50, 500, 800)); EXPECT_TRUE(CheckOneComplement(50, 150, 100, 300, 1, 150, 300)); EXPECT_TRUE(CheckOneComplement(50, 150, 200, 300, 1, 200, 300)); } static bool CheckComplement(const QuicIntervalSet<int>& iset, int comp_min, int comp_max, int count, ...) { QuicIntervalSet<int> iset_copy = iset; iset_copy.Complement(comp_min, comp_max); bool result = true; va_list ap; va_start(ap, count); if (!VA_Check(iset_copy, count, ap)) { result = false; } va_end(ap); return result; } TEST_F(QuicIntervalSetTest, MultiIntervalComplement) { QuicIntervalSet<int> iset; iset.Add(100, 200); iset.Add(300, 400); iset.Add(500, 600); EXPECT_TRUE(CheckComplement(iset, 0, 50, 1, 0, 50)); EXPECT_TRUE(CheckComplement(iset, 0, 200, 1, 0, 100)); EXPECT_TRUE(CheckComplement(iset, 0, 220, 2, 0, 100, 200, 220)); EXPECT_TRUE(CheckComplement(iset, 100, 600, 2, 200, 300, 400, 500)); EXPECT_TRUE(CheckComplement(iset, 300, 400, 0)); EXPECT_TRUE(CheckComplement(iset, 250, 400, 1, 250, 300)); EXPECT_TRUE(CheckComplement(iset, 300, 450, 1, 400, 450)); EXPECT_TRUE(CheckComplement(iset, 250, 450, 2, 250, 300, 400, 450)); EXPECT_TRUE( CheckComplement(iset, 0, 700, 4, 0, 100, 200, 300, 400, 500, 600, 700)); EXPECT_TRUE(CheckComplement(iset, 400, 700, 2, 400, 500, 600, 700)); EXPECT_TRUE(CheckComplement(iset, 350, 700, 2, 400, 500, 600, 700)); EXPECT_TRUE(CheckComplement(iset, 700, 800, 1, 700, 800)); } TEST_F(QuicIntervalSetTest, ToString) { QuicIntervalSet<int> iset; iset.Add(300, 400); iset.Add(100, 200); iset.Add(500, 600); EXPECT_TRUE(!iset.ToString().empty()); QUIC_VLOG(2) << iset; EXPECT_EQ("{ [100, 200) [300, 400) [500, 600) }", iset.ToString()); EXPECT_EQ("{ [1, 2) }", QuicIntervalSet<int>(1, 2).ToString()); EXPECT_EQ("{ }", QuicIntervalSet<int>().ToString()); } TEST_F(QuicIntervalSetTest, ConstructionDiscardsEmptyInterval) { EXPECT_TRUE(QuicIntervalSet<int>(QuicInterval<int>(2, 2)).Empty()); EXPECT_TRUE(QuicIntervalSet<int>(2, 2).Empty()); EXPECT_FALSE(QuicIntervalSet<int>(QuicInterval<int>(2, 3)).Empty()); EXPECT_FALSE(QuicIntervalSet<int>(2, 3).Empty()); } TEST_F(QuicIntervalSetTest, Swap) { QuicIntervalSet<int> a, b; a.Add(300, 400); b.Add(100, 200); b.Add(500, 600); std::swap(a, b); EXPECT_TRUE(Check(a, 2, 100, 200, 500, 600)); EXPECT_TRUE(Check(b, 1, 300, 400)); std::swap(a, b); EXPECT_TRUE(Check(a, 1, 300, 400)); EXPECT_TRUE(Check(b, 2, 100, 200, 500, 600)); } TEST_F(QuicIntervalSetTest, OutputReturnsOstreamRef) { std::stringstream ss; const QuicIntervalSet<int> v(QuicInterval<int>(1, 2)); auto return_type_is_a_ref = [](std::ostream&) {}; return_type_is_a_ref(ss << v); } struct NotOstreamable { bool operator<(const NotOstreamable&) const { return false; } bool operator>(const NotOstreamable&) const { return false; } bool operator!=(const NotOstreamable&) const { return false; } bool operator>=(const NotOstreamable&) const { return true; } bool operator<=(const NotOstreamable&) const { return true; } bool operator==(const NotOstreamable&) const { return true; } }; TEST_F(QuicIntervalSetTest, IntervalOfTypeWithNoOstreamSupport) { const NotOstreamable v; const QuicIntervalSet<NotOstreamable> d(QuicInterval<NotOstreamable>(v, v)); EXPECT_EQ(d, d); } class QuicIntervalSetInitTest : public QuicTest { protected: const std::vector<QuicInterval<int>> intervals_{{0, 1}, {2, 4}}; }; TEST_F(QuicIntervalSetInitTest, DirectInit) { std::initializer_list<QuicInterval<int>> il = {{0, 1}, {2, 3}, {3, 4}}; QuicIntervalSet<int> s(il); EXPECT_THAT(s, ElementsAreArray(intervals_)); } TEST_F(QuicIntervalSetInitTest, CopyInit) { std::initializer_list<QuicInterval<int>> il = {{0, 1}, {2, 3}, {3, 4}}; QuicIntervalSet<int> s = il; EXPECT_THAT(s, ElementsAreArray(intervals_)); } TEST_F(QuicIntervalSetInitTest, AssignIterPair) { QuicIntervalSet<int> s(0, 1000); s.assign(intervals_.begin(), intervals_.end()); EXPECT_THAT(s, ElementsAreArray(intervals_)); } TEST_F(QuicIntervalSetInitTest, AssignInitList) { QuicIntervalSet<int> s(0, 1000); s.assign({{0, 1}, {2, 3}, {3, 4}}); EXPECT_THAT(s, ElementsAreArray(intervals_)); } TEST_F(QuicIntervalSetInitTest, AssignmentInitList) { std::initializer_list<QuicInterval<int>> il = {{0, 1}, {2, 3}, {3, 4}}; QuicIntervalSet<int> s; s = il; EXPECT_THAT(s, ElementsAreArray(intervals_)); } TEST_F(QuicIntervalSetInitTest, BracedInitThenBracedAssign) { QuicIntervalSet<int> s{{0, 1}, {2, 3}, {3, 4}}; s = {{0, 1}, {2, 4}}; EXPECT_THAT(s, ElementsAreArray(intervals_)); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_interval_set.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_interval_set_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
791319cb-920a-4cc6-af9c-e32d1694afba
cpp
google/quiche
quic_interval_deque
quiche/quic/core/quic_interval_deque.h
quiche/quic/core/quic_interval_deque_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_INTERVAL_DEQUE_H_ #define QUICHE_QUIC_CORE_QUIC_INTERVAL_DEQUE_H_ #include <algorithm> #include <optional> #include "quiche/quic/core/quic_interval.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/common/quiche_circular_deque.h" namespace quic { namespace test { class QuicIntervalDequePeer; } template <class T, class C = quiche::QuicheCircularDeque<T>> class QUICHE_NO_EXPORT QuicIntervalDeque { public: class QUICHE_NO_EXPORT Iterator { public: using iterator_category = std::random_access_iterator_tag; using value_type = T; using difference_type = std::ptrdiff_t; using pointer = T*; using reference = T&; Iterator(std::size_t index, QuicIntervalDeque* deque) : index_(index), deque_(deque) {} Iterator& operator++() { const std::size_t container_size = deque_->container_.size(); if (index_ >= container_size) { QUIC_BUG(QuicIntervalDeque_operator_plus_plus_iterator_out_of_bounds) << "Iterator out of bounds."; return *this; } index_++; if (deque_->cached_index_.has_value()) { const std::size_t cached_index = *deque_->cached_index_; if (index_ == container_size) { deque_->cached_index_.reset(); } else { if (cached_index < index_) { deque_->cached_index_ = index_; } } } return *this; } Iterator operator++(int) { Iterator copy = *this; ++(*this); return copy; } Iterator& operator--() { if (index_ == 0) { QUIC_BUG(QuicIntervalDeque_operator_minus_minus_iterator_out_of_bounds) << "Iterator out of bounds."; return *this; } index_--; return *this; } Iterator operator--(int) { Iterator copy = *this; --(*this); return copy; } reference operator*() { return deque_->container_[index_]; } reference operator*() const { return deque_->container_[index_]; } pointer operator->() { return &deque_->container_[index_]; } bool operator==(const Iterator& rhs) const { return index_ == rhs.index_ && deque_ == rhs.deque_; } bool operator!=(const Iterator& rhs) const { return !(*this == rhs); } Iterator& operator+=(difference_type amount) { QUICHE_DCHECK_GE(static_cast<difference_type>(index_), -amount); index_ += amount; QUICHE_DCHECK_LT(index_, deque_->Size()); return *this; } Iterator& operator-=(difference_type amount) { return operator+=(-amount); } difference_type operator-(const Iterator& rhs) const { return static_cast<difference_type>(index_) - static_cast<difference_type>(rhs.index_); } private: std::size_t index_; QuicIntervalDeque* deque_; friend class QuicIntervalDeque; }; QuicIntervalDeque(); void PushBack(T&& item); void PushBack(const T& item); void PopFront(); Iterator DataBegin(); Iterator DataEnd(); Iterator DataAt(const std::size_t interval_begin); std::size_t Size() const; bool Empty() const; private: struct QUICHE_NO_EXPORT IntervalCompare { bool operator()(const T& item, std::size_t interval_begin) const { return item.interval().max() <= interval_begin; } }; template <class U> void PushBackUniversal(U&& item); Iterator Search(const std::size_t interval_begin, const std::size_t begin_index, const std::size_t end_index); friend class test::QuicIntervalDequePeer; C container_; std::optional<std::size_t> cached_index_; }; template <class T, class C> QuicIntervalDeque<T, C>::QuicIntervalDeque() {} template <class T, class C> void QuicIntervalDeque<T, C>::PushBack(T&& item) { PushBackUniversal(std::move(item)); } template <class T, class C> void QuicIntervalDeque<T, C>::PushBack(const T& item) { PushBackUniversal(item); } template <class T, class C> void QuicIntervalDeque<T, C>::PopFront() { if (container_.size() == 0) { QUIC_BUG(QuicIntervalDeque_PopFront_empty) << "Trying to pop from an empty container."; return; } container_.pop_front(); if (container_.size() == 0) { cached_index_.reset(); } if (cached_index_.value_or(0) > 0) { cached_index_ = *cached_index_ - 1; } } template <class T, class C> typename QuicIntervalDeque<T, C>::Iterator QuicIntervalDeque<T, C>::DataBegin() { return Iterator(0, this); } template <class T, class C> typename QuicIntervalDeque<T, C>::Iterator QuicIntervalDeque<T, C>::DataEnd() { return Iterator(container_.size(), this); } template <class T, class C> typename QuicIntervalDeque<T, C>::Iterator QuicIntervalDeque<T, C>::DataAt( const std::size_t interval_begin) { if (!cached_index_.has_value()) { return Search(interval_begin, 0, container_.size()); } const std::size_t cached_index = *cached_index_; QUICHE_DCHECK(cached_index < container_.size()); const QuicInterval<size_t> cached_interval = container_[cached_index].interval(); if (cached_interval.Contains(interval_begin)) { return Iterator(cached_index, this); } const std::size_t next_index = cached_index + 1; if (next_index < container_.size()) { if (container_[next_index].interval().Contains(interval_begin)) { cached_index_ = next_index; return Iterator(next_index, this); } } const std::size_t cached_begin = cached_interval.min(); bool looking_below = interval_begin < cached_begin; const std::size_t lower = looking_below ? 0 : cached_index + 1; const std::size_t upper = looking_below ? cached_index : container_.size(); Iterator ret = Search(interval_begin, lower, upper); if (ret == DataEnd()) { return ret; } if (!looking_below) { cached_index_ = ret.index_; } return ret; } template <class T, class C> std::size_t QuicIntervalDeque<T, C>::Size() const { return container_.size(); } template <class T, class C> bool QuicIntervalDeque<T, C>::Empty() const { return container_.size() == 0; } template <class T, class C> template <class U> void QuicIntervalDeque<T, C>::PushBackUniversal(U&& item) { QuicInterval<std::size_t> interval = item.interval(); if (interval.Empty()) { QUIC_BUG(QuicIntervalDeque_PushBackUniversal_empty) << "Trying to save empty interval to quiche::QuicheCircularDeque."; return; } container_.push_back(std::forward<U>(item)); if (!cached_index_.has_value()) { cached_index_ = container_.size() - 1; } } template <class T, class C> typename QuicIntervalDeque<T, C>::Iterator QuicIntervalDeque<T, C>::Search( const std::size_t interval_begin, const std::size_t begin_index, const std::size_t end_index) { auto begin = container_.begin() + begin_index; auto end = container_.begin() + end_index; auto res = std::lower_bound(begin, end, interval_begin, IntervalCompare()); if (res != end && res->interval().Contains(interval_begin)) { return Iterator(std::distance(begin, res) + begin_index, this); } return DataEnd(); } } #endif
#include "quiche/quic/core/quic_interval_deque.h" #include <cstdint> #include <ostream> #include "quiche/quic/core/quic_interval.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_interval_deque_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { namespace test { namespace { const int32_t kSize = 100; const std::size_t kIntervalStep = 10; } struct TestIntervalItem { int32_t val; std::size_t interval_start, interval_end; QuicInterval<std::size_t> interval() const { return QuicInterval<std::size_t>(interval_start, interval_end); } TestIntervalItem(int32_t val, std::size_t interval_start, std::size_t interval_end) : val(val), interval_start(interval_start), interval_end(interval_end) {} }; using QID = QuicIntervalDeque<TestIntervalItem>; class QuicIntervalDequeTest : public QuicTest { public: QuicIntervalDequeTest() { for (int32_t i = 0; i < kSize; ++i) { const std::size_t interval_begin = kIntervalStep * i; const std::size_t interval_end = interval_begin + kIntervalStep; qid_.PushBack(TestIntervalItem(i, interval_begin, interval_end)); } } QID qid_; }; TEST_F(QuicIntervalDequeTest, InsertRemoveSize) { QID qid; EXPECT_EQ(qid.Size(), std::size_t(0)); qid.PushBack(TestIntervalItem(0, 0, 10)); EXPECT_EQ(qid.Size(), std::size_t(1)); qid.PushBack(TestIntervalItem(1, 10, 20)); EXPECT_EQ(qid.Size(), std::size_t(2)); qid.PushBack(TestIntervalItem(2, 20, 30)); EXPECT_EQ(qid.Size(), std::size_t(3)); qid.PushBack(TestIntervalItem(3, 30, 40)); EXPECT_EQ(qid.Size(), std::size_t(4)); int32_t i = 0; for (auto it = qid.DataAt(0); it != qid.DataEnd(); ++it, ++i) { const int32_t index = QuicIntervalDequePeer::GetCachedIndex(&qid); EXPECT_EQ(index, i); EXPECT_EQ(it->val, i); } const int32_t index = QuicIntervalDequePeer::GetCachedIndex(&qid); EXPECT_EQ(index, -1); qid.PopFront(); EXPECT_EQ(qid.Size(), std::size_t(3)); qid.PopFront(); EXPECT_EQ(qid.Size(), std::size_t(2)); qid.PopFront(); EXPECT_EQ(qid.Size(), std::size_t(1)); qid.PopFront(); EXPECT_EQ(qid.Size(), std::size_t(0)); EXPECT_QUIC_BUG(qid.PopFront(), "Trying to pop from an empty container."); } TEST_F(QuicIntervalDequeTest, InsertIterateWhole) { const int32_t cached_index = QuicIntervalDequePeer::GetCachedIndex(&qid_); EXPECT_EQ(cached_index, 0); auto it = qid_.DataBegin(); auto end = qid_.DataEnd(); for (int32_t i = 0; i < kSize; ++i, ++it) { EXPECT_EQ(it->val, i); const std::size_t current_iteraval_begin = i * kIntervalStep; auto lookup = qid_.DataAt(current_iteraval_begin); EXPECT_EQ(i, lookup->val); const int32_t index_before = QuicIntervalDequePeer::GetCachedIndex(&qid_); EXPECT_EQ(index_before, i); lookup++; const int32_t index_after = QuicIntervalDequePeer::GetCachedIndex(&qid_); const int32_t after_i = (i + 1) == kSize ? -1 : (i + 1); EXPECT_EQ(index_after, after_i); EXPECT_NE(it, end); } } TEST_F(QuicIntervalDequeTest, OffByOne) { const int32_t cached_index = QuicIntervalDequePeer::GetCachedIndex(&qid_); EXPECT_EQ(cached_index, 0); auto it = qid_.DataBegin(); auto end = qid_.DataEnd(); for (int32_t i = 0; i < kSize - 1; ++i, ++it) { EXPECT_EQ(it->val, i); const int32_t off_by_one_i = i + 1; const std::size_t current_iteraval_begin = off_by_one_i * kIntervalStep; const int32_t index_before = QuicIntervalDequePeer::GetCachedIndex(&qid_); EXPECT_EQ(index_before, i); auto lookup = qid_.DataAt(current_iteraval_begin); EXPECT_EQ(off_by_one_i, lookup->val); const int32_t index_after = QuicIntervalDequePeer::GetCachedIndex(&qid_); const int32_t after_i = off_by_one_i == kSize ? -1 : off_by_one_i; EXPECT_EQ(index_after, after_i); EXPECT_NE(it, end); } } TEST_F(QuicIntervalDequeTest, IteratorInvalidation) { const int32_t cached_index = QuicIntervalDequePeer::GetCachedIndex(&qid_); EXPECT_EQ(cached_index, 0); const std::size_t iteraval_begin = (kSize - 1) * kIntervalStep; auto lookup = qid_.DataAt(iteraval_begin); EXPECT_EQ((*lookup).val, (kSize - 1)); qid_.PopFront(); EXPECT_QUIC_BUG(lookup++, "Iterator out of bounds."); auto lookup_end = qid_.DataAt(iteraval_begin + kIntervalStep); EXPECT_EQ(lookup_end, qid_.DataEnd()); } TEST_F(QuicIntervalDequeTest, InsertIterateSkip) { const int32_t cached_index = QuicIntervalDequePeer::GetCachedIndex(&qid_); EXPECT_EQ(cached_index, 0); const std::size_t step = 4; for (int32_t i = 0; i < kSize; i += 4) { if (i != 0) { const int32_t before_i = (i - (step - 1)); EXPECT_EQ(QuicIntervalDequePeer::GetCachedIndex(&qid_), before_i); } const std::size_t current_iteraval_begin = i * kIntervalStep; auto lookup = qid_.DataAt(current_iteraval_begin); EXPECT_EQ(i, lookup->val); const int32_t index_before = QuicIntervalDequePeer::GetCachedIndex(&qid_); EXPECT_EQ(index_before, i); lookup++; const int32_t index_after = QuicIntervalDequePeer::GetCachedIndex(&qid_); const int32_t after_i = (i + 1) == kSize ? -1 : (i + 1); EXPECT_EQ(index_after, after_i); } } TEST_F(QuicIntervalDequeTest, InsertDeleteIterate) { const int32_t index = QuicIntervalDequePeer::GetCachedIndex(&qid_); EXPECT_EQ(index, 0); std::size_t limit = 0; for (int32_t i = 0; limit < qid_.Size(); ++i, ++limit) { auto it = qid_.DataBegin(); EXPECT_EQ(it->val, i); const std::size_t current_iteraval_begin = i * kIntervalStep; auto lookup = qid_.DataAt(current_iteraval_begin); const int32_t index_before = QuicIntervalDequePeer::GetCachedIndex(&qid_); EXPECT_EQ(index_before, 0); lookup++; const int32_t index_after = QuicIntervalDequePeer::GetCachedIndex(&qid_); EXPECT_EQ(index_after, 1); qid_.PopFront(); const int32_t index_after_pop = QuicIntervalDequePeer::GetCachedIndex(&qid_); EXPECT_EQ(index_after_pop, 0); } } TEST_F(QuicIntervalDequeTest, InsertIterateInsert) { const int32_t index = QuicIntervalDequePeer::GetCachedIndex(&qid_); EXPECT_EQ(index, 0); int32_t iterated_elements = 0; for (int32_t i = 0; i < kSize; ++i, ++iterated_elements) { const std::size_t current_iteraval_begin = i * kIntervalStep; auto lookup = qid_.DataAt(current_iteraval_begin); const int32_t index_before = QuicIntervalDequePeer::GetCachedIndex(&qid_); EXPECT_EQ(index_before, i); lookup++; const int32_t index_after = QuicIntervalDequePeer::GetCachedIndex(&qid_); const int32_t after_i = (i + 1) == kSize ? -1 : (i + 1); EXPECT_EQ(index_after, after_i); } const int32_t invalid_index = QuicIntervalDequePeer::GetCachedIndex(&qid_); EXPECT_EQ(invalid_index, -1); const std::size_t offset = qid_.Size(); for (int32_t i = 0; i < kSize; ++i) { const std::size_t interval_begin = offset + (kIntervalStep * i); const std::size_t interval_end = offset + interval_begin + kIntervalStep; qid_.PushBack(TestIntervalItem(i + offset, interval_begin, interval_end)); const int32_t index_current = QuicIntervalDequePeer::GetCachedIndex(&qid_); EXPECT_EQ(index_current, iterated_elements); } const int32_t index_after_add = QuicIntervalDequePeer::GetCachedIndex(&qid_); EXPECT_EQ(index_after_add, iterated_elements); for (int32_t i = 0; i < kSize; ++i, ++iterated_elements) { const std::size_t interval_begin = offset + (kIntervalStep * i); const int32_t index_current = QuicIntervalDequePeer::GetCachedIndex(&qid_); EXPECT_EQ(index_current, iterated_elements); auto lookup = qid_.DataAt(interval_begin); const int32_t expected_value = i + offset; EXPECT_EQ(lookup->val, expected_value); lookup++; const int32_t after_inc = (iterated_elements + 1) == (kSize * 2) ? -1 : (iterated_elements + 1); const int32_t after_index = QuicIntervalDequePeer::GetCachedIndex(&qid_); EXPECT_EQ(after_index, after_inc); } const int32_t invalid_index_again = QuicIntervalDequePeer::GetCachedIndex(&qid_); EXPECT_EQ(invalid_index_again, -1); } TEST_F(QuicIntervalDequeTest, RescanData) { const int32_t index = QuicIntervalDequePeer::GetCachedIndex(&qid_); EXPECT_EQ(index, 0); auto it = qid_.DataBegin(); auto end = qid_.DataEnd(); for (int32_t i = 0; i < kSize - 1; ++i, ++it) { EXPECT_EQ(it->val, i); const std::size_t current_iteraval_begin = i * kIntervalStep; auto lookup = qid_.DataAt(current_iteraval_begin); EXPECT_EQ(i, lookup->val); const int32_t cached_index_before = QuicIntervalDequePeer::GetCachedIndex(&qid_); EXPECT_EQ(cached_index_before, i); const int32_t index_before = QuicIntervalDequePeer::GetCachedIndex(&qid_); const int32_t before_i = i; EXPECT_EQ(index_before, before_i); lookup++; const int32_t cached_index_after = QuicIntervalDequePeer::GetCachedIndex(&qid_); const int32_t after_i = (i + 1); EXPECT_EQ(cached_index_after, after_i); EXPECT_NE(it, end); } int32_t expected_index = static_cast<int32_t>(kSize - 1); for (int32_t i = 0; i < kSize - 1; ++i) { const std::size_t current_iteraval_begin = i * kIntervalStep; auto lookup = qid_.DataAt(current_iteraval_begin); EXPECT_EQ(i, lookup->val); lookup++; const int32_t index_after = QuicIntervalDequePeer::GetCachedIndex(&qid_); EXPECT_EQ(index_after, expected_index); EXPECT_NE(it, end); } } TEST_F(QuicIntervalDequeTest, PopEmpty) { QID qid; EXPECT_TRUE(qid.Empty()); EXPECT_QUIC_BUG(qid.PopFront(), "Trying to pop from an empty container."); } TEST_F(QuicIntervalDequeTest, ZeroSizedInterval) { QID qid; EXPECT_QUIC_BUG(qid.PushBack(TestIntervalItem(0, 0, 0)), "Trying to save empty interval to ."); } TEST_F(QuicIntervalDequeTest, IteratorEmpty) { QID qid; auto it = qid.DataAt(0); EXPECT_EQ(it, qid.DataEnd()); } TEST_F(QuicIntervalDequeTest, IteratorMethods) { auto it1 = qid_.DataBegin(); auto it2 = qid_.DataBegin(); EXPECT_EQ(it1, it2); EXPECT_TRUE(it1 == it2); EXPECT_FALSE(it1 != it2); EXPECT_EQ(it1++, it2); EXPECT_NE(it1, it2); EXPECT_FALSE(it1 == it2); EXPECT_TRUE(it1 != it2); it2++; EXPECT_EQ(it1, it2); EXPECT_NE(++it1, it2); it1++; it2 += 2; EXPECT_EQ(it1, it2); EXPECT_EQ(it1--, it2); EXPECT_EQ(it1, --it2); it1 += 24; it1 -= 2; it2 -= 1; it2 += 23; EXPECT_EQ(it1, it2); it1 = qid_.DataBegin(); EXPECT_QUIC_BUG(it1--, "Iterator out of bounds."); it2 = qid_.DataEnd(); EXPECT_QUIC_BUG(it2++, "Iterator out of bounds."); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_interval_deque.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_interval_deque_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
b30cea4d-4e1c-4807-9798-2c2d3ac27537
cpp
google/quiche
packet_number_indexed_queue
quiche/quic/core/packet_number_indexed_queue.h
quiche/quic/core/packet_number_indexed_queue_test.cc
#ifndef QUICHE_QUIC_CORE_PACKET_NUMBER_INDEXED_QUEUE_H_ #define QUICHE_QUIC_CORE_PACKET_NUMBER_INDEXED_QUEUE_H_ #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_packet_number.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/common/quiche_circular_deque.h" namespace quic { template <typename T> class QUICHE_NO_EXPORT PacketNumberIndexedQueue { public: PacketNumberIndexedQueue() : number_of_present_entries_(0) {} T* GetEntry(QuicPacketNumber packet_number); const T* GetEntry(QuicPacketNumber packet_number) const; template <typename... Args> bool Emplace(QuicPacketNumber packet_number, Args&&... args); bool Remove(QuicPacketNumber packet_number); template <typename Function> bool Remove(QuicPacketNumber packet_number, Function f); void RemoveUpTo(QuicPacketNumber packet_number); bool IsEmpty() const { return number_of_present_entries_ == 0; } size_t number_of_present_entries() const { return number_of_present_entries_; } size_t entry_slots_used() const { return entries_.size(); } QuicPacketNumber first_packet() const { return first_packet_; } QuicPacketNumber last_packet() const { if (IsEmpty()) { return QuicPacketNumber(); } return first_packet_ + entries_.size() - 1; } private: struct QUICHE_NO_EXPORT EntryWrapper : T { bool present; EntryWrapper() : present(false) {} template <typename... Args> explicit EntryWrapper(Args&&... args) : T(std::forward<Args>(args)...), present(true) {} }; void Cleanup(); const EntryWrapper* GetEntryWrapper(QuicPacketNumber offset) const; EntryWrapper* GetEntryWrapper(QuicPacketNumber offset) { const auto* const_this = this; return const_cast<EntryWrapper*>(const_this->GetEntryWrapper(offset)); } quiche::QuicheCircularDeque<EntryWrapper> entries_; size_t number_of_present_entries_; QuicPacketNumber first_packet_; }; template <typename T> T* PacketNumberIndexedQueue<T>::GetEntry(QuicPacketNumber packet_number) { EntryWrapper* entry = GetEntryWrapper(packet_number); if (entry == nullptr) { return nullptr; } return entry; } template <typename T> const T* PacketNumberIndexedQueue<T>::GetEntry( QuicPacketNumber packet_number) const { const EntryWrapper* entry = GetEntryWrapper(packet_number); if (entry == nullptr) { return nullptr; } return entry; } template <typename T> template <typename... Args> bool PacketNumberIndexedQueue<T>::Emplace(QuicPacketNumber packet_number, Args&&... args) { if (!packet_number.IsInitialized()) { QUIC_BUG(quic_bug_10359_1) << "Try to insert an uninitialized packet number"; return false; } if (IsEmpty()) { QUICHE_DCHECK(entries_.empty()); QUICHE_DCHECK(!first_packet_.IsInitialized()); entries_.emplace_back(std::forward<Args>(args)...); number_of_present_entries_ = 1; first_packet_ = packet_number; return true; } if (packet_number <= last_packet()) { return false; } size_t offset = packet_number - first_packet_; if (offset > entries_.size()) { entries_.resize(offset); } number_of_present_entries_++; entries_.emplace_back(std::forward<Args>(args)...); QUICHE_DCHECK_EQ(packet_number, last_packet()); return true; } template <typename T> bool PacketNumberIndexedQueue<T>::Remove(QuicPacketNumber packet_number) { return Remove(packet_number, [](const T&) {}); } template <typename T> template <typename Function> bool PacketNumberIndexedQueue<T>::Remove(QuicPacketNumber packet_number, Function f) { EntryWrapper* entry = GetEntryWrapper(packet_number); if (entry == nullptr) { return false; } f(*static_cast<const T*>(entry)); entry->present = false; number_of_present_entries_--; if (packet_number == first_packet()) { Cleanup(); } return true; } template <typename T> void PacketNumberIndexedQueue<T>::RemoveUpTo(QuicPacketNumber packet_number) { while (!entries_.empty() && first_packet_.IsInitialized() && first_packet_ < packet_number) { if (entries_.front().present) { number_of_present_entries_--; } entries_.pop_front(); first_packet_++; } Cleanup(); } template <typename T> void PacketNumberIndexedQueue<T>::Cleanup() { while (!entries_.empty() && !entries_.front().present) { entries_.pop_front(); first_packet_++; } if (entries_.empty()) { first_packet_.Clear(); } } template <typename T> auto PacketNumberIndexedQueue<T>::GetEntryWrapper( QuicPacketNumber packet_number) const -> const EntryWrapper* { if (!packet_number.IsInitialized() || IsEmpty() || packet_number < first_packet_) { return nullptr; } uint64_t offset = packet_number - first_packet_; if (offset >= entries_.size()) { return nullptr; } const EntryWrapper* entry = &entries_[offset]; if (!entry->present) { return nullptr; } return entry; } } #endif
#include "quiche/quic/core/packet_number_indexed_queue.h" #include <limits> #include <map> #include <string> #include "quiche/quic/core/quic_packet_number.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic::test { namespace { class PacketNumberIndexedQueueTest : public QuicTest { public: PacketNumberIndexedQueueTest() {} protected: PacketNumberIndexedQueue<std::string> queue_; }; TEST_F(PacketNumberIndexedQueueTest, InitialState) { EXPECT_TRUE(queue_.IsEmpty()); EXPECT_FALSE(queue_.first_packet().IsInitialized()); EXPECT_FALSE(queue_.last_packet().IsInitialized()); EXPECT_EQ(0u, queue_.number_of_present_entries()); EXPECT_EQ(0u, queue_.entry_slots_used()); } TEST_F(PacketNumberIndexedQueueTest, InsertingContinuousElements) { ASSERT_TRUE(queue_.Emplace(QuicPacketNumber(1001), "one")); EXPECT_EQ("one", *queue_.GetEntry(QuicPacketNumber(1001))); ASSERT_TRUE(queue_.Emplace(QuicPacketNumber(1002), "two")); EXPECT_EQ("two", *queue_.GetEntry(QuicPacketNumber(1002))); EXPECT_FALSE(queue_.IsEmpty()); EXPECT_EQ(QuicPacketNumber(1001u), queue_.first_packet()); EXPECT_EQ(QuicPacketNumber(1002u), queue_.last_packet()); EXPECT_EQ(2u, queue_.number_of_present_entries()); EXPECT_EQ(2u, queue_.entry_slots_used()); } TEST_F(PacketNumberIndexedQueueTest, InsertingOutOfOrder) { queue_.Emplace(QuicPacketNumber(1001), "one"); ASSERT_TRUE(queue_.Emplace(QuicPacketNumber(1003), "three")); EXPECT_EQ(nullptr, queue_.GetEntry(QuicPacketNumber(1002))); EXPECT_EQ("three", *queue_.GetEntry(QuicPacketNumber(1003))); EXPECT_EQ(QuicPacketNumber(1001u), queue_.first_packet()); EXPECT_EQ(QuicPacketNumber(1003u), queue_.last_packet()); EXPECT_EQ(2u, queue_.number_of_present_entries()); EXPECT_EQ(3u, queue_.entry_slots_used()); ASSERT_FALSE(queue_.Emplace(QuicPacketNumber(1002), "two")); } TEST_F(PacketNumberIndexedQueueTest, InsertingIntoPast) { queue_.Emplace(QuicPacketNumber(1001), "one"); EXPECT_FALSE(queue_.Emplace(QuicPacketNumber(1000), "zero")); } TEST_F(PacketNumberIndexedQueueTest, InsertingDuplicate) { queue_.Emplace(QuicPacketNumber(1001), "one"); EXPECT_FALSE(queue_.Emplace(QuicPacketNumber(1001), "one")); } TEST_F(PacketNumberIndexedQueueTest, RemoveInTheMiddle) { queue_.Emplace(QuicPacketNumber(1001), "one"); queue_.Emplace(QuicPacketNumber(1002), "two"); queue_.Emplace(QuicPacketNumber(1003), "three"); ASSERT_TRUE(queue_.Remove(QuicPacketNumber(1002))); EXPECT_EQ(nullptr, queue_.GetEntry(QuicPacketNumber(1002))); EXPECT_EQ(QuicPacketNumber(1001u), queue_.first_packet()); EXPECT_EQ(QuicPacketNumber(1003u), queue_.last_packet()); EXPECT_EQ(2u, queue_.number_of_present_entries()); EXPECT_EQ(3u, queue_.entry_slots_used()); EXPECT_FALSE(queue_.Emplace(QuicPacketNumber(1002), "two")); EXPECT_TRUE(queue_.Emplace(QuicPacketNumber(1004), "four")); } TEST_F(PacketNumberIndexedQueueTest, RemoveAtImmediateEdges) { queue_.Emplace(QuicPacketNumber(1001), "one"); queue_.Emplace(QuicPacketNumber(1002), "two"); queue_.Emplace(QuicPacketNumber(1003), "three"); ASSERT_TRUE(queue_.Remove(QuicPacketNumber(1001))); EXPECT_EQ(nullptr, queue_.GetEntry(QuicPacketNumber(1001))); ASSERT_TRUE(queue_.Remove(QuicPacketNumber(1003))); EXPECT_EQ(nullptr, queue_.GetEntry(QuicPacketNumber(1003))); EXPECT_EQ(QuicPacketNumber(1002u), queue_.first_packet()); EXPECT_EQ(QuicPacketNumber(1003u), queue_.last_packet()); EXPECT_EQ(1u, queue_.number_of_present_entries()); EXPECT_EQ(2u, queue_.entry_slots_used()); EXPECT_TRUE(queue_.Emplace(QuicPacketNumber(1004), "four")); } TEST_F(PacketNumberIndexedQueueTest, RemoveAtDistantFront) { queue_.Emplace(QuicPacketNumber(1001), "one"); queue_.Emplace(QuicPacketNumber(1002), "one (kinda)"); queue_.Emplace(QuicPacketNumber(2001), "two"); EXPECT_EQ(QuicPacketNumber(1001u), queue_.first_packet()); EXPECT_EQ(QuicPacketNumber(2001u), queue_.last_packet()); EXPECT_EQ(3u, queue_.number_of_present_entries()); EXPECT_EQ(1001u, queue_.entry_slots_used()); ASSERT_TRUE(queue_.Remove(QuicPacketNumber(1002))); EXPECT_EQ(QuicPacketNumber(1001u), queue_.first_packet()); EXPECT_EQ(QuicPacketNumber(2001u), queue_.last_packet()); EXPECT_EQ(2u, queue_.number_of_present_entries()); EXPECT_EQ(1001u, queue_.entry_slots_used()); ASSERT_TRUE(queue_.Remove(QuicPacketNumber(1001))); EXPECT_EQ(QuicPacketNumber(2001u), queue_.first_packet()); EXPECT_EQ(QuicPacketNumber(2001u), queue_.last_packet()); EXPECT_EQ(1u, queue_.number_of_present_entries()); EXPECT_EQ(1u, queue_.entry_slots_used()); } TEST_F(PacketNumberIndexedQueueTest, RemoveAtDistantBack) { queue_.Emplace(QuicPacketNumber(1001), "one"); queue_.Emplace(QuicPacketNumber(2001), "two"); EXPECT_EQ(QuicPacketNumber(1001u), queue_.first_packet()); EXPECT_EQ(QuicPacketNumber(2001u), queue_.last_packet()); ASSERT_TRUE(queue_.Remove(QuicPacketNumber(2001))); EXPECT_EQ(QuicPacketNumber(1001u), queue_.first_packet()); EXPECT_EQ(QuicPacketNumber(2001u), queue_.last_packet()); } TEST_F(PacketNumberIndexedQueueTest, ClearAndRepopulate) { queue_.Emplace(QuicPacketNumber(1001), "one"); queue_.Emplace(QuicPacketNumber(2001), "two"); ASSERT_TRUE(queue_.Remove(QuicPacketNumber(1001))); ASSERT_TRUE(queue_.Remove(QuicPacketNumber(2001))); EXPECT_TRUE(queue_.IsEmpty()); EXPECT_FALSE(queue_.first_packet().IsInitialized()); EXPECT_FALSE(queue_.last_packet().IsInitialized()); EXPECT_TRUE(queue_.Emplace(QuicPacketNumber(101), "one")); EXPECT_TRUE(queue_.Emplace(QuicPacketNumber(201), "two")); EXPECT_EQ(QuicPacketNumber(101u), queue_.first_packet()); EXPECT_EQ(QuicPacketNumber(201u), queue_.last_packet()); } TEST_F(PacketNumberIndexedQueueTest, FailToRemoveElementsThatNeverExisted) { ASSERT_FALSE(queue_.Remove(QuicPacketNumber(1000))); queue_.Emplace(QuicPacketNumber(1001), "one"); ASSERT_FALSE(queue_.Remove(QuicPacketNumber(1000))); ASSERT_FALSE(queue_.Remove(QuicPacketNumber(1002))); } TEST_F(PacketNumberIndexedQueueTest, FailToRemoveElementsTwice) { queue_.Emplace(QuicPacketNumber(1001), "one"); ASSERT_TRUE(queue_.Remove(QuicPacketNumber(1001))); ASSERT_FALSE(queue_.Remove(QuicPacketNumber(1001))); ASSERT_FALSE(queue_.Remove(QuicPacketNumber(1001))); } TEST_F(PacketNumberIndexedQueueTest, RemoveUpTo) { queue_.Emplace(QuicPacketNumber(1001), "one"); queue_.Emplace(QuicPacketNumber(2001), "two"); EXPECT_EQ(QuicPacketNumber(1001u), queue_.first_packet()); EXPECT_EQ(2u, queue_.number_of_present_entries()); queue_.RemoveUpTo(QuicPacketNumber(1001)); EXPECT_EQ(QuicPacketNumber(1001u), queue_.first_packet()); EXPECT_EQ(2u, queue_.number_of_present_entries()); queue_.RemoveUpTo(QuicPacketNumber(1100)); EXPECT_EQ(QuicPacketNumber(2001u), queue_.first_packet()); EXPECT_EQ(1u, queue_.number_of_present_entries()); queue_.RemoveUpTo(QuicPacketNumber(2001)); EXPECT_EQ(QuicPacketNumber(2001u), queue_.first_packet()); EXPECT_EQ(1u, queue_.number_of_present_entries()); queue_.RemoveUpTo(QuicPacketNumber(2002)); EXPECT_FALSE(queue_.first_packet().IsInitialized()); EXPECT_EQ(0u, queue_.number_of_present_entries()); } TEST_F(PacketNumberIndexedQueueTest, ConstGetter) { queue_.Emplace(QuicPacketNumber(1001), "one"); const auto& const_queue = queue_; EXPECT_EQ("one", *const_queue.GetEntry(QuicPacketNumber(1001))); EXPECT_EQ(nullptr, const_queue.GetEntry(QuicPacketNumber(1002))); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/packet_number_indexed_queue.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/packet_number_indexed_queue_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
f845cd84-f662-46bb-a6e6-300d4c18375b
cpp
google/quiche
quic_lru_cache
quiche/quic/core/quic_lru_cache.h
quiche/quic/core/quic_lru_cache_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_LRU_CACHE_H_ #define QUICHE_QUIC_CORE_QUIC_LRU_CACHE_H_ #include <memory> #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/common/quiche_linked_hash_map.h" namespace quic { template <class K, class V, class Hash = std::hash<K>, class Eq = std::equal_to<K>> class QUICHE_EXPORT QuicLRUCache { private: using HashMapType = typename quiche::QuicheLinkedHashMap<K, std::unique_ptr<V>, Hash, Eq>; public: using iterator = typename HashMapType::iterator; using const_iterator = typename HashMapType::const_iterator; using reverse_iterator = typename HashMapType::reverse_iterator; using const_reverse_iterator = typename HashMapType::const_reverse_iterator; explicit QuicLRUCache(size_t capacity) : capacity_(capacity) {} QuicLRUCache(const QuicLRUCache&) = delete; QuicLRUCache& operator=(const QuicLRUCache&) = delete; iterator begin() { return cache_.begin(); } const_iterator begin() const { return cache_.begin(); } iterator end() { return cache_.end(); } const_iterator end() const { return cache_.end(); } reverse_iterator rbegin() { return cache_.rbegin(); } const_reverse_iterator rbegin() const { return cache_.rbegin(); } reverse_iterator rend() { return cache_.rend(); } const_reverse_iterator rend() const { return cache_.rend(); } void Insert(const K& key, std::unique_ptr<V> value) { auto it = cache_.find(key); if (it != cache_.end()) { cache_.erase(it); } cache_.emplace(key, std::move(value)); if (cache_.size() > capacity_) { cache_.pop_front(); } QUICHE_DCHECK_LE(cache_.size(), capacity_); } iterator Lookup(const K& key) { auto iter = cache_.find(key); if (iter == cache_.end()) { return iter; } std::unique_ptr<V> value = std::move(iter->second); cache_.erase(iter); auto result = cache_.emplace(key, std::move(value)); QUICHE_DCHECK(result.second); return result.first; } iterator Erase(iterator iter) { return cache_.erase(iter); } void Clear() { cache_.clear(); } size_t MaxSize() const { return capacity_; } size_t Size() const { return cache_.size(); } private: quiche::QuicheLinkedHashMap<K, std::unique_ptr<V>, Hash, Eq> cache_; const size_t capacity_; }; } #endif
#include "quiche/quic/core/quic_lru_cache.h" #include <memory> #include <utility> #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { namespace { struct CachedItem { explicit CachedItem(uint32_t new_value) : value(new_value) {} uint32_t value; }; TEST(QuicLRUCacheTest, InsertAndLookup) { QuicLRUCache<int, CachedItem> cache(5); EXPECT_EQ(cache.end(), cache.Lookup(1)); EXPECT_EQ(0u, cache.Size()); EXPECT_EQ(5u, cache.MaxSize()); std::unique_ptr<CachedItem> item1(new CachedItem(11)); cache.Insert(1, std::move(item1)); EXPECT_EQ(1u, cache.Size()); EXPECT_EQ(11u, cache.Lookup(1)->second->value); std::unique_ptr<CachedItem> item2(new CachedItem(12)); cache.Insert(1, std::move(item2)); EXPECT_EQ(1u, cache.Size()); EXPECT_EQ(12u, cache.Lookup(1)->second->value); std::unique_ptr<CachedItem> item3(new CachedItem(13)); cache.Insert(3, std::move(item3)); EXPECT_EQ(2u, cache.Size()); auto iter = cache.Lookup(3); ASSERT_NE(cache.end(), iter); EXPECT_EQ(13u, iter->second->value); cache.Erase(iter); ASSERT_EQ(cache.end(), cache.Lookup(3)); EXPECT_EQ(1u, cache.Size()); cache.Clear(); EXPECT_EQ(0u, cache.Size()); } TEST(QuicLRUCacheTest, Eviction) { QuicLRUCache<int, CachedItem> cache(3); for (size_t i = 1; i <= 4; ++i) { std::unique_ptr<CachedItem> item(new CachedItem(10 + i)); cache.Insert(i, std::move(item)); } EXPECT_EQ(3u, cache.Size()); EXPECT_EQ(3u, cache.MaxSize()); EXPECT_EQ(cache.end(), cache.Lookup(1)); EXPECT_EQ(14u, cache.Lookup(4)->second->value); EXPECT_EQ(12u, cache.Lookup(2)->second->value); std::unique_ptr<CachedItem> item5(new CachedItem(15)); cache.Insert(5, std::move(item5)); EXPECT_EQ(cache.end(), cache.Lookup(3)); EXPECT_EQ(15u, cache.Lookup(5)->second->value); cache.Clear(); EXPECT_EQ(0u, cache.Size()); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_lru_cache.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_lru_cache_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
b2311b06-979b-4608-94cb-3cc979515934
cpp
google/quiche
quic_arena_scoped_ptr
quiche/quic/core/quic_arena_scoped_ptr.h
quiche/quic/core/quic_arena_scoped_ptr_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_ARENA_SCOPED_PTR_H_ #define QUICHE_QUIC_CORE_QUIC_ARENA_SCOPED_PTR_H_ #include <cstdint> #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { template <typename T> class QUICHE_NO_EXPORT QuicArenaScopedPtr { static_assert(alignof(T*) > 1, "QuicArenaScopedPtr can only store objects that are aligned to " "greater than 1 byte."); public: QuicArenaScopedPtr(); explicit QuicArenaScopedPtr(T* value); template <typename U> QuicArenaScopedPtr(QuicArenaScopedPtr<U>&& other); template <typename U> QuicArenaScopedPtr& operator=(QuicArenaScopedPtr<U>&& other); ~QuicArenaScopedPtr(); T* get() const; T& operator*() const; T* operator->() const; void swap(QuicArenaScopedPtr& other); void reset(T* value = nullptr); bool is_from_arena(); private: template <typename U> friend class QuicArenaScopedPtr; template <uint32_t ArenaSize> friend class QuicOneBlockArena; enum class ConstructFrom { kHeap, kArena }; QuicArenaScopedPtr(void* value, ConstructFrom from); QuicArenaScopedPtr(const QuicArenaScopedPtr&) = delete; QuicArenaScopedPtr& operator=(const QuicArenaScopedPtr&) = delete; static const uintptr_t kFromArenaMask = 0x1; void* value_; }; template <typename T> bool operator==(const QuicArenaScopedPtr<T>& left, const QuicArenaScopedPtr<T>& right) { return left.get() == right.get(); } template <typename T> bool operator!=(const QuicArenaScopedPtr<T>& left, const QuicArenaScopedPtr<T>& right) { return left.get() != right.get(); } template <typename T> bool operator==(std::nullptr_t, const QuicArenaScopedPtr<T>& right) { return nullptr == right.get(); } template <typename T> bool operator!=(std::nullptr_t, const QuicArenaScopedPtr<T>& right) { return nullptr != right.get(); } template <typename T> bool operator==(const QuicArenaScopedPtr<T>& left, std::nullptr_t) { return left.get() == nullptr; } template <typename T> bool operator!=(const QuicArenaScopedPtr<T>& left, std::nullptr_t) { return left.get() != nullptr; } template <typename T> QuicArenaScopedPtr<T>::QuicArenaScopedPtr() : value_(nullptr) {} template <typename T> QuicArenaScopedPtr<T>::QuicArenaScopedPtr(T* value) : QuicArenaScopedPtr(value, ConstructFrom::kHeap) {} template <typename T> template <typename U> QuicArenaScopedPtr<T>::QuicArenaScopedPtr(QuicArenaScopedPtr<U>&& other) : value_(other.value_) { static_assert( std::is_base_of<T, U>::value || std::is_same<T, U>::value, "Cannot construct QuicArenaScopedPtr; type is not derived or same."); other.value_ = nullptr; } template <typename T> template <typename U> QuicArenaScopedPtr<T>& QuicArenaScopedPtr<T>::operator=( QuicArenaScopedPtr<U>&& other) { static_assert( std::is_base_of<T, U>::value || std::is_same<T, U>::value, "Cannot assign QuicArenaScopedPtr; type is not derived or same."); swap(other); return *this; } template <typename T> QuicArenaScopedPtr<T>::~QuicArenaScopedPtr() { reset(); } template <typename T> T* QuicArenaScopedPtr<T>::get() const { return reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(value_) & ~kFromArenaMask); } template <typename T> T& QuicArenaScopedPtr<T>::operator*() const { return *get(); } template <typename T> T* QuicArenaScopedPtr<T>::operator->() const { return get(); } template <typename T> void QuicArenaScopedPtr<T>::swap(QuicArenaScopedPtr& other) { using std::swap; swap(value_, other.value_); } template <typename T> bool QuicArenaScopedPtr<T>::is_from_arena() { return (reinterpret_cast<uintptr_t>(value_) & kFromArenaMask) != 0; } template <typename T> void QuicArenaScopedPtr<T>::reset(T* value) { if (value_ != nullptr) { if (is_from_arena()) { get()->~T(); } else { delete get(); } } QUICHE_DCHECK_EQ(0u, reinterpret_cast<uintptr_t>(value) & kFromArenaMask); value_ = value; } template <typename T> QuicArenaScopedPtr<T>::QuicArenaScopedPtr(void* value, ConstructFrom from_arena) : value_(value) { QUICHE_DCHECK_EQ(0u, reinterpret_cast<uintptr_t>(value_) & kFromArenaMask); switch (from_arena) { case ConstructFrom::kHeap: break; case ConstructFrom::kArena: value_ = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(value_) | QuicArenaScopedPtr<T>::kFromArenaMask); break; } } } #endif
#include "quiche/quic/core/quic_arena_scoped_ptr.h" #include <string> #include <utility> #include <vector> #include "quiche/quic/core/quic_one_block_arena.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic::test { namespace { enum class TestParam { kFromHeap, kFromArena }; struct TestObject { explicit TestObject(uintptr_t value) : value(value) { buffer.resize(1024); } uintptr_t value; std::vector<char> buffer; }; std::string PrintToString(const TestParam& p) { switch (p) { case TestParam::kFromHeap: return "heap"; case TestParam::kFromArena: return "arena"; } QUICHE_DCHECK(false); return "?"; } class QuicArenaScopedPtrParamTest : public QuicTestWithParam<TestParam> { protected: QuicArenaScopedPtr<TestObject> CreateObject(uintptr_t value) { QuicArenaScopedPtr<TestObject> ptr; switch (GetParam()) { case TestParam::kFromHeap: ptr = QuicArenaScopedPtr<TestObject>(new TestObject(value)); QUICHE_CHECK(!ptr.is_from_arena()); break; case TestParam::kFromArena: ptr = arena_.New<TestObject>(value); QUICHE_CHECK(ptr.is_from_arena()); break; } return ptr; } private: QuicOneBlockArena<1024> arena_; }; INSTANTIATE_TEST_SUITE_P(QuicArenaScopedPtrParamTest, QuicArenaScopedPtrParamTest, testing::Values(TestParam::kFromHeap, TestParam::kFromArena), ::testing::PrintToStringParamName()); TEST_P(QuicArenaScopedPtrParamTest, NullObjects) { QuicArenaScopedPtr<TestObject> def; QuicArenaScopedPtr<TestObject> null(nullptr); EXPECT_EQ(def, null); EXPECT_EQ(def, nullptr); EXPECT_EQ(null, nullptr); } TEST_P(QuicArenaScopedPtrParamTest, FromArena) { QuicOneBlockArena<1024> arena_; EXPECT_TRUE(arena_.New<TestObject>(0).is_from_arena()); EXPECT_FALSE( QuicArenaScopedPtr<TestObject>(new TestObject(0)).is_from_arena()); } TEST_P(QuicArenaScopedPtrParamTest, Assign) { QuicArenaScopedPtr<TestObject> ptr = CreateObject(12345); ptr = CreateObject(54321); EXPECT_EQ(54321u, ptr->value); } TEST_P(QuicArenaScopedPtrParamTest, MoveConstruct) { QuicArenaScopedPtr<TestObject> ptr1 = CreateObject(12345); QuicArenaScopedPtr<TestObject> ptr2(std::move(ptr1)); EXPECT_EQ(nullptr, ptr1); EXPECT_EQ(12345u, ptr2->value); } TEST_P(QuicArenaScopedPtrParamTest, Accessors) { QuicArenaScopedPtr<TestObject> ptr = CreateObject(12345); EXPECT_EQ(12345u, (*ptr).value); EXPECT_EQ(12345u, ptr->value); EXPECT_EQ(12345u, ptr.get()->value); } TEST_P(QuicArenaScopedPtrParamTest, Reset) { QuicArenaScopedPtr<TestObject> ptr = CreateObject(12345); ptr.reset(new TestObject(54321)); EXPECT_EQ(54321u, ptr->value); } TEST_P(QuicArenaScopedPtrParamTest, Swap) { QuicArenaScopedPtr<TestObject> ptr1 = CreateObject(12345); QuicArenaScopedPtr<TestObject> ptr2 = CreateObject(54321); ptr1.swap(ptr2); EXPECT_EQ(12345u, ptr2->value); EXPECT_EQ(54321u, ptr1->value); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_arena_scoped_ptr.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_arena_scoped_ptr_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
8c4aaeca-b06d-4085-a531-fea704dd37b6
cpp
google/quiche
quic_one_block_arena
quiche/quic/core/quic_one_block_arena.h
quiche/quic/core/quic_one_block_arena_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_ONE_BLOCK_ARENA_H_ #define QUICHE_QUIC_CORE_QUIC_ONE_BLOCK_ARENA_H_ #include <cstdint> #include "absl/base/optimization.h" #include "quiche/quic/core/quic_arena_scoped_ptr.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { template <uint32_t ArenaSize> class QUICHE_EXPORT QuicOneBlockArena { static const uint32_t kMaxAlign = 8; public: QuicOneBlockArena() : offset_(0) {} QuicOneBlockArena(const QuicOneBlockArena&) = delete; QuicOneBlockArena& operator=(const QuicOneBlockArena&) = delete; template <typename T, typename... Args> QuicArenaScopedPtr<T> New(Args&&... args) { QUICHE_DCHECK_LT(AlignedSize<T>(), ArenaSize) << "Object is too large for the arena."; static_assert(alignof(T) > 1, "Objects added to the arena must be at least 2B aligned."); if (ABSL_PREDICT_FALSE(offset_ > ArenaSize - AlignedSize<T>())) { QUIC_BUG(quic_bug_10593_1) << "Ran out of space in QuicOneBlockArena at " << this << ", max size was " << ArenaSize << ", failing request was " << AlignedSize<T>() << ", end of arena was " << offset_; return QuicArenaScopedPtr<T>(new T(std::forward<Args>(args)...)); } void* buf = &storage_[offset_]; new (buf) T(std::forward<Args>(args)...); offset_ += AlignedSize<T>(); return QuicArenaScopedPtr<T>(buf, QuicArenaScopedPtr<T>::ConstructFrom::kArena); } private: template <typename T> static inline uint32_t AlignedSize() { return ((sizeof(T) + (kMaxAlign - 1)) / kMaxAlign) * kMaxAlign; } alignas(8) char storage_[ArenaSize]; uint32_t offset_; }; using QuicConnectionArena = QuicOneBlockArena<1380>; } #endif
#include "quiche/quic/core/quic_one_block_arena.h" #include <cstdint> #include <vector> #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic::test { namespace { static const uint32_t kMaxAlign = 8; struct TestObject { uint32_t value; }; class QuicOneBlockArenaTest : public QuicTest {}; TEST_F(QuicOneBlockArenaTest, AllocateSuccess) { QuicOneBlockArena<1024> arena; QuicArenaScopedPtr<TestObject> ptr = arena.New<TestObject>(); EXPECT_TRUE(ptr.is_from_arena()); } TEST_F(QuicOneBlockArenaTest, Exhaust) { QuicOneBlockArena<1024> arena; for (size_t i = 0; i < 1024 / kMaxAlign; ++i) { QuicArenaScopedPtr<TestObject> ptr = arena.New<TestObject>(); EXPECT_TRUE(ptr.is_from_arena()); } QuicArenaScopedPtr<TestObject> ptr; EXPECT_QUIC_BUG(ptr = arena.New<TestObject>(), "Ran out of space in QuicOneBlockArena"); EXPECT_FALSE(ptr.is_from_arena()); } TEST_F(QuicOneBlockArenaTest, NoOverlaps) { QuicOneBlockArena<1024> arena; std::vector<QuicArenaScopedPtr<TestObject>> objects; QuicIntervalSet<uintptr_t> used; for (size_t i = 0; i < 1024 / kMaxAlign; ++i) { QuicArenaScopedPtr<TestObject> ptr = arena.New<TestObject>(); EXPECT_TRUE(ptr.is_from_arena()); uintptr_t begin = reinterpret_cast<uintptr_t>(ptr.get()); uintptr_t end = begin + sizeof(TestObject); EXPECT_FALSE(used.Contains(begin)); EXPECT_FALSE(used.Contains(end - 1)); used.Add(begin, end); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_one_block_arena.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_one_block_arena_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
dcc6598e-7586-4f85-ac2b-7dd32be7be0e
cpp
google/quiche
http_frames
quiche/quic/core/http/http_frames.h
quiche/quic/core/http/http_frames_test.cc
#ifndef QUICHE_QUIC_CORE_HTTP_HTTP_FRAMES_H_ #define QUICHE_QUIC_CORE_HTTP_HTTP_FRAMES_H_ #include <algorithm> #include <cstdint> #include <map> #include <ostream> #include <sstream> #include "absl/container/flat_hash_map.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/http2/core/spdy_protocol.h" #include "quiche/quic/core/http/http_constants.h" #include "quiche/quic/core/quic_types.h" namespace quic { enum class HttpFrameType { DATA = 0x0, HEADERS = 0x1, CANCEL_PUSH = 0x3, SETTINGS = 0x4, PUSH_PROMISE = 0x5, GOAWAY = 0x7, ORIGIN = 0xC, MAX_PUSH_ID = 0xD, ACCEPT_CH = 0x89, PRIORITY_UPDATE_REQUEST_STREAM = 0xF0700, WEBTRANSPORT_STREAM = 0x41, METADATA = 0x4d, }; struct QUICHE_EXPORT DataFrame { absl::string_view data; }; struct QUICHE_EXPORT HeadersFrame { absl::string_view headers; }; using SettingsMap = absl::flat_hash_map<uint64_t, uint64_t>; struct QUICHE_EXPORT SettingsFrame { SettingsMap values; bool operator==(const SettingsFrame& rhs) const { return values == rhs.values; } std::string ToString() const { std::string s; for (auto it : values) { std::string setting = absl::StrCat( H3SettingsToString( static_cast<Http3AndQpackSettingsIdentifiers>(it.first)), " = ", it.second, "; "); absl::StrAppend(&s, setting); } return s; } friend QUICHE_EXPORT std::ostream& operator<<(std::ostream& os, const SettingsFrame& s) { os << s.ToString(); return os; } }; struct QUICHE_EXPORT GoAwayFrame { uint64_t id; bool operator==(const GoAwayFrame& rhs) const { return id == rhs.id; } }; struct QUICHE_EXPORT OriginFrame { std::vector<std::string> origins; bool operator==(const OriginFrame& rhs) const { return origins == rhs.origins; } std::string ToString() const { std::string result = "Origin Frame: {origins: "; for (const std::string& origin : origins) { absl::StrAppend(&result, "\n", origin); } result += "}"; return result; } friend QUICHE_EXPORT std::ostream& operator<<(std::ostream& os, const OriginFrame& s) { os << s.ToString(); return os; } }; inline constexpr QuicByteCount kPriorityFirstByteLength = 1; struct QUICHE_EXPORT PriorityUpdateFrame { uint64_t prioritized_element_id = 0; std::string priority_field_value; bool operator==(const PriorityUpdateFrame& rhs) const { return std::tie(prioritized_element_id, priority_field_value) == std::tie(rhs.prioritized_element_id, rhs.priority_field_value); } std::string ToString() const { return absl::StrCat( "Priority Frame : {prioritized_element_id: ", prioritized_element_id, ", priority_field_value: ", priority_field_value, "}"); } friend QUICHE_EXPORT std::ostream& operator<<(std::ostream& os, const PriorityUpdateFrame& s) { os << s.ToString(); return os; } }; struct QUICHE_EXPORT AcceptChFrame { std::vector<spdy::AcceptChOriginValuePair> entries; bool operator==(const AcceptChFrame& rhs) const { return entries.size() == rhs.entries.size() && std::equal(entries.begin(), entries.end(), rhs.entries.begin()); } std::string ToString() const { std::stringstream s; s << *this; return s.str(); } friend QUICHE_EXPORT std::ostream& operator<<(std::ostream& os, const AcceptChFrame& frame) { os << "ACCEPT_CH frame with " << frame.entries.size() << " entries: "; for (auto& entry : frame.entries) { os << "origin: " << entry.origin << "; value: " << entry.value; } return os; } }; } #endif
#include "quiche/quic/core/http/http_frames.h" #include <sstream> #include "quiche/quic/core/http/http_constants.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { TEST(HttpFramesTest, SettingsFrame) { SettingsFrame a; EXPECT_TRUE(a == a); EXPECT_EQ("", a.ToString()); SettingsFrame b; b.values[SETTINGS_QPACK_MAX_TABLE_CAPACITY] = 1; EXPECT_FALSE(a == b); EXPECT_TRUE(b == b); a.values[SETTINGS_QPACK_MAX_TABLE_CAPACITY] = 2; EXPECT_FALSE(a == b); a.values[SETTINGS_QPACK_MAX_TABLE_CAPACITY] = 1; EXPECT_TRUE(a == b); EXPECT_EQ("SETTINGS_QPACK_MAX_TABLE_CAPACITY = 1; ", b.ToString()); std::stringstream s; s << b; EXPECT_EQ("SETTINGS_QPACK_MAX_TABLE_CAPACITY = 1; ", s.str()); } TEST(HttpFramesTest, GoAwayFrame) { GoAwayFrame a{1}; EXPECT_TRUE(a == a); GoAwayFrame b{2}; EXPECT_FALSE(a == b); b.id = 1; EXPECT_TRUE(a == b); } TEST(HttpFramesTest, PriorityUpdateFrame) { PriorityUpdateFrame a{0, ""}; EXPECT_TRUE(a == a); PriorityUpdateFrame b{4, ""}; EXPECT_FALSE(a == b); a.prioritized_element_id = 4; EXPECT_TRUE(a == b); a.priority_field_value = "foo"; EXPECT_FALSE(a == b); EXPECT_EQ( "Priority Frame : {prioritized_element_id: 4, priority_field_value: foo}", a.ToString()); std::stringstream s; s << a; EXPECT_EQ( "Priority Frame : {prioritized_element_id: 4, priority_field_value: foo}", s.str()); } TEST(HttpFramesTest, AcceptChFrame) { AcceptChFrame a; EXPECT_TRUE(a == a); EXPECT_EQ("ACCEPT_CH frame with 0 entries: ", a.ToString()); AcceptChFrame b{{{"foo", "bar"}}}; EXPECT_FALSE(a == b); a.entries.push_back({"foo", "bar"}); EXPECT_TRUE(a == b); EXPECT_EQ("ACCEPT_CH frame with 1 entries: origin: foo; value: bar", a.ToString()); std::stringstream s; s << a; EXPECT_EQ("ACCEPT_CH frame with 1 entries: origin: foo; value: bar", s.str()); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/http_frames.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/http_frames_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
8bc8366f-ab31-48c6-bc7d-30c6ed6df6f4
cpp
google/quiche
windowed_filter
quiche/quic/core/congestion_control/windowed_filter.h
quiche/quic/core/congestion_control/windowed_filter_test.cc
#ifndef QUICHE_QUIC_CORE_CONGESTION_CONTROL_WINDOWED_FILTER_H_ #define QUICHE_QUIC_CORE_CONGESTION_CONTROL_WINDOWED_FILTER_H_ #include "quiche/quic/core/quic_time.h" namespace quic { template <class T> struct QUICHE_EXPORT MinFilter { bool operator()(const T& lhs, const T& rhs) const { return lhs <= rhs; } }; template <class T> struct QUICHE_EXPORT MaxFilter { bool operator()(const T& lhs, const T& rhs) const { return lhs >= rhs; } }; template <class T, class Compare, typename TimeT, typename TimeDeltaT> class QUICHE_EXPORT WindowedFilter { public: WindowedFilter(TimeDeltaT window_length, T zero_value, TimeT zero_time) : window_length_(window_length), zero_value_(zero_value), zero_time_(zero_time), estimates_{Sample(zero_value_, zero_time), Sample(zero_value_, zero_time), Sample(zero_value_, zero_time)} {} void SetWindowLength(TimeDeltaT window_length) { window_length_ = window_length; } void Update(T new_sample, TimeT new_time) { if (estimates_[0].sample == zero_value_ || Compare()(new_sample, estimates_[0].sample) || new_time - estimates_[2].time > window_length_) { Reset(new_sample, new_time); return; } if (Compare()(new_sample, estimates_[1].sample)) { estimates_[1] = Sample(new_sample, new_time); estimates_[2] = estimates_[1]; } else if (Compare()(new_sample, estimates_[2].sample)) { estimates_[2] = Sample(new_sample, new_time); } if (new_time - estimates_[0].time > window_length_) { estimates_[0] = estimates_[1]; estimates_[1] = estimates_[2]; estimates_[2] = Sample(new_sample, new_time); if (new_time - estimates_[0].time > window_length_) { estimates_[0] = estimates_[1]; estimates_[1] = estimates_[2]; } return; } if (estimates_[1].sample == estimates_[0].sample && new_time - estimates_[1].time > window_length_ >> 2) { estimates_[2] = estimates_[1] = Sample(new_sample, new_time); return; } if (estimates_[2].sample == estimates_[1].sample && new_time - estimates_[2].time > window_length_ >> 1) { estimates_[2] = Sample(new_sample, new_time); } } void Reset(T new_sample, TimeT new_time) { estimates_[0] = estimates_[1] = estimates_[2] = Sample(new_sample, new_time); } void Clear() { Reset(zero_value_, zero_time_); } T GetBest() const { return estimates_[0].sample; } T GetSecondBest() const { return estimates_[1].sample; } T GetThirdBest() const { return estimates_[2].sample; } private: struct QUICHE_EXPORT Sample { T sample; TimeT time; Sample(T init_sample, TimeT init_time) : sample(init_sample), time(init_time) {} }; TimeDeltaT window_length_; T zero_value_; TimeT zero_time_; Sample estimates_[3]; }; } #endif
#include "quiche/quic/core/congestion_control/windowed_filter.h" #include "quiche/quic/core/congestion_control/rtt_stats.h" #include "quiche/quic/core/quic_bandwidth.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { class WindowedFilterTest : public QuicTest { public: WindowedFilterTest() : windowed_min_rtt_(QuicTime::Delta::FromMilliseconds(99), QuicTime::Delta::Zero(), QuicTime::Zero()), windowed_max_bw_(QuicTime::Delta::FromMilliseconds(99), QuicBandwidth::Zero(), QuicTime::Zero()) {} void InitializeMinFilter() { QuicTime now = QuicTime::Zero(); QuicTime::Delta rtt_sample = QuicTime::Delta::FromMilliseconds(10); for (int i = 0; i < 5; ++i) { windowed_min_rtt_.Update(rtt_sample, now); QUIC_VLOG(1) << "i: " << i << " sample: " << rtt_sample.ToMilliseconds() << " mins: " << " " << windowed_min_rtt_.GetBest().ToMilliseconds() << " " << windowed_min_rtt_.GetSecondBest().ToMilliseconds() << " " << windowed_min_rtt_.GetThirdBest().ToMilliseconds(); now = now + QuicTime::Delta::FromMilliseconds(25); rtt_sample = rtt_sample + QuicTime::Delta::FromMilliseconds(10); } EXPECT_EQ(QuicTime::Delta::FromMilliseconds(20), windowed_min_rtt_.GetBest()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(40), windowed_min_rtt_.GetSecondBest()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(50), windowed_min_rtt_.GetThirdBest()); } void InitializeMaxFilter() { QuicTime now = QuicTime::Zero(); QuicBandwidth bw_sample = QuicBandwidth::FromBitsPerSecond(1000); for (int i = 0; i < 5; ++i) { windowed_max_bw_.Update(bw_sample, now); QUIC_VLOG(1) << "i: " << i << " sample: " << bw_sample.ToBitsPerSecond() << " maxs: " << " " << windowed_max_bw_.GetBest().ToBitsPerSecond() << " " << windowed_max_bw_.GetSecondBest().ToBitsPerSecond() << " " << windowed_max_bw_.GetThirdBest().ToBitsPerSecond(); now = now + QuicTime::Delta::FromMilliseconds(25); bw_sample = bw_sample - QuicBandwidth::FromBitsPerSecond(100); } EXPECT_EQ(QuicBandwidth::FromBitsPerSecond(900), windowed_max_bw_.GetBest()); EXPECT_EQ(QuicBandwidth::FromBitsPerSecond(700), windowed_max_bw_.GetSecondBest()); EXPECT_EQ(QuicBandwidth::FromBitsPerSecond(600), windowed_max_bw_.GetThirdBest()); } protected: WindowedFilter<QuicTime::Delta, MinFilter<QuicTime::Delta>, QuicTime, QuicTime::Delta> windowed_min_rtt_; WindowedFilter<QuicBandwidth, MaxFilter<QuicBandwidth>, QuicTime, QuicTime::Delta> windowed_max_bw_; }; namespace { void UpdateWithIrrelevantSamples( WindowedFilter<uint64_t, MaxFilter<uint64_t>, uint64_t, uint64_t>* filter, uint64_t max_value, uint64_t time) { for (uint64_t i = 0; i < 1000; i++) { filter->Update(i % max_value, time); } } } TEST_F(WindowedFilterTest, UninitializedEstimates) { EXPECT_EQ(QuicTime::Delta::Zero(), windowed_min_rtt_.GetBest()); EXPECT_EQ(QuicTime::Delta::Zero(), windowed_min_rtt_.GetSecondBest()); EXPECT_EQ(QuicTime::Delta::Zero(), windowed_min_rtt_.GetThirdBest()); EXPECT_EQ(QuicBandwidth::Zero(), windowed_max_bw_.GetBest()); EXPECT_EQ(QuicBandwidth::Zero(), windowed_max_bw_.GetSecondBest()); EXPECT_EQ(QuicBandwidth::Zero(), windowed_max_bw_.GetThirdBest()); } TEST_F(WindowedFilterTest, MonotonicallyIncreasingMin) { QuicTime now = QuicTime::Zero(); QuicTime::Delta rtt_sample = QuicTime::Delta::FromMilliseconds(10); windowed_min_rtt_.Update(rtt_sample, now); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), windowed_min_rtt_.GetBest()); for (int i = 0; i < 6; ++i) { now = now + QuicTime::Delta::FromMilliseconds(25); rtt_sample = rtt_sample + QuicTime::Delta::FromMilliseconds(10); windowed_min_rtt_.Update(rtt_sample, now); QUIC_VLOG(1) << "i: " << i << " sample: " << rtt_sample.ToMilliseconds() << " mins: " << " " << windowed_min_rtt_.GetBest().ToMilliseconds() << " " << windowed_min_rtt_.GetSecondBest().ToMilliseconds() << " " << windowed_min_rtt_.GetThirdBest().ToMilliseconds(); if (i < 3) { EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), windowed_min_rtt_.GetBest()); } else if (i == 3) { EXPECT_EQ(QuicTime::Delta::FromMilliseconds(20), windowed_min_rtt_.GetBest()); } else if (i < 6) { EXPECT_EQ(QuicTime::Delta::FromMilliseconds(40), windowed_min_rtt_.GetBest()); } } } TEST_F(WindowedFilterTest, MonotonicallyDecreasingMax) { QuicTime now = QuicTime::Zero(); QuicBandwidth bw_sample = QuicBandwidth::FromBitsPerSecond(1000); windowed_max_bw_.Update(bw_sample, now); EXPECT_EQ(QuicBandwidth::FromBitsPerSecond(1000), windowed_max_bw_.GetBest()); for (int i = 0; i < 6; ++i) { now = now + QuicTime::Delta::FromMilliseconds(25); bw_sample = bw_sample - QuicBandwidth::FromBitsPerSecond(100); windowed_max_bw_.Update(bw_sample, now); QUIC_VLOG(1) << "i: " << i << " sample: " << bw_sample.ToBitsPerSecond() << " maxs: " << " " << windowed_max_bw_.GetBest().ToBitsPerSecond() << " " << windowed_max_bw_.GetSecondBest().ToBitsPerSecond() << " " << windowed_max_bw_.GetThirdBest().ToBitsPerSecond(); if (i < 3) { EXPECT_EQ(QuicBandwidth::FromBitsPerSecond(1000), windowed_max_bw_.GetBest()); } else if (i == 3) { EXPECT_EQ(QuicBandwidth::FromBitsPerSecond(900), windowed_max_bw_.GetBest()); } else if (i < 6) { EXPECT_EQ(QuicBandwidth::FromBitsPerSecond(700), windowed_max_bw_.GetBest()); } } } TEST_F(WindowedFilterTest, SampleChangesThirdBestMin) { InitializeMinFilter(); QuicTime::Delta rtt_sample = windowed_min_rtt_.GetThirdBest() - QuicTime::Delta::FromMilliseconds(5); ASSERT_GT(windowed_min_rtt_.GetThirdBest(), QuicTime::Delta::FromMilliseconds(5)); QuicTime now = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(101); windowed_min_rtt_.Update(rtt_sample, now); EXPECT_EQ(rtt_sample, windowed_min_rtt_.GetThirdBest()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(40), windowed_min_rtt_.GetSecondBest()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(20), windowed_min_rtt_.GetBest()); } TEST_F(WindowedFilterTest, SampleChangesThirdBestMax) { InitializeMaxFilter(); QuicBandwidth bw_sample = windowed_max_bw_.GetThirdBest() + QuicBandwidth::FromBitsPerSecond(50); QuicTime now = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(101); windowed_max_bw_.Update(bw_sample, now); EXPECT_EQ(bw_sample, windowed_max_bw_.GetThirdBest()); EXPECT_EQ(QuicBandwidth::FromBitsPerSecond(700), windowed_max_bw_.GetSecondBest()); EXPECT_EQ(QuicBandwidth::FromBitsPerSecond(900), windowed_max_bw_.GetBest()); } TEST_F(WindowedFilterTest, SampleChangesSecondBestMin) { InitializeMinFilter(); QuicTime::Delta rtt_sample = windowed_min_rtt_.GetSecondBest() - QuicTime::Delta::FromMilliseconds(5); ASSERT_GT(windowed_min_rtt_.GetSecondBest(), QuicTime::Delta::FromMilliseconds(5)); QuicTime now = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(101); windowed_min_rtt_.Update(rtt_sample, now); EXPECT_EQ(rtt_sample, windowed_min_rtt_.GetThirdBest()); EXPECT_EQ(rtt_sample, windowed_min_rtt_.GetSecondBest()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(20), windowed_min_rtt_.GetBest()); } TEST_F(WindowedFilterTest, SampleChangesSecondBestMax) { InitializeMaxFilter(); QuicBandwidth bw_sample = windowed_max_bw_.GetSecondBest() + QuicBandwidth::FromBitsPerSecond(50); QuicTime now = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(101); windowed_max_bw_.Update(bw_sample, now); EXPECT_EQ(bw_sample, windowed_max_bw_.GetThirdBest()); EXPECT_EQ(bw_sample, windowed_max_bw_.GetSecondBest()); EXPECT_EQ(QuicBandwidth::FromBitsPerSecond(900), windowed_max_bw_.GetBest()); } TEST_F(WindowedFilterTest, SampleChangesAllMins) { InitializeMinFilter(); QuicTime::Delta rtt_sample = windowed_min_rtt_.GetBest() - QuicTime::Delta::FromMilliseconds(5); ASSERT_GT(windowed_min_rtt_.GetBest(), QuicTime::Delta::FromMilliseconds(5)); QuicTime now = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(101); windowed_min_rtt_.Update(rtt_sample, now); EXPECT_EQ(rtt_sample, windowed_min_rtt_.GetThirdBest()); EXPECT_EQ(rtt_sample, windowed_min_rtt_.GetSecondBest()); EXPECT_EQ(rtt_sample, windowed_min_rtt_.GetBest()); } TEST_F(WindowedFilterTest, SampleChangesAllMaxs) { InitializeMaxFilter(); QuicBandwidth bw_sample = windowed_max_bw_.GetBest() + QuicBandwidth::FromBitsPerSecond(50); QuicTime now = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(101); windowed_max_bw_.Update(bw_sample, now); EXPECT_EQ(bw_sample, windowed_max_bw_.GetThirdBest()); EXPECT_EQ(bw_sample, windowed_max_bw_.GetSecondBest()); EXPECT_EQ(bw_sample, windowed_max_bw_.GetBest()); } TEST_F(WindowedFilterTest, ExpireBestMin) { InitializeMinFilter(); QuicTime::Delta old_third_best = windowed_min_rtt_.GetThirdBest(); QuicTime::Delta old_second_best = windowed_min_rtt_.GetSecondBest(); QuicTime::Delta rtt_sample = old_third_best + QuicTime::Delta::FromMilliseconds(5); QuicTime now = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(125); windowed_min_rtt_.Update(rtt_sample, now); EXPECT_EQ(rtt_sample, windowed_min_rtt_.GetThirdBest()); EXPECT_EQ(old_third_best, windowed_min_rtt_.GetSecondBest()); EXPECT_EQ(old_second_best, windowed_min_rtt_.GetBest()); } TEST_F(WindowedFilterTest, ExpireBestMax) { InitializeMaxFilter(); QuicBandwidth old_third_best = windowed_max_bw_.GetThirdBest(); QuicBandwidth old_second_best = windowed_max_bw_.GetSecondBest(); QuicBandwidth bw_sample = old_third_best - QuicBandwidth::FromBitsPerSecond(50); QuicTime now = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(125); windowed_max_bw_.Update(bw_sample, now); EXPECT_EQ(bw_sample, windowed_max_bw_.GetThirdBest()); EXPECT_EQ(old_third_best, windowed_max_bw_.GetSecondBest()); EXPECT_EQ(old_second_best, windowed_max_bw_.GetBest()); } TEST_F(WindowedFilterTest, ExpireSecondBestMin) { InitializeMinFilter(); QuicTime::Delta old_third_best = windowed_min_rtt_.GetThirdBest(); QuicTime::Delta rtt_sample = old_third_best + QuicTime::Delta::FromMilliseconds(5); QuicTime now = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(175); windowed_min_rtt_.Update(rtt_sample, now); EXPECT_EQ(rtt_sample, windowed_min_rtt_.GetThirdBest()); EXPECT_EQ(rtt_sample, windowed_min_rtt_.GetSecondBest()); EXPECT_EQ(old_third_best, windowed_min_rtt_.GetBest()); } TEST_F(WindowedFilterTest, ExpireSecondBestMax) { InitializeMaxFilter(); QuicBandwidth old_third_best = windowed_max_bw_.GetThirdBest(); QuicBandwidth bw_sample = old_third_best - QuicBandwidth::FromBitsPerSecond(50); QuicTime now = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(175); windowed_max_bw_.Update(bw_sample, now); EXPECT_EQ(bw_sample, windowed_max_bw_.GetThirdBest()); EXPECT_EQ(bw_sample, windowed_max_bw_.GetSecondBest()); EXPECT_EQ(old_third_best, windowed_max_bw_.GetBest()); } TEST_F(WindowedFilterTest, ExpireAllMins) { InitializeMinFilter(); QuicTime::Delta rtt_sample = windowed_min_rtt_.GetThirdBest() + QuicTime::Delta::FromMilliseconds(5); ASSERT_LT(windowed_min_rtt_.GetThirdBest(), QuicTime::Delta::Infinite() - QuicTime::Delta::FromMilliseconds(5)); QuicTime now = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(200); windowed_min_rtt_.Update(rtt_sample, now); EXPECT_EQ(rtt_sample, windowed_min_rtt_.GetThirdBest()); EXPECT_EQ(rtt_sample, windowed_min_rtt_.GetSecondBest()); EXPECT_EQ(rtt_sample, windowed_min_rtt_.GetBest()); } TEST_F(WindowedFilterTest, ExpireAllMaxs) { InitializeMaxFilter(); QuicBandwidth bw_sample = windowed_max_bw_.GetThirdBest() - QuicBandwidth::FromBitsPerSecond(50); QuicTime now = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(200); windowed_max_bw_.Update(bw_sample, now); EXPECT_EQ(bw_sample, windowed_max_bw_.GetThirdBest()); EXPECT_EQ(bw_sample, windowed_max_bw_.GetSecondBest()); EXPECT_EQ(bw_sample, windowed_max_bw_.GetBest()); } TEST_F(WindowedFilterTest, ExpireCounterBasedMax) { WindowedFilter<uint64_t, MaxFilter<uint64_t>, uint64_t, uint64_t> max_filter( 2, 0, 0); const uint64_t kBest = 50000; max_filter.Update(50000, 1); EXPECT_EQ(kBest, max_filter.GetBest()); UpdateWithIrrelevantSamples(&max_filter, 20, 1); EXPECT_EQ(kBest, max_filter.GetBest()); max_filter.Update(40000, 2); EXPECT_EQ(kBest, max_filter.GetBest()); UpdateWithIrrelevantSamples(&max_filter, 20, 2); EXPECT_EQ(kBest, max_filter.GetBest()); max_filter.Update(30000, 3); EXPECT_EQ(kBest, max_filter.GetBest()); UpdateWithIrrelevantSamples(&max_filter, 20, 3); EXPECT_EQ(kBest, max_filter.GetBest()); QUIC_VLOG(0) << max_filter.GetSecondBest(); QUIC_VLOG(0) << max_filter.GetThirdBest(); const uint64_t kNewBest = 40000; max_filter.Update(20000, 4); EXPECT_EQ(kNewBest, max_filter.GetBest()); UpdateWithIrrelevantSamples(&max_filter, 20, 4); EXPECT_EQ(kNewBest, max_filter.GetBest()); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/congestion_control/windowed_filter.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/congestion_control/windowed_filter_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
e05e458f-6e23-4833-bf54-9723da543bec
cpp
google/quiche
moq_chat
quiche/quic/moqt/tools/moq_chat.h
quiche/quic/moqt/tools/moq_chat_test.cc
#ifndef QUICHE_QUIC_MOQT_TOOLS_MOQ_CHAT_H #define QUICHE_QUIC_MOQT_TOOLS_MOQ_CHAT_H #include <string> #include <vector> #include "absl/strings/str_cat.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "quiche/quic/moqt/moqt_messages.h" namespace moqt { class MoqChatStrings { public: explicit MoqChatStrings(absl::string_view chat_id) : chat_id_(chat_id) {} static constexpr absl::string_view kBasePath = "moq-chat"; static constexpr absl::string_view kParticipantPath = "participant"; static constexpr absl::string_view kCatalogPath = "catalog"; static constexpr absl::string_view kCatalogHeader = "version=1\n"; bool IsValidPath(absl::string_view path) const { return path == absl::StrCat("/", kBasePath); } std::string GetUsernameFromFullTrackName( FullTrackName full_track_name) const { if (full_track_name.tuple().size() != 2) { return ""; } if (!full_track_name.tuple()[1].empty()) { return ""; } std::vector<absl::string_view> elements = absl::StrSplit(full_track_name.tuple()[0], '/'); if (elements.size() != 4 || elements[0] != kBasePath || elements[1] != chat_id_ || elements[2] != kParticipantPath) { return ""; } return std::string(elements[3]); } FullTrackName GetFullTrackNameFromUsername(absl::string_view username) const { return FullTrackName{absl::StrCat(kBasePath, "/", chat_id_, "/", kParticipantPath, "/", username), ""}; } FullTrackName GetCatalogName() const { return FullTrackName{absl::StrCat(kBasePath, "/", chat_id_), absl::StrCat("/", kCatalogPath)}; } private: const std::string chat_id_; }; } #endif
#include "quiche/quic/moqt/tools/moq_chat.h" #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/common/platform/api/quiche_test.h" namespace moqt { namespace { class MoqChatStringsTest : public quiche::test::QuicheTest { public: MoqChatStrings strings_{"chat-id"}; }; TEST_F(MoqChatStringsTest, IsValidPath) { EXPECT_TRUE(strings_.IsValidPath("/moq-chat")); EXPECT_FALSE(strings_.IsValidPath("moq-chat")); EXPECT_FALSE(strings_.IsValidPath("/moq-cha")); EXPECT_FALSE(strings_.IsValidPath("/moq-chats")); EXPECT_FALSE(strings_.IsValidPath("/moq-chat/")); } TEST_F(MoqChatStringsTest, GetUsernameFromFullTrackName) { EXPECT_EQ(strings_.GetUsernameFromFullTrackName( FullTrackName{"moq-chat/chat-id/participant/user", ""}), "user"); } TEST_F(MoqChatStringsTest, GetUsernameFromFullTrackNameInvalidInput) { EXPECT_EQ(strings_.GetUsernameFromFullTrackName( FullTrackName{"/moq-chat/chat-id/participant/user", ""}), ""); EXPECT_EQ(strings_.GetUsernameFromFullTrackName( FullTrackName{"moq-chat/chat-id/participant/user/", ""}), ""); EXPECT_EQ(strings_.GetUsernameFromFullTrackName( FullTrackName{"moq-cha/chat-id/participant/user", ""}), ""); EXPECT_EQ(strings_.GetUsernameFromFullTrackName( FullTrackName{"moq-chat/chat-i/participant/user", ""}), ""); EXPECT_EQ(strings_.GetUsernameFromFullTrackName( FullTrackName{"moq-chat/chat-id/participan/user", ""}), ""); EXPECT_EQ(strings_.GetUsernameFromFullTrackName( FullTrackName{"moq-chat/chat-id/user", ""}), ""); EXPECT_EQ(strings_.GetUsernameFromFullTrackName( FullTrackName{"moq-chat/chat-id/participant/foo/user", ""}), ""); EXPECT_EQ(strings_.GetUsernameFromFullTrackName( FullTrackName{"moq-chat/chat-id/participant/user", "foo"}), ""); EXPECT_EQ(strings_.GetUsernameFromFullTrackName( FullTrackName{"moq-chat/chat-id/participant/user"}), ""); EXPECT_EQ(strings_.GetUsernameFromFullTrackName( FullTrackName{"foo", "moq-chat/chat-id/participant/user", ""}), ""); } TEST_F(MoqChatStringsTest, GetFullTrackNameFromUsername) { EXPECT_EQ(strings_.GetFullTrackNameFromUsername("user"), FullTrackName("moq-chat/chat-id/participant/user", "")); } TEST_F(MoqChatStringsTest, GetCatalogName) { EXPECT_EQ(strings_.GetCatalogName(), FullTrackName("moq-chat/chat-id", "/catalog")); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/moqt/tools/moq_chat.h
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/moqt/tools/moq_chat_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
372236e7-5a41-4764-b03d-19e31bd1286d
cpp
google/cel-cpp
branch_coverage
tools/branch_coverage.cc
tools/branch_coverage_test.cc
#include "tools/branch_coverage.h" #include <cstdint> #include <memory> #include "google/api/expr/v1alpha1/checked.pb.h" #include "absl/base/no_destructor.h" #include "absl/base/nullability.h" #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/functional/overload.h" #include "absl/status/status.h" #include "absl/synchronization/mutex.h" #include "absl/types/variant.h" #include "common/value.h" #include "eval/internal/interop.h" #include "eval/public/cel_value.h" #include "tools/navigable_ast.h" #include "google/protobuf/arena.h" namespace cel { namespace { using ::google::api::expr::v1alpha1::CheckedExpr; using ::google::api::expr::v1alpha1::Type; using ::google::api::expr::runtime::CelValue; const absl::Status& UnsupportedConversionError() { static absl::NoDestructor<absl::Status> kErr( absl::StatusCode::kInternal, "Conversion to legacy type unsupported."); return *kErr; } struct ConstantNode {}; struct BoolNode { int result_true; int result_false; int result_error; }; struct OtherNode { int result_error; }; struct CoverageNode { int evaluate_count; absl::variant<ConstantNode, OtherNode, BoolNode> kind; }; absl::Nullable<const Type*> FindCheckerType(const CheckedExpr& expr, int64_t expr_id) { if (auto it = expr.type_map().find(expr_id); it != expr.type_map().end()) { return &it->second; } return nullptr; } class BranchCoverageImpl : public BranchCoverage { public: explicit BranchCoverageImpl(const CheckedExpr& expr) : expr_(expr) {} void Record(int64_t expr_id, const Value& value) override { auto value_or = interop_internal::ToLegacyValue(&arena_, value); if (!value_or.ok()) { RecordImpl(expr_id, CelValue::CreateError(&UnsupportedConversionError())); } else { return RecordImpl(expr_id, *value_or); } } void RecordLegacyValue(int64_t expr_id, const CelValue& value) override { return RecordImpl(expr_id, value); } BranchCoverage::NodeCoverageStats StatsForNode( int64_t expr_id) const override; const NavigableAst& ast() const override; const CheckedExpr& expr() const override; void Init(); private: friend class BranchCoverage; void RecordImpl(int64_t expr_id, const CelValue& value); bool InferredBoolType(const AstNode& node) const; CheckedExpr expr_; NavigableAst ast_; mutable absl::Mutex coverage_nodes_mu_; absl::flat_hash_map<int64_t, CoverageNode> coverage_nodes_ ABSL_GUARDED_BY(coverage_nodes_mu_); absl::flat_hash_set<int64_t> unexpected_expr_ids_ ABSL_GUARDED_BY(coverage_nodes_mu_); google::protobuf::Arena arena_; }; BranchCoverage::NodeCoverageStats BranchCoverageImpl::StatsForNode( int64_t expr_id) const { BranchCoverage::NodeCoverageStats stats{ false, 0, 0, 0, 0, }; absl::MutexLock lock(&coverage_nodes_mu_); auto it = coverage_nodes_.find(expr_id); if (it != coverage_nodes_.end()) { const CoverageNode& coverage_node = it->second; stats.evaluation_count = coverage_node.evaluate_count; absl::visit(absl::Overload([&](const ConstantNode& cov) {}, [&](const OtherNode& cov) { stats.error_count = cov.result_error; }, [&](const BoolNode& cov) { stats.is_boolean = true; stats.boolean_true_count = cov.result_true; stats.boolean_false_count = cov.result_false; stats.error_count = cov.result_error; }), coverage_node.kind); return stats; } return stats; } const NavigableAst& BranchCoverageImpl::ast() const { return ast_; } const CheckedExpr& BranchCoverageImpl::expr() const { return expr_; } bool BranchCoverageImpl::InferredBoolType(const AstNode& node) const { int64_t expr_id = node.expr()->id(); const auto* checker_type = FindCheckerType(expr_, expr_id); if (checker_type != nullptr) { return checker_type->has_primitive() && checker_type->primitive() == Type::BOOL; } return false; } void BranchCoverageImpl::Init() ABSL_NO_THREAD_SAFETY_ANALYSIS { ast_ = NavigableAst::Build(expr_.expr()); for (const AstNode& node : ast_.Root().DescendantsPreorder()) { int64_t expr_id = node.expr()->id(); CoverageNode& coverage_node = coverage_nodes_[expr_id]; coverage_node.evaluate_count = 0; if (node.node_kind() == NodeKind::kConstant) { coverage_node.kind = ConstantNode{}; } else if (InferredBoolType(node)) { coverage_node.kind = BoolNode{0, 0, 0}; } else { coverage_node.kind = OtherNode{0}; } } } void BranchCoverageImpl::RecordImpl(int64_t expr_id, const CelValue& value) { absl::MutexLock lock(&coverage_nodes_mu_); auto it = coverage_nodes_.find(expr_id); if (it == coverage_nodes_.end()) { unexpected_expr_ids_.insert(expr_id); it = coverage_nodes_.insert({expr_id, CoverageNode{0, {}}}).first; if (value.IsBool()) { it->second.kind = BoolNode{0, 0, 0}; } } CoverageNode& coverage_node = it->second; coverage_node.evaluate_count++; bool is_error = value.IsError() && value.ErrorOrDie() != &UnsupportedConversionError(); absl::visit(absl::Overload([&](ConstantNode& node) {}, [&](OtherNode& cov) { if (is_error) { cov.result_error++; } }, [&](BoolNode& cov) { if (value.IsBool()) { bool held_value = value.BoolOrDie(); if (held_value) { cov.result_true++; } else { cov.result_false++; } } else if (is_error) { cov.result_error++; } }), coverage_node.kind); } } std::unique_ptr<BranchCoverage> CreateBranchCoverage(const CheckedExpr& expr) { auto result = std::make_unique<BranchCoverageImpl>(expr); result->Init(); return result; } }
#include "tools/branch_coverage.h" #include <cstdint> #include <string> #include "absl/base/no_destructor.h" #include "absl/log/absl_check.h" #include "absl/status/status.h" #include "absl/strings/substitute.h" #include "base/builtins.h" #include "base/type_provider.h" #include "common/memory.h" #include "eval/public/activation.h" #include "eval/public/builtin_func_registrar.h" #include "eval/public/cel_expr_builder_factory.h" #include "eval/public/cel_expression.h" #include "eval/public/cel_value.h" #include "internal/proto_file_util.h" #include "internal/testing.h" #include "runtime/managed_value_factory.h" #include "tools/navigable_ast.h" #include "google/protobuf/arena.h" namespace cel { namespace { using ::cel::internal::test::ReadTextProtoFromFile; using ::google::api::expr::v1alpha1::CheckedExpr; using ::google::api::expr::runtime::Activation; using ::google::api::expr::runtime::CelValue; using ::google::api::expr::runtime::CreateCelExpressionBuilder; using ::google::api::expr::runtime::RegisterBuiltinFunctions; constexpr char kCoverageExamplePath[] = "tools/testdata/coverage_example.textproto"; const CheckedExpr& TestExpression() { static absl::NoDestructor<CheckedExpr> expression([]() { CheckedExpr value; ABSL_CHECK_OK(ReadTextProtoFromFile(kCoverageExamplePath, value)); return value; }()); return *expression; } std::string FormatNodeStats(const BranchCoverage::NodeCoverageStats& stats) { return absl::Substitute( "is_bool: $0; evaluated: $1; bool_true: $2; bool_false: $3; error: $4", stats.is_boolean, stats.evaluation_count, stats.boolean_true_count, stats.boolean_false_count, stats.error_count); } google::api::expr::runtime::CelEvaluationListener EvaluationListenerForCoverage( BranchCoverage* coverage) { return [coverage](int64_t id, const CelValue& value, google::protobuf::Arena* arena) { coverage->RecordLegacyValue(id, value); return absl::OkStatus(); }; } MATCHER_P(MatchesNodeStats, expected, "") { const BranchCoverage::NodeCoverageStats& actual = arg; *result_listener << "\n"; *result_listener << "Expected: " << FormatNodeStats(expected); *result_listener << "\n"; *result_listener << "Got: " << FormatNodeStats(actual); return actual.is_boolean == expected.is_boolean && actual.evaluation_count == expected.evaluation_count && actual.boolean_true_count == expected.boolean_true_count && actual.boolean_false_count == expected.boolean_false_count && actual.error_count == expected.error_count; } MATCHER(NodeStatsIsBool, "") { const BranchCoverage::NodeCoverageStats& actual = arg; *result_listener << "\n"; *result_listener << "Expected: " << FormatNodeStats({true, 0, 0, 0, 0}); *result_listener << "\n"; *result_listener << "Got: " << FormatNodeStats(actual); return actual.is_boolean == true; } TEST(BranchCoverage, DefaultsForUntrackedId) { auto coverage = CreateBranchCoverage(TestExpression()); using Stats = BranchCoverage::NodeCoverageStats; EXPECT_THAT(coverage->StatsForNode(99), MatchesNodeStats(Stats{false, 0, 0, 0, 0})); } TEST(BranchCoverage, Record) { auto coverage = CreateBranchCoverage(TestExpression()); int64_t root_id = coverage->expr().expr().id(); cel::ManagedValueFactory factory(cel::TypeProvider::Builtin(), cel::MemoryManagerRef::ReferenceCounting()); coverage->Record(root_id, factory.get().CreateBoolValue(false)); using Stats = BranchCoverage::NodeCoverageStats; EXPECT_THAT(coverage->StatsForNode(root_id), MatchesNodeStats(Stats{true, 1, 0, 1, 0})); } TEST(BranchCoverage, RecordUnexpectedId) { auto coverage = CreateBranchCoverage(TestExpression()); int64_t unexpected_id = 99; cel::ManagedValueFactory factory(cel::TypeProvider::Builtin(), cel::MemoryManagerRef::ReferenceCounting()); coverage->Record(unexpected_id, factory.get().CreateBoolValue(false)); using Stats = BranchCoverage::NodeCoverageStats; EXPECT_THAT(coverage->StatsForNode(unexpected_id), MatchesNodeStats(Stats{true, 1, 0, 1, 0})); } TEST(BranchCoverage, IncrementsCounters) { auto coverage = CreateBranchCoverage(TestExpression()); EXPECT_TRUE(static_cast<bool>(coverage->ast())); auto builder = CreateCelExpressionBuilder(); ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry())); ASSERT_OK_AND_ASSIGN(auto program, builder->CreateExpression(&TestExpression())); google::protobuf::Arena arena; Activation activation; activation.InsertValue("bool1", CelValue::CreateBool(false)); activation.InsertValue("bool2", CelValue::CreateBool(false)); activation.InsertValue("int1", CelValue::CreateInt64(42)); activation.InsertValue("int2", CelValue::CreateInt64(43)); activation.InsertValue("int_divisor", CelValue::CreateInt64(4)); activation.InsertValue("ternary_c", CelValue::CreateBool(true)); activation.InsertValue("ternary_t", CelValue::CreateBool(true)); activation.InsertValue("ternary_f", CelValue::CreateBool(false)); ASSERT_OK_AND_ASSIGN( auto result, program->Trace(activation, &arena, EvaluationListenerForCoverage(coverage.get()))); EXPECT_TRUE(result.IsBool() && result.BoolOrDie() == true); using Stats = BranchCoverage::NodeCoverageStats; const NavigableAst& ast = coverage->ast(); auto root_node_stats = coverage->StatsForNode(ast.Root().expr()->id()); EXPECT_THAT(root_node_stats, MatchesNodeStats(Stats{true, 1, 1, 0, 0})); const AstNode* ternary; for (const auto& node : ast.Root().DescendantsPreorder()) { if (node.node_kind() == NodeKind::kCall && node.expr()->call_expr().function() == cel::builtin::kTernary) { ternary = &node; break; } } ASSERT_NE(ternary, nullptr); auto ternary_node_stats = coverage->StatsForNode(ternary->expr()->id()); EXPECT_THAT(ternary_node_stats, NodeStatsIsBool()); const auto* false_node = ternary->children().at(2); auto false_node_stats = coverage->StatsForNode(false_node->expr()->id()); EXPECT_THAT(false_node_stats, MatchesNodeStats(Stats{true, 0, 0, 0, 0})); const AstNode* not_arg_expr; for (const auto& node : ast.Root().DescendantsPreorder()) { if (node.node_kind() == NodeKind::kCall && node.expr()->call_expr().function() == cel::builtin::kNot) { not_arg_expr = node.children().at(0); break; } } ASSERT_NE(not_arg_expr, nullptr); auto not_expr_node_stats = coverage->StatsForNode(not_arg_expr->expr()->id()); EXPECT_THAT(not_expr_node_stats, MatchesNodeStats(Stats{true, 1, 0, 1, 0})); const AstNode* div_expr; for (const auto& node : ast.Root().DescendantsPreorder()) { if (node.node_kind() == NodeKind::kCall && node.expr()->call_expr().function() == cel::builtin::kDivide) { div_expr = &node; break; } } ASSERT_NE(div_expr, nullptr); auto div_expr_stats = coverage->StatsForNode(div_expr->expr()->id()); EXPECT_THAT(div_expr_stats, MatchesNodeStats(Stats{false, 1, 0, 0, 0})); } TEST(BranchCoverage, AccumulatesAcrossRuns) { auto coverage = CreateBranchCoverage(TestExpression()); EXPECT_TRUE(static_cast<bool>(coverage->ast())); auto builder = CreateCelExpressionBuilder(); ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry())); ASSERT_OK_AND_ASSIGN(auto program, builder->CreateExpression(&TestExpression())); google::protobuf::Arena arena; Activation activation; activation.InsertValue("bool1", CelValue::CreateBool(false)); activation.InsertValue("bool2", CelValue::CreateBool(false)); activation.InsertValue("int1", CelValue::CreateInt64(42)); activation.InsertValue("int2", CelValue::CreateInt64(43)); activation.InsertValue("int_divisor", CelValue::CreateInt64(4)); activation.InsertValue("ternary_c", CelValue::CreateBool(true)); activation.InsertValue("ternary_t", CelValue::CreateBool(true)); activation.InsertValue("ternary_f", CelValue::CreateBool(false)); ASSERT_OK_AND_ASSIGN( auto result, program->Trace(activation, &arena, EvaluationListenerForCoverage(coverage.get()))); EXPECT_TRUE(result.IsBool() && result.BoolOrDie() == true); activation.RemoveValueEntry("ternary_c"); activation.RemoveValueEntry("ternary_f"); activation.InsertValue("ternary_c", CelValue::CreateBool(false)); activation.InsertValue("ternary_f", CelValue::CreateBool(false)); ASSERT_OK_AND_ASSIGN( result, program->Trace(activation, &arena, EvaluationListenerForCoverage(coverage.get()))); EXPECT_TRUE(result.IsBool() && result.BoolOrDie() == false) << result.DebugString(); using Stats = BranchCoverage::NodeCoverageStats; const NavigableAst& ast = coverage->ast(); auto root_node_stats = coverage->StatsForNode(ast.Root().expr()->id()); EXPECT_THAT(root_node_stats, MatchesNodeStats(Stats{true, 2, 1, 1, 0})); const AstNode* ternary; for (const auto& node : ast.Root().DescendantsPreorder()) { if (node.node_kind() == NodeKind::kCall && node.expr()->call_expr().function() == cel::builtin::kTernary) { ternary = &node; break; } } ASSERT_NE(ternary, nullptr); auto ternary_node_stats = coverage->StatsForNode(ternary->expr()->id()); EXPECT_THAT(ternary_node_stats, NodeStatsIsBool()); const auto* false_node = ternary->children().at(2); auto false_node_stats = coverage->StatsForNode(false_node->expr()->id()); EXPECT_THAT(false_node_stats, MatchesNodeStats(Stats{true, 1, 0, 1, 0})); } TEST(BranchCoverage, CountsErrors) { auto coverage = CreateBranchCoverage(TestExpression()); EXPECT_TRUE(static_cast<bool>(coverage->ast())); auto builder = CreateCelExpressionBuilder(); ASSERT_OK(RegisterBuiltinFunctions(builder->GetRegistry())); ASSERT_OK_AND_ASSIGN(auto program, builder->CreateExpression(&TestExpression())); google::protobuf::Arena arena; Activation activation; activation.InsertValue("bool1", CelValue::CreateBool(false)); activation.InsertValue("bool2", CelValue::CreateBool(false)); activation.InsertValue("int1", CelValue::CreateInt64(42)); activation.InsertValue("int2", CelValue::CreateInt64(43)); activation.InsertValue("int_divisor", CelValue::CreateInt64(0)); activation.InsertValue("ternary_c", CelValue::CreateBool(true)); activation.InsertValue("ternary_t", CelValue::CreateBool(false)); activation.InsertValue("ternary_f", CelValue::CreateBool(false)); ASSERT_OK_AND_ASSIGN( auto result, program->Trace(activation, &arena, EvaluationListenerForCoverage(coverage.get()))); EXPECT_TRUE(result.IsBool() && result.BoolOrDie() == false); using Stats = BranchCoverage::NodeCoverageStats; const NavigableAst& ast = coverage->ast(); auto root_node_stats = coverage->StatsForNode(ast.Root().expr()->id()); EXPECT_THAT(root_node_stats, MatchesNodeStats(Stats{true, 1, 0, 1, 0})); const AstNode* ternary; for (const auto& node : ast.Root().DescendantsPreorder()) { if (node.node_kind() == NodeKind::kCall && node.expr()->call_expr().function() == cel::builtin::kTernary) { ternary = &node; break; } } const AstNode* div_expr; for (const auto& node : ast.Root().DescendantsPreorder()) { if (node.node_kind() == NodeKind::kCall && node.expr()->call_expr().function() == cel::builtin::kDivide) { div_expr = &node; break; } } ASSERT_NE(div_expr, nullptr); auto div_expr_stats = coverage->StatsForNode(div_expr->expr()->id()); EXPECT_THAT(div_expr_stats, MatchesNodeStats(Stats{false, 1, 0, 0, 1})); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/tools/branch_coverage.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/tools/branch_coverage_test.cc
4552db5798fb0853b131b783d8875794334fae7f
c6633d09-02d1-403c-bb55-c66cc9091cc7
cpp
google/cel-cpp
flatbuffers_backed_impl
tools/flatbuffers_backed_impl.cc
tools/flatbuffers_backed_impl_test.cc
#include "tools/flatbuffers_backed_impl.h" #include <algorithm> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/types/optional.h" #include "eval/public/cel_value.h" #include "flatbuffers/flatbuffers.h" namespace google { namespace api { namespace expr { namespace runtime { namespace { CelValue CreateValue(int64_t value) { return CelValue::CreateInt64(value); } CelValue CreateValue(uint64_t value) { return CelValue::CreateUint64(value); } CelValue CreateValue(double value) { return CelValue::CreateDouble(value); } CelValue CreateValue(bool value) { return CelValue::CreateBool(value); } template <typename T, typename U> class FlatBuffersListImpl : public CelList { public: FlatBuffersListImpl(const flatbuffers::Table& table, const reflection::Field& field) : list_(table.GetPointer<const flatbuffers::Vector<T>*>(field.offset())) { } int size() const override { return list_ ? list_->size() : 0; } CelValue operator[](int index) const override { return CreateValue(static_cast<U>(list_->Get(index))); } private: const flatbuffers::Vector<T>* list_; }; class StringListImpl : public CelList { public: explicit StringListImpl( const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>* list) : list_(list) {} int size() const override { return list_ ? list_->size() : 0; } CelValue operator[](int index) const override { auto value = list_->Get(index); return CelValue::CreateStringView( absl::string_view(value->c_str(), value->size())); } private: const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>* list_; }; class ObjectListImpl : public CelList { public: ObjectListImpl( const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::Table>>* list, const reflection::Schema& schema, const reflection::Object& object, google::protobuf::Arena* arena) : arena_(arena), list_(list), schema_(schema), object_(object) {} int size() const override { return list_ ? list_->size() : 0; } CelValue operator[](int index) const override { auto value = list_->Get(index); return CelValue::CreateMap(google::protobuf::Arena::Create<FlatBuffersMapImpl>( arena_, *value, schema_, object_, arena_)); } private: google::protobuf::Arena* arena_; const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::Table>>* list_; const reflection::Schema& schema_; const reflection::Object& object_; }; class ObjectStringIndexedMapImpl : public CelMap { public: ObjectStringIndexedMapImpl( const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::Table>>* list, const reflection::Schema& schema, const reflection::Object& object, const reflection::Field& index, google::protobuf::Arena* arena) : arena_(arena), list_(list), schema_(schema), object_(object), index_(index) { keys_.parent = this; } int size() const override { return list_ ? list_->size() : 0; } absl::StatusOr<bool> Has(const CelValue& key) const override { auto lookup_result = (*this)[key]; if (!lookup_result.has_value()) { return false; } auto result = *lookup_result; if (result.IsError()) { return *(result.ErrorOrDie()); } return true; } absl::optional<CelValue> operator[](CelValue cel_key) const override { if (!cel_key.IsString()) { return CreateErrorValue( arena_, absl::InvalidArgumentError( absl::StrCat("Invalid map key type: '", CelValue::TypeName(cel_key.type()), "'"))); } const absl::string_view key = cel_key.StringOrDie().value(); const auto it = std::lower_bound( list_->begin(), list_->end(), key, [this](const flatbuffers::Table* t, const absl::string_view key) { auto value = flatbuffers::GetFieldS(*t, index_); auto sv = value ? absl::string_view(value->c_str(), value->size()) : absl::string_view(); return sv < key; }); if (it != list_->end()) { auto value = flatbuffers::GetFieldS(**it, index_); auto sv = value ? absl::string_view(value->c_str(), value->size()) : absl::string_view(); if (sv == key) { return CelValue::CreateMap(google::protobuf::Arena::Create<FlatBuffersMapImpl>( arena_, **it, schema_, object_, arena_)); } } return absl::nullopt; } absl::StatusOr<const CelList*> ListKeys() const override { return &keys_; } private: struct KeyList : public CelList { int size() const override { return parent->size(); } CelValue operator[](int index) const override { auto value = flatbuffers::GetFieldS(*(parent->list_->Get(index)), parent->index_); if (value == nullptr) { return CelValue::CreateStringView(absl::string_view()); } return CelValue::CreateStringView( absl::string_view(value->c_str(), value->size())); } ObjectStringIndexedMapImpl* parent; }; google::protobuf::Arena* arena_; const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::Table>>* list_; const reflection::Schema& schema_; const reflection::Object& object_; const reflection::Field& index_; KeyList keys_; }; const reflection::Field* findStringKeyField(const reflection::Object& object) { for (const auto field : *object.fields()) { if (field->key() && field->type()->base_type() == reflection::String) { return field; } } return nullptr; } } absl::StatusOr<bool> FlatBuffersMapImpl::Has(const CelValue& key) const { auto lookup_result = (*this)[key]; if (!lookup_result.has_value()) { return false; } auto result = *lookup_result; if (result.IsError()) { return *(result.ErrorOrDie()); } return true; } absl::optional<CelValue> FlatBuffersMapImpl::operator[]( CelValue cel_key) const { if (!cel_key.IsString()) { return CreateErrorValue( arena_, absl::InvalidArgumentError( absl::StrCat("Invalid map key type: '", CelValue::TypeName(cel_key.type()), "'"))); } auto field = keys_.fields->LookupByKey(cel_key.StringOrDie().value().data()); if (field == nullptr) { return absl::nullopt; } switch (field->type()->base_type()) { case reflection::Byte: return CelValue::CreateInt64( flatbuffers::GetFieldI<int8_t>(table_, *field)); case reflection::Short: return CelValue::CreateInt64( flatbuffers::GetFieldI<int16_t>(table_, *field)); case reflection::Int: return CelValue::CreateInt64( flatbuffers::GetFieldI<int32_t>(table_, *field)); case reflection::Long: return CelValue::CreateInt64( flatbuffers::GetFieldI<int64_t>(table_, *field)); case reflection::UByte: return CelValue::CreateUint64( flatbuffers::GetFieldI<uint8_t>(table_, *field)); case reflection::UShort: return CelValue::CreateUint64( flatbuffers::GetFieldI<uint16_t>(table_, *field)); case reflection::UInt: return CelValue::CreateUint64( flatbuffers::GetFieldI<uint32_t>(table_, *field)); case reflection::ULong: return CelValue::CreateUint64( flatbuffers::GetFieldI<uint64_t>(table_, *field)); case reflection::Float: return CelValue::CreateDouble( flatbuffers::GetFieldF<float>(table_, *field)); case reflection::Double: return CelValue::CreateDouble( flatbuffers::GetFieldF<double>(table_, *field)); case reflection::Bool: return CelValue::CreateBool( flatbuffers::GetFieldI<int8_t>(table_, *field)); case reflection::String: { auto value = flatbuffers::GetFieldS(table_, *field); if (value == nullptr) { return CelValue::CreateStringView(absl::string_view()); } return CelValue::CreateStringView( absl::string_view(value->c_str(), value->size())); } case reflection::Obj: { const auto* field_schema = schema_.objects()->Get(field->type()->index()); const auto* field_table = flatbuffers::GetFieldT(table_, *field); if (field_table == nullptr) { return CelValue::CreateNull(); } if (field_schema) { return CelValue::CreateMap(google::protobuf::Arena::Create<FlatBuffersMapImpl>( arena_, *field_table, schema_, *field_schema, arena_)); } break; } case reflection::Vector: { switch (field->type()->element()) { case reflection::Byte: case reflection::UByte: { const auto* field_table = flatbuffers::GetFieldAnyV(table_, *field); if (field_table == nullptr) { return CelValue::CreateBytesView(absl::string_view()); } return CelValue::CreateBytesView(absl::string_view( reinterpret_cast<const char*>(field_table->Data()), field_table->size())); } case reflection::Short: return CelValue::CreateList( google::protobuf::Arena::Create<FlatBuffersListImpl<int16_t, int64_t>>( arena_, table_, *field)); case reflection::Int: return CelValue::CreateList( google::protobuf::Arena::Create<FlatBuffersListImpl<int32_t, int64_t>>( arena_, table_, *field)); case reflection::Long: return CelValue::CreateList( google::protobuf::Arena::Create<FlatBuffersListImpl<int64_t, int64_t>>( arena_, table_, *field)); case reflection::UShort: return CelValue::CreateList( google::protobuf::Arena::Create<FlatBuffersListImpl<uint16_t, uint64_t>>( arena_, table_, *field)); case reflection::UInt: return CelValue::CreateList( google::protobuf::Arena::Create<FlatBuffersListImpl<uint32_t, uint64_t>>( arena_, table_, *field)); case reflection::ULong: return CelValue::CreateList( google::protobuf::Arena::Create<FlatBuffersListImpl<uint64_t, uint64_t>>( arena_, table_, *field)); case reflection::Float: return CelValue::CreateList( google::protobuf::Arena::Create<FlatBuffersListImpl<float, double>>( arena_, table_, *field)); case reflection::Double: return CelValue::CreateList( google::protobuf::Arena::Create<FlatBuffersListImpl<double, double>>( arena_, table_, *field)); case reflection::Bool: return CelValue::CreateList( google::protobuf::Arena::Create<FlatBuffersListImpl<uint8_t, bool>>( arena_, table_, *field)); case reflection::String: return CelValue::CreateList(google::protobuf::Arena::Create<StringListImpl>( arena_, table_.GetPointer<const flatbuffers::Vector< flatbuffers::Offset<flatbuffers::String>>*>( field->offset()))); case reflection::Obj: { const auto* field_schema = schema_.objects()->Get(field->type()->index()); if (field_schema) { const auto* index = findStringKeyField(*field_schema); if (index) { return CelValue::CreateMap( google::protobuf::Arena::Create<ObjectStringIndexedMapImpl>( arena_, table_.GetPointer<const flatbuffers::Vector< flatbuffers::Offset<flatbuffers::Table>>*>( field->offset()), schema_, *field_schema, *index, arena_)); } else { return CelValue::CreateList(google::protobuf::Arena::Create<ObjectListImpl>( arena_, table_.GetPointer<const flatbuffers::Vector< flatbuffers::Offset<flatbuffers::Table>>*>( field->offset()), schema_, *field_schema, arena_)); } } break; } default: return absl::nullopt; } break; } default: return absl::nullopt; } return absl::nullopt; } const CelMap* CreateFlatBuffersBackedObject(const uint8_t* flatbuf, const reflection::Schema& schema, google::protobuf::Arena* arena) { return google::protobuf::Arena::Create<const FlatBuffersMapImpl>( arena, *flatbuffers::GetAnyRoot(flatbuf), schema, *schema.root_table(), arena); } } } } }
#include "tools/flatbuffers_backed_impl.h" #include <string> #include "internal/status_macros.h" #include "internal/testing.h" #include "flatbuffers/idl.h" #include "flatbuffers/reflection.h" namespace google { namespace api { namespace expr { namespace runtime { namespace { constexpr char kReflectionBufferPath[] = "tools/testdata/" "flatbuffers.bfbs"; constexpr absl::string_view kByteField = "f_byte"; constexpr absl::string_view kUbyteField = "f_ubyte"; constexpr absl::string_view kShortField = "f_short"; constexpr absl::string_view kUshortField = "f_ushort"; constexpr absl::string_view kIntField = "f_int"; constexpr absl::string_view kUintField = "f_uint"; constexpr absl::string_view kLongField = "f_long"; constexpr absl::string_view kUlongField = "f_ulong"; constexpr absl::string_view kFloatField = "f_float"; constexpr absl::string_view kDoubleField = "f_double"; constexpr absl::string_view kBoolField = "f_bool"; constexpr absl::string_view kStringField = "f_string"; constexpr absl::string_view kObjField = "f_obj"; constexpr absl::string_view kUnknownField = "f_unknown"; constexpr absl::string_view kBytesField = "r_byte"; constexpr absl::string_view kUbytesField = "r_ubyte"; constexpr absl::string_view kShortsField = "r_short"; constexpr absl::string_view kUshortsField = "r_ushort"; constexpr absl::string_view kIntsField = "r_int"; constexpr absl::string_view kUintsField = "r_uint"; constexpr absl::string_view kLongsField = "r_long"; constexpr absl::string_view kUlongsField = "r_ulong"; constexpr absl::string_view kFloatsField = "r_float"; constexpr absl::string_view kDoublesField = "r_double"; constexpr absl::string_view kBoolsField = "r_bool"; constexpr absl::string_view kStringsField = "r_string"; constexpr absl::string_view kObjsField = "r_obj"; constexpr absl::string_view kIndexedField = "r_indexed"; const int64_t kNumFields = 27; class FlatBuffersTest : public testing::Test { public: FlatBuffersTest() { EXPECT_TRUE( flatbuffers::LoadFile(kReflectionBufferPath, true, &schema_file_)); flatbuffers::Verifier verifier( reinterpret_cast<const uint8_t*>(schema_file_.data()), schema_file_.size()); EXPECT_TRUE(reflection::VerifySchemaBuffer(verifier)); EXPECT_TRUE(parser_.Deserialize( reinterpret_cast<const uint8_t*>(schema_file_.data()), schema_file_.size())); schema_ = reflection::GetSchema(schema_file_.data()); } const CelMap& loadJson(std::string data) { EXPECT_TRUE(parser_.Parse(data.data())); const CelMap* value = CreateFlatBuffersBackedObject( parser_.builder_.GetBufferPointer(), *schema_, &arena_); EXPECT_NE(nullptr, value); EXPECT_EQ(kNumFields, value->size()); const CelList* keys = value->ListKeys().value(); EXPECT_NE(nullptr, keys); EXPECT_EQ(kNumFields, keys->size()); EXPECT_TRUE((*keys)[2].IsString()); return *value; } protected: std::string schema_file_; flatbuffers::Parser parser_; const reflection::Schema* schema_; google::protobuf::Arena arena_; }; TEST_F(FlatBuffersTest, PrimitiveFields) { const CelMap& value = loadJson(R"({ f_byte: -1, f_ubyte: 1, f_short: -2, f_ushort: 2, f_int: -3, f_uint: 3, f_long: -4, f_ulong: 4, f_float: 5.0, f_double: 6.0, f_bool: false, f_string: "test" })"); { auto f = value[CelValue::CreateStringView(kByteField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsInt64()); EXPECT_EQ(-1, f->Int64OrDie()); } { auto uf = value[CelValue::CreateStringView(kUbyteField)]; EXPECT_TRUE(uf.has_value()); EXPECT_TRUE(uf->IsUint64()); EXPECT_EQ(1, uf->Uint64OrDie()); } { auto f = value[CelValue::CreateStringView(kShortField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsInt64()); EXPECT_EQ(-2, f->Int64OrDie()); } { auto uf = value[CelValue::CreateStringView(kUshortField)]; EXPECT_TRUE(uf.has_value()); EXPECT_TRUE(uf->IsUint64()); EXPECT_EQ(2, uf->Uint64OrDie()); } { auto f = value[CelValue::CreateStringView(kIntField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsInt64()); EXPECT_EQ(-3, f->Int64OrDie()); } { auto uf = value[CelValue::CreateStringView(kUintField)]; EXPECT_TRUE(uf.has_value()); EXPECT_TRUE(uf->IsUint64()); EXPECT_EQ(3, uf->Uint64OrDie()); } { auto f = value[CelValue::CreateStringView(kLongField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsInt64()); EXPECT_EQ(-4, f->Int64OrDie()); } { auto uf = value[CelValue::CreateStringView(kUlongField)]; EXPECT_TRUE(uf.has_value()); EXPECT_TRUE(uf->IsUint64()); EXPECT_EQ(4, uf->Uint64OrDie()); } { auto f = value[CelValue::CreateStringView(kFloatField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsDouble()); EXPECT_EQ(5.0, f->DoubleOrDie()); } { auto f = value[CelValue::CreateStringView(kDoubleField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsDouble()); EXPECT_EQ(6.0, f->DoubleOrDie()); } { auto f = value[CelValue::CreateStringView(kBoolField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsBool()); EXPECT_EQ(false, f->BoolOrDie()); } { auto f = value[CelValue::CreateStringView(kStringField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsString()); EXPECT_EQ("test", f->StringOrDie().value()); } { CelValue bad_field = CelValue::CreateInt64(1); auto f = value[bad_field]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsError()); auto presence = value.Has(bad_field); EXPECT_FALSE(presence.ok()); EXPECT_EQ(presence.status().code(), absl::StatusCode::kInvalidArgument); } { auto f = value[CelValue::CreateStringView(kUnknownField)]; EXPECT_FALSE(f.has_value()); } } TEST_F(FlatBuffersTest, PrimitiveFieldDefaults) { const CelMap& value = loadJson("{}"); { auto f = value[CelValue::CreateStringView(kByteField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsInt64()); EXPECT_EQ(0, f->Int64OrDie()); } { auto f = value[CelValue::CreateStringView(kShortField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsInt64()); EXPECT_EQ(150, f->Int64OrDie()); } { auto f = value[CelValue::CreateStringView(kBoolField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsBool()); EXPECT_EQ(true, f->BoolOrDie()); } { auto f = value[CelValue::CreateStringView(kStringField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsString()); EXPECT_EQ("", f->StringOrDie().value()); } } TEST_F(FlatBuffersTest, ObjectField) { const CelMap& value = loadJson(R"({ f_obj: { f_string: "entry", f_int: 16 } })"); CelValue field = CelValue::CreateStringView(kObjField); auto presence = value.Has(field); EXPECT_OK(presence); EXPECT_TRUE(*presence); auto f = value[field]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsMap()); const CelMap& m = *f->MapOrDie(); EXPECT_EQ(2, m.size()); { auto obj_field = CelValue::CreateStringView(kStringField); auto member_presence = m.Has(obj_field); EXPECT_OK(member_presence); EXPECT_TRUE(*member_presence); auto mf = m[obj_field]; EXPECT_TRUE(mf.has_value()); EXPECT_TRUE(mf->IsString()); EXPECT_EQ("entry", mf->StringOrDie().value()); } { auto obj_field = CelValue::CreateStringView(kIntField); auto member_presence = m.Has(obj_field); EXPECT_OK(member_presence); EXPECT_TRUE(*member_presence); auto mf = m[obj_field]; EXPECT_TRUE(mf.has_value()); EXPECT_TRUE(mf->IsInt64()); EXPECT_EQ(16, mf->Int64OrDie()); } { std::string undefined = "f_undefined"; CelValue undefined_field = CelValue::CreateStringView(undefined); auto presence = m.Has(undefined_field); EXPECT_OK(presence); EXPECT_FALSE(*presence); auto v = m[undefined_field]; EXPECT_FALSE(v.has_value()); presence = m.Has(CelValue::CreateBool(false)); EXPECT_FALSE(presence.ok()); EXPECT_EQ(presence.status().code(), absl::StatusCode::kInvalidArgument); } } TEST_F(FlatBuffersTest, ObjectFieldDefault) { const CelMap& value = loadJson("{}"); auto f = value[CelValue::CreateStringView(kObjField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsNull()); } TEST_F(FlatBuffersTest, PrimitiveVectorFields) { const CelMap& value = loadJson(R"({ r_byte: [-97], r_ubyte: [97, 98, 99], r_short: [-2], r_ushort: [2], r_int: [-3], r_uint: [3], r_long: [-4], r_ulong: [4], r_float: [5.0], r_double: [6.0], r_bool: [false], r_string: ["test"] })"); { auto f = value[CelValue::CreateStringView(kBytesField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsBytes()); EXPECT_EQ("\x9F", f->BytesOrDie().value()); } { auto uf = value[CelValue::CreateStringView(kUbytesField)]; EXPECT_TRUE(uf.has_value()); EXPECT_TRUE(uf->IsBytes()); EXPECT_EQ("abc", uf->BytesOrDie().value()); } { auto f = value[CelValue::CreateStringView(kShortsField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsList()); const CelList& l = *f->ListOrDie(); EXPECT_EQ(1, l.size()); EXPECT_EQ(-2, l[0].Int64OrDie()); } { auto uf = value[CelValue::CreateStringView(kUshortsField)]; EXPECT_TRUE(uf.has_value()); EXPECT_TRUE(uf->IsList()); const CelList& l = *uf->ListOrDie(); EXPECT_EQ(1, l.size()); EXPECT_EQ(2, l[0].Uint64OrDie()); } { auto f = value[CelValue::CreateStringView(kIntsField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsList()); const CelList& l = *f->ListOrDie(); EXPECT_EQ(1, l.size()); EXPECT_EQ(-3, l[0].Int64OrDie()); } { auto uf = value[CelValue::CreateStringView(kUintsField)]; EXPECT_TRUE(uf.has_value()); EXPECT_TRUE(uf->IsList()); const CelList& l = *uf->ListOrDie(); EXPECT_EQ(1, l.size()); EXPECT_EQ(3, l[0].Uint64OrDie()); } { auto f = value[CelValue::CreateStringView(kLongsField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsList()); const CelList& l = *f->ListOrDie(); EXPECT_EQ(1, l.size()); EXPECT_EQ(-4, l[0].Int64OrDie()); } { auto uf = value[CelValue::CreateStringView(kUlongsField)]; EXPECT_TRUE(uf.has_value()); EXPECT_TRUE(uf->IsList()); const CelList& l = *uf->ListOrDie(); EXPECT_EQ(1, l.size()); EXPECT_EQ(4, l[0].Uint64OrDie()); } { auto f = value[CelValue::CreateStringView(kFloatsField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsList()); const CelList& l = *f->ListOrDie(); EXPECT_EQ(1, l.size()); EXPECT_EQ(5.0, l[0].DoubleOrDie()); } { auto f = value[CelValue::CreateStringView(kDoublesField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsList()); const CelList& l = *f->ListOrDie(); EXPECT_EQ(1, l.size()); EXPECT_EQ(6.0, l[0].DoubleOrDie()); } { auto f = value[CelValue::CreateStringView(kBoolsField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsList()); const CelList& l = *f->ListOrDie(); EXPECT_EQ(1, l.size()); EXPECT_EQ(false, l[0].BoolOrDie()); } { auto f = value[CelValue::CreateStringView(kStringsField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsList()); const CelList& l = *f->ListOrDie(); EXPECT_EQ(1, l.size()); EXPECT_EQ("test", l[0].StringOrDie().value()); } } TEST_F(FlatBuffersTest, ObjectVectorField) { const CelMap& value = loadJson(R"({ r_obj: [{ f_string: "entry", f_int: 16 },{ f_int: 32 }] })"); auto f = value[CelValue::CreateStringView(kObjsField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsList()); const CelList& l = *f->ListOrDie(); EXPECT_EQ(2, l.size()); { EXPECT_TRUE(l[0].IsMap()); const CelMap& m = *l[0].MapOrDie(); EXPECT_EQ(2, m.size()); { CelValue field = CelValue::CreateStringView(kStringField); auto presence = m.Has(field); EXPECT_OK(presence); EXPECT_TRUE(*presence); auto mf = m[field]; EXPECT_TRUE(mf.has_value()); EXPECT_TRUE(mf->IsString()); EXPECT_EQ("entry", mf->StringOrDie().value()); } { CelValue field = CelValue::CreateStringView(kIntField); auto presence = m.Has(field); EXPECT_OK(presence); EXPECT_TRUE(*presence); auto mf = m[field]; EXPECT_TRUE(mf.has_value()); EXPECT_TRUE(mf->IsInt64()); EXPECT_EQ(16, mf->Int64OrDie()); } } { EXPECT_TRUE(l[1].IsMap()); const CelMap& m = *l[1].MapOrDie(); EXPECT_EQ(2, m.size()); { CelValue field = CelValue::CreateStringView(kStringField); auto presence = m.Has(field); EXPECT_OK(presence); EXPECT_TRUE(*presence); auto mf = m[field]; EXPECT_TRUE(mf.has_value()); EXPECT_TRUE(mf->IsString()); EXPECT_EQ("", mf->StringOrDie().value()); } { CelValue field = CelValue::CreateStringView(kIntField); auto presence = m.Has(field); EXPECT_OK(presence); EXPECT_TRUE(*presence); auto mf = m[field]; EXPECT_TRUE(mf.has_value()); EXPECT_TRUE(mf->IsInt64()); EXPECT_EQ(32, mf->Int64OrDie()); } { std::string undefined = "f_undefined"; CelValue field = CelValue::CreateStringView(undefined); auto presence = m.Has(field); EXPECT_OK(presence); EXPECT_FALSE(*presence); auto mf = m[field]; EXPECT_FALSE(mf.has_value()); } } } TEST_F(FlatBuffersTest, VectorFieldDefaults) { const CelMap& value = loadJson("{}"); for (const auto field : std::vector<absl::string_view>{ kIntsField, kBoolsField, kStringsField, kObjsField}) { auto f = value[CelValue::CreateStringView(field)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsList()); const CelList& l = *f->ListOrDie(); EXPECT_EQ(0, l.size()); } { auto f = value[CelValue::CreateStringView(kIndexedField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsMap()); const CelMap& m = *f->MapOrDie(); EXPECT_EQ(0, m.size()); EXPECT_EQ(0, (*m.ListKeys())->size()); } { auto f = value[CelValue::CreateStringView(kBytesField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsBytes()); EXPECT_EQ("", f->BytesOrDie().value()); } } TEST_F(FlatBuffersTest, IndexedObjectVectorField) { const CelMap& value = loadJson(R"({ r_indexed: [ { f_string: "a", f_int: 16 }, { f_string: "b", f_int: 32 }, { f_string: "c", f_int: 64 }, { f_string: "d", f_int: 128 } ] })"); auto f = value[CelValue::CreateStringView(kIndexedField)]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsMap()); const CelMap& m = *f->MapOrDie(); EXPECT_EQ(4, m.size()); const CelList& l = *m.ListKeys().value(); EXPECT_EQ(4, l.size()); EXPECT_TRUE(l[0].IsString()); EXPECT_TRUE(l[1].IsString()); EXPECT_TRUE(l[2].IsString()); EXPECT_TRUE(l[3].IsString()); std::string a = "a"; std::string b = "b"; std::string c = "c"; std::string d = "d"; EXPECT_EQ(a, l[0].StringOrDie().value()); EXPECT_EQ(b, l[1].StringOrDie().value()); EXPECT_EQ(c, l[2].StringOrDie().value()); EXPECT_EQ(d, l[3].StringOrDie().value()); for (const std::string& key : std::vector<std::string>{a, b, c, d}) { auto v = m[CelValue::CreateString(&key)]; EXPECT_TRUE(v.has_value()); const CelMap& vm = *v->MapOrDie(); EXPECT_EQ(2, vm.size()); auto vf = vm[CelValue::CreateStringView(kStringField)]; EXPECT_TRUE(vf.has_value()); EXPECT_TRUE(vf->IsString()); EXPECT_EQ(key, vf->StringOrDie().value()); auto vi = vm[CelValue::CreateStringView(kIntField)]; EXPECT_TRUE(vi.has_value()); EXPECT_TRUE(vi->IsInt64()); } { std::string bb = "bb"; std::string dd = "dd"; EXPECT_FALSE(m[CelValue::CreateString(&bb)].has_value()); EXPECT_FALSE(m[CelValue::CreateString(&dd)].has_value()); EXPECT_FALSE( m[CelValue::CreateStringView(absl::string_view())].has_value()); } } TEST_F(FlatBuffersTest, IndexedObjectVectorFieldDefaults) { const CelMap& value = loadJson(R"({ r_indexed: [ { f_string: "", f_int: 16 } ] })"); CelValue field = CelValue::CreateStringView(kIndexedField); auto presence = value.Has(field); EXPECT_OK(presence); EXPECT_TRUE(*presence); auto f = value[field]; EXPECT_TRUE(f.has_value()); EXPECT_TRUE(f->IsMap()); const CelMap& m = *f->MapOrDie(); EXPECT_EQ(1, m.size()); const CelList& l = *m.ListKeys().value(); EXPECT_EQ(1, l.size()); EXPECT_TRUE(l[0].IsString()); EXPECT_EQ("", l[0].StringOrDie().value()); CelValue map_field = CelValue::CreateStringView(absl::string_view()); presence = m.Has(map_field); EXPECT_OK(presence); EXPECT_TRUE(*presence); auto v = m[map_field]; EXPECT_TRUE(v.has_value()); std::string undefined = "f_undefined"; CelValue undefined_field = CelValue::CreateStringView(undefined); presence = m.Has(undefined_field); EXPECT_OK(presence); EXPECT_FALSE(*presence); v = m[undefined_field]; EXPECT_FALSE(v.has_value()); presence = m.Has(CelValue::CreateBool(false)); EXPECT_FALSE(presence.ok()); EXPECT_EQ(presence.status().code(), absl::StatusCode::kInvalidArgument); } } } } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/tools/flatbuffers_backed_impl.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/tools/flatbuffers_backed_impl_test.cc
4552db5798fb0853b131b783d8875794334fae7f
45a0f00c-97a3-4a6b-a58a-8ad1ecc2fa36
cpp
google/cel-cpp
navigable_ast
tools/navigable_ast.cc
tools/navigable_ast_test.cc
#include "tools/navigable_ast.h" #include <cstddef> #include <memory> #include <string> #include <utility> #include <vector> #include "google/api/expr/v1alpha1/checked.pb.h" #include "absl/container/flat_hash_map.h" #include "absl/log/absl_check.h" #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "absl/types/span.h" #include "eval/public/ast_traverse.h" #include "eval/public/ast_visitor.h" #include "eval/public/ast_visitor_base.h" #include "eval/public/source_position.h" namespace cel { namespace tools_internal { AstNodeData& AstMetadata::NodeDataAt(size_t index) { ABSL_CHECK(index < nodes.size()); return nodes[index]->data_; } size_t AstMetadata::AddNode() { size_t index = nodes.size(); nodes.push_back(absl::WrapUnique(new AstNode())); return index; } } namespace { using google::api::expr::v1alpha1::Expr; using google::api::expr::runtime::AstTraverse; using google::api::expr::runtime::SourcePosition; NodeKind GetNodeKind(const Expr& expr) { switch (expr.expr_kind_case()) { case Expr::kConstExpr: return NodeKind::kConstant; case Expr::kIdentExpr: return NodeKind::kIdent; case Expr::kSelectExpr: return NodeKind::kSelect; case Expr::kCallExpr: return NodeKind::kCall; case Expr::kListExpr: return NodeKind::kList; case Expr::kStructExpr: if (!expr.struct_expr().message_name().empty()) { return NodeKind::kStruct; } else { return NodeKind::kMap; } case Expr::kComprehensionExpr: return NodeKind::kComprehension; case Expr::EXPR_KIND_NOT_SET: default: return NodeKind::kUnspecified; } } ChildKind GetChildKind(const tools_internal::AstNodeData& parent_node, size_t child_index) { constexpr size_t kComprehensionRangeArgIndex = google::api::expr::runtime::ITER_RANGE; constexpr size_t kComprehensionInitArgIndex = google::api::expr::runtime::ACCU_INIT; constexpr size_t kComprehensionConditionArgIndex = google::api::expr::runtime::LOOP_CONDITION; constexpr size_t kComprehensionLoopStepArgIndex = google::api::expr::runtime::LOOP_STEP; constexpr size_t kComprehensionResultArgIndex = google::api::expr::runtime::RESULT; switch (parent_node.node_kind) { case NodeKind::kStruct: return ChildKind::kStructValue; case NodeKind::kMap: if (child_index % 2 == 0) { return ChildKind::kMapKey; } return ChildKind::kMapValue; case NodeKind::kList: return ChildKind::kListElem; case NodeKind::kSelect: return ChildKind::kSelectOperand; case NodeKind::kCall: if (child_index == 0 && parent_node.expr->call_expr().has_target()) { return ChildKind::kCallReceiver; } return ChildKind::kCallArg; case NodeKind::kComprehension: switch (child_index) { case kComprehensionRangeArgIndex: return ChildKind::kComprehensionRange; case kComprehensionInitArgIndex: return ChildKind::kComprehensionInit; case kComprehensionConditionArgIndex: return ChildKind::kComprehensionCondition; case kComprehensionLoopStepArgIndex: return ChildKind::kComprehensionLoopStep; case kComprehensionResultArgIndex: return ChildKind::kComprensionResult; default: return ChildKind::kUnspecified; } default: return ChildKind::kUnspecified; } } class NavigableExprBuilderVisitor : public google::api::expr::runtime::AstVisitorBase { public: NavigableExprBuilderVisitor() : metadata_(std::make_unique<tools_internal::AstMetadata>()) {} void PreVisitExpr(const Expr* expr, const SourcePosition* position) override { AstNode* parent = parent_stack_.empty() ? nullptr : metadata_->nodes[parent_stack_.back()].get(); size_t index = metadata_->AddNode(); tools_internal::AstNodeData& node_data = metadata_->NodeDataAt(index); node_data.parent = parent; node_data.expr = expr; node_data.parent_relation = ChildKind::kUnspecified; node_data.node_kind = GetNodeKind(*expr); node_data.weight = 1; node_data.index = index; node_data.metadata = metadata_.get(); metadata_->id_to_node.insert({expr->id(), index}); metadata_->expr_to_node.insert({expr, index}); if (!parent_stack_.empty()) { auto& parent_node_data = metadata_->NodeDataAt(parent_stack_.back()); size_t child_index = parent_node_data.children.size(); parent_node_data.children.push_back(metadata_->nodes[index].get()); node_data.parent_relation = GetChildKind(parent_node_data, child_index); } parent_stack_.push_back(index); } void PostVisitExpr(const Expr* expr, const SourcePosition* position) override { size_t idx = parent_stack_.back(); parent_stack_.pop_back(); metadata_->postorder.push_back(metadata_->nodes[idx].get()); tools_internal::AstNodeData& node = metadata_->NodeDataAt(idx); if (!parent_stack_.empty()) { tools_internal::AstNodeData& parent_node_data = metadata_->NodeDataAt(parent_stack_.back()); parent_node_data.weight += node.weight; } } std::unique_ptr<tools_internal::AstMetadata> Consume() && { return std::move(metadata_); } private: std::unique_ptr<tools_internal::AstMetadata> metadata_; std::vector<size_t> parent_stack_; }; } std::string ChildKindName(ChildKind kind) { switch (kind) { case ChildKind::kUnspecified: return "Unspecified"; case ChildKind::kSelectOperand: return "SelectOperand"; case ChildKind::kCallReceiver: return "CallReceiver"; case ChildKind::kCallArg: return "CallArg"; case ChildKind::kListElem: return "ListElem"; case ChildKind::kMapKey: return "MapKey"; case ChildKind::kMapValue: return "MapValue"; case ChildKind::kStructValue: return "StructValue"; case ChildKind::kComprehensionRange: return "ComprehensionRange"; case ChildKind::kComprehensionInit: return "ComprehensionInit"; case ChildKind::kComprehensionCondition: return "ComprehensionCondition"; case ChildKind::kComprehensionLoopStep: return "ComprehensionLoopStep"; case ChildKind::kComprensionResult: return "ComprehensionResult"; default: return absl::StrCat("Unknown ChildKind ", static_cast<int>(kind)); } } std::string NodeKindName(NodeKind kind) { switch (kind) { case NodeKind::kUnspecified: return "Unspecified"; case NodeKind::kConstant: return "Constant"; case NodeKind::kIdent: return "Ident"; case NodeKind::kSelect: return "Select"; case NodeKind::kCall: return "Call"; case NodeKind::kList: return "List"; case NodeKind::kMap: return "Map"; case NodeKind::kStruct: return "Struct"; case NodeKind::kComprehension: return "Comprehension"; default: return absl::StrCat("Unknown NodeKind ", static_cast<int>(kind)); } } int AstNode::child_index() const { if (data_.parent == nullptr) { return -1; } int i = 0; for (const AstNode* ptr : data_.parent->children()) { if (ptr->expr() == expr()) { return i; } i++; } return -1; } AstNode::PreorderRange AstNode::DescendantsPreorder() const { return AstNode::PreorderRange(absl::MakeConstSpan(data_.metadata->nodes) .subspan(data_.index, data_.weight)); } AstNode::PostorderRange AstNode::DescendantsPostorder() const { return AstNode::PostorderRange(absl::MakeConstSpan(data_.metadata->postorder) .subspan(data_.index, data_.weight)); } NavigableAst NavigableAst::Build(const Expr& expr) { NavigableExprBuilderVisitor visitor; AstTraverse(&expr, nullptr, &visitor); return NavigableAst(std::move(visitor).Consume()); } }
#include "tools/navigable_ast.h" #include <utility> #include <vector> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/base/casts.h" #include "absl/strings/str_cat.h" #include "base/builtins.h" #include "internal/testing.h" #include "parser/parser.h" namespace cel { namespace { using ::google::api::expr::v1alpha1::Expr; using ::google::api::expr::parser::Parse; using ::testing::ElementsAre; using ::testing::IsEmpty; using ::testing::Pair; using ::testing::SizeIs; TEST(NavigableAst, Basic) { Expr const_node; const_node.set_id(1); const_node.mutable_const_expr()->set_int64_value(42); NavigableAst ast = NavigableAst::Build(const_node); EXPECT_TRUE(ast.IdsAreUnique()); const AstNode& root = ast.Root(); EXPECT_EQ(root.expr(), &const_node); EXPECT_THAT(root.children(), IsEmpty()); EXPECT_TRUE(root.parent() == nullptr); EXPECT_EQ(root.child_index(), -1); EXPECT_EQ(root.node_kind(), NodeKind::kConstant); EXPECT_EQ(root.parent_relation(), ChildKind::kUnspecified); } TEST(NavigableAst, DefaultCtorEmpty) { Expr const_node; const_node.set_id(1); const_node.mutable_const_expr()->set_int64_value(42); NavigableAst ast = NavigableAst::Build(const_node); EXPECT_EQ(ast, ast); NavigableAst empty; EXPECT_NE(ast, empty); EXPECT_EQ(empty, empty); EXPECT_TRUE(static_cast<bool>(ast)); EXPECT_FALSE(static_cast<bool>(empty)); NavigableAst moved = std::move(ast); EXPECT_EQ(ast, empty); EXPECT_FALSE(static_cast<bool>(ast)); EXPECT_TRUE(static_cast<bool>(moved)); } TEST(NavigableAst, FindById) { Expr const_node; const_node.set_id(1); const_node.mutable_const_expr()->set_int64_value(42); NavigableAst ast = NavigableAst::Build(const_node); const AstNode& root = ast.Root(); EXPECT_EQ(ast.FindId(const_node.id()), &root); EXPECT_EQ(ast.FindId(-1), nullptr); } MATCHER_P(AstNodeWrapping, expr, "") { const AstNode* ptr = arg; return ptr != nullptr && ptr->expr() == expr; } TEST(NavigableAst, ToleratesNonUnique) { Expr call_node; call_node.set_id(1); call_node.mutable_call_expr()->set_function(cel::builtin::kNot); Expr* const_node = call_node.mutable_call_expr()->add_args(); const_node->mutable_const_expr()->set_bool_value(false); const_node->set_id(1); NavigableAst ast = NavigableAst::Build(call_node); const AstNode& root = ast.Root(); EXPECT_EQ(ast.FindId(1), &root); EXPECT_EQ(ast.FindExpr(&call_node), &root); EXPECT_FALSE(ast.IdsAreUnique()); EXPECT_THAT(ast.FindExpr(const_node), AstNodeWrapping(const_node)); } TEST(NavigableAst, FindByExprPtr) { Expr const_node; const_node.set_id(1); const_node.mutable_const_expr()->set_int64_value(42); NavigableAst ast = NavigableAst::Build(const_node); const AstNode& root = ast.Root(); EXPECT_EQ(ast.FindExpr(&const_node), &root); EXPECT_EQ(ast.FindExpr(&Expr::default_instance()), nullptr); } TEST(NavigableAst, Children) { ASSERT_OK_AND_ASSIGN(auto parsed_expr, Parse("1 + 2")); NavigableAst ast = NavigableAst::Build(parsed_expr.expr()); const AstNode& root = ast.Root(); EXPECT_EQ(root.expr(), &parsed_expr.expr()); EXPECT_THAT(root.children(), SizeIs(2)); EXPECT_TRUE(root.parent() == nullptr); EXPECT_EQ(root.child_index(), -1); EXPECT_EQ(root.parent_relation(), ChildKind::kUnspecified); EXPECT_EQ(root.node_kind(), NodeKind::kCall); EXPECT_THAT( root.children(), ElementsAre(AstNodeWrapping(&parsed_expr.expr().call_expr().args(0)), AstNodeWrapping(&parsed_expr.expr().call_expr().args(1)))); ASSERT_THAT(root.children(), SizeIs(2)); const auto* child1 = root.children()[0]; EXPECT_EQ(child1->child_index(), 0); EXPECT_EQ(child1->parent(), &root); EXPECT_EQ(child1->parent_relation(), ChildKind::kCallArg); EXPECT_EQ(child1->node_kind(), NodeKind::kConstant); EXPECT_THAT(child1->children(), IsEmpty()); const auto* child2 = root.children()[1]; EXPECT_EQ(child2->child_index(), 1); } TEST(NavigableAst, UnspecifiedExpr) { Expr expr; expr.set_id(1); NavigableAst ast = NavigableAst::Build(expr); const AstNode& root = ast.Root(); EXPECT_EQ(root.expr(), &expr); EXPECT_THAT(root.children(), SizeIs(0)); EXPECT_TRUE(root.parent() == nullptr); EXPECT_EQ(root.child_index(), -1); EXPECT_EQ(root.node_kind(), NodeKind::kUnspecified); } TEST(NavigableAst, ParentRelationSelect) { ASSERT_OK_AND_ASSIGN(auto parsed_expr, Parse("a.b")); NavigableAst ast = NavigableAst::Build(parsed_expr.expr()); const AstNode& root = ast.Root(); ASSERT_THAT(root.children(), SizeIs(1)); const auto* child = root.children()[0]; EXPECT_EQ(child->parent_relation(), ChildKind::kSelectOperand); EXPECT_EQ(child->node_kind(), NodeKind::kIdent); } TEST(NavigableAst, ParentRelationCallReceiver) { ASSERT_OK_AND_ASSIGN(auto parsed_expr, Parse("a.b()")); NavigableAst ast = NavigableAst::Build(parsed_expr.expr()); const AstNode& root = ast.Root(); ASSERT_THAT(root.children(), SizeIs(1)); const auto* child = root.children()[0]; EXPECT_EQ(child->parent_relation(), ChildKind::kCallReceiver); EXPECT_EQ(child->node_kind(), NodeKind::kIdent); } TEST(NavigableAst, ParentRelationCreateStruct) { ASSERT_OK_AND_ASSIGN(auto parsed_expr, Parse("com.example.Type{field: '123'}")); NavigableAst ast = NavigableAst::Build(parsed_expr.expr()); const AstNode& root = ast.Root(); EXPECT_EQ(root.node_kind(), NodeKind::kStruct); ASSERT_THAT(root.children(), SizeIs(1)); const auto* child = root.children()[0]; EXPECT_EQ(child->parent_relation(), ChildKind::kStructValue); EXPECT_EQ(child->node_kind(), NodeKind::kConstant); } TEST(NavigableAst, ParentRelationCreateMap) { ASSERT_OK_AND_ASSIGN(auto parsed_expr, Parse("{'a': 123}")); NavigableAst ast = NavigableAst::Build(parsed_expr.expr()); const AstNode& root = ast.Root(); EXPECT_EQ(root.node_kind(), NodeKind::kMap); ASSERT_THAT(root.children(), SizeIs(2)); const auto* key = root.children()[0]; const auto* value = root.children()[1]; EXPECT_EQ(key->parent_relation(), ChildKind::kMapKey); EXPECT_EQ(key->node_kind(), NodeKind::kConstant); EXPECT_EQ(value->parent_relation(), ChildKind::kMapValue); EXPECT_EQ(value->node_kind(), NodeKind::kConstant); } TEST(NavigableAst, ParentRelationCreateList) { ASSERT_OK_AND_ASSIGN(auto parsed_expr, Parse("[123]")); NavigableAst ast = NavigableAst::Build(parsed_expr.expr()); const AstNode& root = ast.Root(); EXPECT_EQ(root.node_kind(), NodeKind::kList); ASSERT_THAT(root.children(), SizeIs(1)); const auto* child = root.children()[0]; EXPECT_EQ(child->parent_relation(), ChildKind::kListElem); EXPECT_EQ(child->node_kind(), NodeKind::kConstant); } TEST(NavigableAst, ParentRelationComprehension) { ASSERT_OK_AND_ASSIGN(auto parsed_expr, Parse("[1].all(x, x < 2)")); NavigableAst ast = NavigableAst::Build(parsed_expr.expr()); const AstNode& root = ast.Root(); EXPECT_EQ(root.node_kind(), NodeKind::kComprehension); ASSERT_THAT(root.children(), SizeIs(5)); const auto* range = root.children()[0]; const auto* init = root.children()[1]; const auto* condition = root.children()[2]; const auto* step = root.children()[3]; const auto* finish = root.children()[4]; EXPECT_EQ(range->parent_relation(), ChildKind::kComprehensionRange); EXPECT_EQ(init->parent_relation(), ChildKind::kComprehensionInit); EXPECT_EQ(condition->parent_relation(), ChildKind::kComprehensionCondition); EXPECT_EQ(step->parent_relation(), ChildKind::kComprehensionLoopStep); EXPECT_EQ(finish->parent_relation(), ChildKind::kComprensionResult); } TEST(NavigableAst, DescendantsPostorder) { ASSERT_OK_AND_ASSIGN(auto parsed_expr, Parse("1 + (x * 3)")); NavigableAst ast = NavigableAst::Build(parsed_expr.expr()); const AstNode& root = ast.Root(); EXPECT_EQ(root.node_kind(), NodeKind::kCall); std::vector<int> constants; std::vector<NodeKind> node_kinds; for (const AstNode& node : root.DescendantsPostorder()) { if (node.node_kind() == NodeKind::kConstant) { constants.push_back(node.expr()->const_expr().int64_value()); } node_kinds.push_back(node.node_kind()); } EXPECT_THAT(node_kinds, ElementsAre(NodeKind::kConstant, NodeKind::kIdent, NodeKind::kConstant, NodeKind::kCall, NodeKind::kCall)); EXPECT_THAT(constants, ElementsAre(1, 3)); } TEST(NavigableAst, DescendantsPreorder) { ASSERT_OK_AND_ASSIGN(auto parsed_expr, Parse("1 + (x * 3)")); NavigableAst ast = NavigableAst::Build(parsed_expr.expr()); const AstNode& root = ast.Root(); EXPECT_EQ(root.node_kind(), NodeKind::kCall); std::vector<int> constants; std::vector<NodeKind> node_kinds; for (const AstNode& node : root.DescendantsPreorder()) { if (node.node_kind() == NodeKind::kConstant) { constants.push_back(node.expr()->const_expr().int64_value()); } node_kinds.push_back(node.node_kind()); } EXPECT_THAT(node_kinds, ElementsAre(NodeKind::kCall, NodeKind::kConstant, NodeKind::kCall, NodeKind::kIdent, NodeKind::kConstant)); EXPECT_THAT(constants, ElementsAre(1, 3)); } TEST(NavigableAst, DescendantsPreorderComprehension) { ASSERT_OK_AND_ASSIGN(auto parsed_expr, Parse("[1, 2, 3].map(x, x + 1)")); NavigableAst ast = NavigableAst::Build(parsed_expr.expr()); const AstNode& root = ast.Root(); EXPECT_EQ(root.node_kind(), NodeKind::kComprehension); std::vector<std::pair<NodeKind, ChildKind>> node_kinds; for (const AstNode& node : root.DescendantsPreorder()) { node_kinds.push_back( std::make_pair(node.node_kind(), node.parent_relation())); } EXPECT_THAT( node_kinds, ElementsAre(Pair(NodeKind::kComprehension, ChildKind::kUnspecified), Pair(NodeKind::kList, ChildKind::kComprehensionRange), Pair(NodeKind::kConstant, ChildKind::kListElem), Pair(NodeKind::kConstant, ChildKind::kListElem), Pair(NodeKind::kConstant, ChildKind::kListElem), Pair(NodeKind::kList, ChildKind::kComprehensionInit), Pair(NodeKind::kConstant, ChildKind::kComprehensionCondition), Pair(NodeKind::kCall, ChildKind::kComprehensionLoopStep), Pair(NodeKind::kIdent, ChildKind::kCallArg), Pair(NodeKind::kList, ChildKind::kCallArg), Pair(NodeKind::kCall, ChildKind::kListElem), Pair(NodeKind::kIdent, ChildKind::kCallArg), Pair(NodeKind::kConstant, ChildKind::kCallArg), Pair(NodeKind::kIdent, ChildKind::kComprensionResult))); } TEST(NavigableAst, DescendantsPreorderCreateMap) { ASSERT_OK_AND_ASSIGN(auto parsed_expr, Parse("{'key1': 1, 'key2': 2}")); NavigableAst ast = NavigableAst::Build(parsed_expr.expr()); const AstNode& root = ast.Root(); EXPECT_EQ(root.node_kind(), NodeKind::kMap); std::vector<std::pair<NodeKind, ChildKind>> node_kinds; for (const AstNode& node : root.DescendantsPreorder()) { node_kinds.push_back( std::make_pair(node.node_kind(), node.parent_relation())); } EXPECT_THAT(node_kinds, ElementsAre(Pair(NodeKind::kMap, ChildKind::kUnspecified), Pair(NodeKind::kConstant, ChildKind::kMapKey), Pair(NodeKind::kConstant, ChildKind::kMapValue), Pair(NodeKind::kConstant, ChildKind::kMapKey), Pair(NodeKind::kConstant, ChildKind::kMapValue))); } TEST(NodeKind, Stringify) { EXPECT_EQ(absl::StrCat(NodeKind::kConstant), "Constant"); EXPECT_EQ(absl::StrCat(NodeKind::kIdent), "Ident"); EXPECT_EQ(absl::StrCat(NodeKind::kSelect), "Select"); EXPECT_EQ(absl::StrCat(NodeKind::kCall), "Call"); EXPECT_EQ(absl::StrCat(NodeKind::kList), "List"); EXPECT_EQ(absl::StrCat(NodeKind::kMap), "Map"); EXPECT_EQ(absl::StrCat(NodeKind::kStruct), "Struct"); EXPECT_EQ(absl::StrCat(NodeKind::kComprehension), "Comprehension"); EXPECT_EQ(absl::StrCat(NodeKind::kUnspecified), "Unspecified"); EXPECT_EQ(absl::StrCat(absl::bit_cast<NodeKind>(255)), "Unknown NodeKind 255"); } TEST(ChildKind, Stringify) { EXPECT_EQ(absl::StrCat(ChildKind::kSelectOperand), "SelectOperand"); EXPECT_EQ(absl::StrCat(ChildKind::kCallReceiver), "CallReceiver"); EXPECT_EQ(absl::StrCat(ChildKind::kCallArg), "CallArg"); EXPECT_EQ(absl::StrCat(ChildKind::kListElem), "ListElem"); EXPECT_EQ(absl::StrCat(ChildKind::kMapKey), "MapKey"); EXPECT_EQ(absl::StrCat(ChildKind::kMapValue), "MapValue"); EXPECT_EQ(absl::StrCat(ChildKind::kStructValue), "StructValue"); EXPECT_EQ(absl::StrCat(ChildKind::kComprehensionRange), "ComprehensionRange"); EXPECT_EQ(absl::StrCat(ChildKind::kComprehensionInit), "ComprehensionInit"); EXPECT_EQ(absl::StrCat(ChildKind::kComprehensionCondition), "ComprehensionCondition"); EXPECT_EQ(absl::StrCat(ChildKind::kComprehensionLoopStep), "ComprehensionLoopStep"); EXPECT_EQ(absl::StrCat(ChildKind::kComprensionResult), "ComprehensionResult"); EXPECT_EQ(absl::StrCat(ChildKind::kUnspecified), "Unspecified"); EXPECT_EQ(absl::StrCat(absl::bit_cast<ChildKind>(255)), "Unknown ChildKind 255"); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/tools/navigable_ast.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/tools/navigable_ast_test.cc
4552db5798fb0853b131b783d8875794334fae7f
ffc07e61-07c7-4b48-aa1e-c9a582db6910
cpp
google/cel-cpp
standard_library
checker/standard_library.cc
checker/standard_library_test.cc
#include "checker/standard_library.h" #include <string> #include <utility> #include "absl/base/no_destructor.h" #include "absl/status/status.h" #include "base/builtins.h" #include "checker/internal/builtins_arena.h" #include "checker/type_checker_builder.h" #include "common/constant.h" #include "common/decl.h" #include "common/type.h" #include "internal/status_macros.h" namespace cel { namespace { using ::cel::checker_internal::BuiltinsArena; TypeParamType TypeParamA() { return TypeParamType("A"); } TypeParamType TypeParamB() { return TypeParamType("B"); } Type ListOfA() { static absl::NoDestructor<Type> kInstance( ListType(BuiltinsArena(), TypeParamA())); return *kInstance; } Type MapOfAB() { static absl::NoDestructor<Type> kInstance( MapType(BuiltinsArena(), TypeParamA(), TypeParamB())); return *kInstance; } Type TypeOfA() { static absl::NoDestructor<Type> kInstance( TypeType(BuiltinsArena(), TypeParamA())); return *kInstance; } Type TypeNullType() { static absl::NoDestructor<Type> kInstance( TypeType(BuiltinsArena(), NullType())); return *kInstance; } Type TypeBoolType() { static absl::NoDestructor<Type> kInstance( TypeType(BuiltinsArena(), BoolType())); return *kInstance; } Type TypeIntType() { static absl::NoDestructor<Type> kInstance( TypeType(BuiltinsArena(), IntType())); return *kInstance; } Type TypeUintType() { static absl::NoDestructor<Type> kInstance( TypeType(BuiltinsArena(), UintType())); return *kInstance; } Type TypeDoubleType() { static absl::NoDestructor<Type> kInstance( TypeType(BuiltinsArena(), DoubleType())); return *kInstance; } Type TypeStringType() { static absl::NoDestructor<Type> kInstance( TypeType(BuiltinsArena(), StringType())); return *kInstance; } Type TypeBytesType() { static absl::NoDestructor<Type> kInstance( TypeType(BuiltinsArena(), BytesType())); return *kInstance; } Type TypeDurationType() { static absl::NoDestructor<Type> kInstance( TypeType(BuiltinsArena(), DurationType())); return *kInstance; } Type TypeTimestampType() { static absl::NoDestructor<Type> kInstance( TypeType(BuiltinsArena(), TimestampType())); return *kInstance; } Type TypeListType() { static absl::NoDestructor<Type> kInstance( TypeType(BuiltinsArena(), ListOfA())); return *kInstance; } Type TypeMapType() { static absl::NoDestructor<Type> kInstance( TypeType(BuiltinsArena(), MapOfAB())); return *kInstance; } class StandardOverloads { public: static constexpr char kAddInt[] = "add_int64"; static constexpr char kAddUint[] = "add_uint64"; static constexpr char kAddDouble[] = "add_double"; static constexpr char kAddDurationDuration[] = "add_duration_duration"; static constexpr char kAddDurationTimestamp[] = "add_duration_timestamp"; static constexpr char kAddTimestampDuration[] = "add_timestamp_duration"; static constexpr char kAddString[] = "add_string"; static constexpr char kAddBytes[] = "add_bytes"; static constexpr char kAddList[] = "add_list"; static constexpr char kSubtractInt[] = "subtract_int64"; static constexpr char kSubtractUint[] = "subtract_uint64"; static constexpr char kSubtractDouble[] = "subtract_double"; static constexpr char kSubtractDurationDuration[] = "subtract_duration_duration"; static constexpr char kSubtractTimestampDuration[] = "subtract_timestamp_duration"; static constexpr char kSubtractTimestampTimestamp[] = "subtract_timestamp_timestamp"; static constexpr char kMultiplyInt[] = "multiply_int64"; static constexpr char kMultiplyUint[] = "multiply_uint64"; static constexpr char kMultiplyDouble[] = "multiply_double"; static constexpr char kDivideInt[] = "divide_int64"; static constexpr char kDivideUint[] = "divide_uint64"; static constexpr char kDivideDouble[] = "divide_double"; static constexpr char kModuloInt[] = "modulo_int64"; static constexpr char kModuloUint[] = "modulo_uint64"; static constexpr char kNegateInt[] = "negate_int64"; static constexpr char kNegateDouble[] = "negate_double"; static constexpr char kNot[] = "logical_not"; static constexpr char kAnd[] = "logical_and"; static constexpr char kOr[] = "logical_or"; static constexpr char kConditional[] = "conditional"; static constexpr char kNotStrictlyFalse[] = "not_strictly_false"; static constexpr char kNotStrictlyFalseDeprecated[] = "__not_strictly_false__"; static constexpr char kEquals[] = "equals"; static constexpr char kNotEquals[] = "not_equals"; static constexpr char kLessBool[] = "less_bool"; static constexpr char kLessString[] = "less_string"; static constexpr char kLessBytes[] = "less_bytes"; static constexpr char kLessDuration[] = "less_duration"; static constexpr char kLessTimestamp[] = "less_timestamp"; static constexpr char kLessInt[] = "less_int64"; static constexpr char kLessIntUint[] = "less_int64_uint64"; static constexpr char kLessIntDouble[] = "less_int64_double"; static constexpr char kLessDouble[] = "less_double"; static constexpr char kLessDoubleInt[] = "less_double_int64"; static constexpr char kLessDoubleUint[] = "less_double_uint64"; static constexpr char kLessUint[] = "less_uint64"; static constexpr char kLessUintInt[] = "less_uint64_int64"; static constexpr char kLessUintDouble[] = "less_uint64_double"; static constexpr char kGreaterBool[] = "greater_bool"; static constexpr char kGreaterString[] = "greater_string"; static constexpr char kGreaterBytes[] = "greater_bytes"; static constexpr char kGreaterDuration[] = "greater_duration"; static constexpr char kGreaterTimestamp[] = "greater_timestamp"; static constexpr char kGreaterInt[] = "greater_int64"; static constexpr char kGreaterIntUint[] = "greater_int64_uint64"; static constexpr char kGreaterIntDouble[] = "greater_int64_double"; static constexpr char kGreaterDouble[] = "greater_double"; static constexpr char kGreaterDoubleInt[] = "greater_double_int64"; static constexpr char kGreaterDoubleUint[] = "greater_double_uint64"; static constexpr char kGreaterUint[] = "greater_uint64"; static constexpr char kGreaterUintInt[] = "greater_uint64_int64"; static constexpr char kGreaterUintDouble[] = "greater_uint64_double"; static constexpr char kGreaterEqualsBool[] = "greater_equals_bool"; static constexpr char kGreaterEqualsString[] = "greater_equals_string"; static constexpr char kGreaterEqualsBytes[] = "greater_equals_bytes"; static constexpr char kGreaterEqualsDuration[] = "greater_equals_duration"; static constexpr char kGreaterEqualsTimestamp[] = "greater_equals_timestamp"; static constexpr char kGreaterEqualsInt[] = "greater_equals_int64"; static constexpr char kGreaterEqualsIntUint[] = "greater_equals_int64_uint64"; static constexpr char kGreaterEqualsIntDouble[] = "greater_equals_int64_double"; static constexpr char kGreaterEqualsDouble[] = "greater_equals_double"; static constexpr char kGreaterEqualsDoubleInt[] = "greater_equals_double_int64"; static constexpr char kGreaterEqualsDoubleUint[] = "greater_equals_double_uint64"; static constexpr char kGreaterEqualsUint[] = "greater_equals_uint64"; static constexpr char kGreaterEqualsUintInt[] = "greater_equals_uint64_int64"; static constexpr char kGreaterEqualsUintDouble[] = "greater_equals_uint_double"; static constexpr char kLessEqualsBool[] = "less_equals_bool"; static constexpr char kLessEqualsString[] = "less_equals_string"; static constexpr char kLessEqualsBytes[] = "less_equals_bytes"; static constexpr char kLessEqualsDuration[] = "less_equals_duration"; static constexpr char kLessEqualsTimestamp[] = "less_equals_timestamp"; static constexpr char kLessEqualsInt[] = "less_equals_int64"; static constexpr char kLessEqualsIntUint[] = "less_equals_int64_uint64"; static constexpr char kLessEqualsIntDouble[] = "less_equals_int64_double"; static constexpr char kLessEqualsDouble[] = "less_equals_double"; static constexpr char kLessEqualsDoubleInt[] = "less_equals_double_int64"; static constexpr char kLessEqualsDoubleUint[] = "less_equals_double_uint64"; static constexpr char kLessEqualsUint[] = "less_equals_uint64"; static constexpr char kLessEqualsUintInt[] = "less_equals_uint64_int64"; static constexpr char kLessEqualsUintDouble[] = "less_equals_uint64_double"; static constexpr char kIndexList[] = "index_list"; static constexpr char kIndexMap[] = "index_map"; static constexpr char kInList[] = "in_list"; static constexpr char kInMap[] = "in_map"; static constexpr char kSizeBytes[] = "size_bytes"; static constexpr char kSizeList[] = "size_list"; static constexpr char kSizeMap[] = "size_map"; static constexpr char kSizeString[] = "size_string"; static constexpr char kSizeBytesMember[] = "bytes_size"; static constexpr char kSizeListMember[] = "list_size"; static constexpr char kSizeMapMember[] = "map_size"; static constexpr char kSizeStringMember[] = "string_size"; static constexpr char kContainsString[] = "contains_string"; static constexpr char kEndsWithString[] = "ends_with_string"; static constexpr char kStartsWithString[] = "starts_with_string"; static constexpr char kMatches[] = "matches"; static constexpr char kMatchesMember[] = "matches_string"; static constexpr char kTimestampToYear[] = "timestamp_to_year"; static constexpr char kTimestampToYearWithTz[] = "timestamp_to_year_with_tz"; static constexpr char kTimestampToMonth[] = "timestamp_to_month"; static constexpr char kTimestampToMonthWithTz[] = "timestamp_to_month_with_tz"; static constexpr char kTimestampToDayOfYear[] = "timestamp_to_day_of_year"; static constexpr char kTimestampToDayOfYearWithTz[] = "timestamp_to_day_of_year_with_tz"; static constexpr char kTimestampToDayOfMonth[] = "timestamp_to_day_of_month"; static constexpr char kTimestampToDayOfMonthWithTz[] = "timestamp_to_day_of_month_with_tz"; static constexpr char kTimestampToDayOfWeek[] = "timestamp_to_day_of_week"; static constexpr char kTimestampToDayOfWeekWithTz[] = "timestamp_to_day_of_week_with_tz"; static constexpr char kTimestampToDate[] = "timestamp_to_day_of_month_1_based"; static constexpr char kTimestampToDateWithTz[] = "timestamp_to_day_of_month_1_based_with_tz"; static constexpr char kTimestampToHours[] = "timestamp_to_hours"; static constexpr char kTimestampToHoursWithTz[] = "timestamp_to_hours_with_tz"; static constexpr char kDurationToHours[] = "duration_to_hours"; static constexpr char kTimestampToMinutes[] = "timestamp_to_minutes"; static constexpr char kTimestampToMinutesWithTz[] = "timestamp_to_minutes_with_tz"; static constexpr char kDurationToMinutes[] = "duration_to_minutes"; static constexpr char kTimestampToSeconds[] = "timestamp_to_seconds"; static constexpr char kTimestampToSecondsWithTz[] = "timestamp_to_seconds_tz"; static constexpr char kDurationToSeconds[] = "duration_to_seconds"; static constexpr char kTimestampToMilliseconds[] = "timestamp_to_milliseconds"; static constexpr char kTimestampToMillisecondsWithTz[] = "timestamp_to_milliseconds_with_tz"; static constexpr char kDurationToMilliseconds[] = "duration_to_milliseconds"; static constexpr char kToDyn[] = "to_dyn"; static constexpr char kUintToUint[] = "uint64_to_uint64"; static constexpr char kDoubleToUint[] = "double_to_uint64"; static constexpr char kIntToUint[] = "int64_to_uint64"; static constexpr char kStringToUint[] = "string_to_uint64"; static constexpr char kUintToInt[] = "uint64_to_int64"; static constexpr char kDoubleToInt[] = "double_to_int64"; static constexpr char kIntToInt[] = "int64_to_int64"; static constexpr char kStringToInt[] = "string_to_int64"; static constexpr char kTimestampToInt[] = "timestamp_to_int64"; static constexpr char kDurationToInt[] = "duration_to_int64"; static constexpr char kDoubleToDouble[] = "double_to_double"; static constexpr char kUintToDouble[] = "uint64_to_double"; static constexpr char kIntToDouble[] = "int64_to_double"; static constexpr char kStringToDouble[] = "string_to_double"; static constexpr char kBoolToBool[] = "bool_to_bool"; static constexpr char kStringToBool[] = "string_to_bool"; static constexpr char kBytesToBytes[] = "bytes_to_bytes"; static constexpr char kStringToBytes[] = "string_to_bytes"; static constexpr char kStringToString[] = "string_to_string"; static constexpr char kBytesToString[] = "bytes_to_string"; static constexpr char kBoolToString[] = "bool_to_string"; static constexpr char kDoubleToString[] = "double_to_string"; static constexpr char kIntToString[] = "int64_to_string"; static constexpr char kUintToString[] = "uint64_to_string"; static constexpr char kDurationToString[] = "duration_to_string"; static constexpr char kTimestampToString[] = "timestamp_to_string"; static constexpr char kTimestampToTimestamp[] = "timestamp_to_timestamp"; static constexpr char kIntToTimestamp[] = "int64_to_timestamp"; static constexpr char kStringToTimestamp[] = "string_to_timestamp"; static constexpr char kDurationToDuration[] = "duration_to_duration"; static constexpr char kIntToDuration[] = "int64_to_duration"; static constexpr char kStringToDuration[] = "string_to_duration"; static constexpr char kToType[] = "type"; }; absl::Status AddArithmeticOps(TypeCheckerBuilder& builder) { FunctionDecl add_op; add_op.set_name(builtin::kAdd); CEL_RETURN_IF_ERROR(add_op.AddOverload(MakeOverloadDecl( StandardOverloads::kAddInt, IntType(), IntType(), IntType()))); CEL_RETURN_IF_ERROR(add_op.AddOverload( MakeOverloadDecl(StandardOverloads::kAddDouble, DoubleType(), DoubleType(), DoubleType()))); CEL_RETURN_IF_ERROR(add_op.AddOverload(MakeOverloadDecl( StandardOverloads::kAddUint, UintType(), UintType(), UintType()))); CEL_RETURN_IF_ERROR(add_op.AddOverload( MakeOverloadDecl(StandardOverloads::kAddDurationDuration, DurationType(), DurationType(), DurationType()))); CEL_RETURN_IF_ERROR(add_op.AddOverload( MakeOverloadDecl(StandardOverloads::kAddDurationTimestamp, TimestampType(), DurationType(), TimestampType()))); CEL_RETURN_IF_ERROR(add_op.AddOverload( MakeOverloadDecl(StandardOverloads::kAddTimestampDuration, TimestampType(), TimestampType(), DurationType()))); CEL_RETURN_IF_ERROR(add_op.AddOverload(MakeOverloadDecl( StandardOverloads::kAddBytes, BytesType(), BytesType(), BytesType()))); CEL_RETURN_IF_ERROR(add_op.AddOverload( MakeOverloadDecl(StandardOverloads::kAddString, StringType(), StringType(), StringType()))); CEL_RETURN_IF_ERROR(add_op.AddOverload(MakeOverloadDecl( StandardOverloads::kAddList, ListOfA(), ListOfA(), ListOfA()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(add_op))); FunctionDecl subtract_op; subtract_op.set_name(builtin::kSubtract); CEL_RETURN_IF_ERROR(subtract_op.AddOverload(MakeOverloadDecl( StandardOverloads::kSubtractInt, IntType(), IntType(), IntType()))); CEL_RETURN_IF_ERROR(subtract_op.AddOverload(MakeOverloadDecl( StandardOverloads::kSubtractUint, UintType(), UintType(), UintType()))); CEL_RETURN_IF_ERROR(subtract_op.AddOverload( MakeOverloadDecl(StandardOverloads::kSubtractDouble, DoubleType(), DoubleType(), DoubleType()))); CEL_RETURN_IF_ERROR(subtract_op.AddOverload( MakeOverloadDecl(StandardOverloads::kSubtractDurationDuration, DurationType(), DurationType(), DurationType()))); CEL_RETURN_IF_ERROR(subtract_op.AddOverload( MakeOverloadDecl(StandardOverloads::kSubtractTimestampDuration, TimestampType(), TimestampType(), DurationType()))); CEL_RETURN_IF_ERROR(subtract_op.AddOverload( MakeOverloadDecl(StandardOverloads::kSubtractTimestampTimestamp, DurationType(), TimestampType(), TimestampType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(subtract_op))); FunctionDecl multiply_op; multiply_op.set_name(builtin::kMultiply); CEL_RETURN_IF_ERROR(multiply_op.AddOverload(MakeOverloadDecl( StandardOverloads::kMultiplyInt, IntType(), IntType(), IntType()))); CEL_RETURN_IF_ERROR(multiply_op.AddOverload(MakeOverloadDecl( StandardOverloads::kMultiplyUint, UintType(), UintType(), UintType()))); CEL_RETURN_IF_ERROR(multiply_op.AddOverload( MakeOverloadDecl(StandardOverloads::kMultiplyDouble, DoubleType(), DoubleType(), DoubleType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(multiply_op))); FunctionDecl division_op; division_op.set_name(builtin::kDivide); CEL_RETURN_IF_ERROR(division_op.AddOverload(MakeOverloadDecl( StandardOverloads::kDivideInt, IntType(), IntType(), IntType()))); CEL_RETURN_IF_ERROR(division_op.AddOverload(MakeOverloadDecl( StandardOverloads::kDivideUint, UintType(), UintType(), UintType()))); CEL_RETURN_IF_ERROR(division_op.AddOverload( MakeOverloadDecl(StandardOverloads::kDivideDouble, DoubleType(), DoubleType(), DoubleType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(division_op))); FunctionDecl modulo_op; modulo_op.set_name(builtin::kModulo); CEL_RETURN_IF_ERROR(modulo_op.AddOverload(MakeOverloadDecl( StandardOverloads::kModuloInt, IntType(), IntType(), IntType()))); CEL_RETURN_IF_ERROR(modulo_op.AddOverload(MakeOverloadDecl( StandardOverloads::kModuloUint, UintType(), UintType(), UintType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(modulo_op))); FunctionDecl negate_op; negate_op.set_name(builtin::kNeg); CEL_RETURN_IF_ERROR(negate_op.AddOverload( MakeOverloadDecl(StandardOverloads::kNegateInt, IntType(), IntType()))); CEL_RETURN_IF_ERROR(negate_op.AddOverload(MakeOverloadDecl( StandardOverloads::kNegateDouble, DoubleType(), DoubleType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(negate_op))); return absl::OkStatus(); } absl::Status AddLogicalOps(TypeCheckerBuilder& builder) { FunctionDecl not_op; not_op.set_name(builtin::kNot); CEL_RETURN_IF_ERROR(not_op.AddOverload( MakeOverloadDecl(StandardOverloads::kNot, BoolType(), BoolType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(not_op))); FunctionDecl and_op; and_op.set_name(builtin::kAnd); CEL_RETURN_IF_ERROR(and_op.AddOverload(MakeOverloadDecl( StandardOverloads::kAnd, BoolType(), BoolType(), BoolType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(and_op))); FunctionDecl or_op; or_op.set_name(builtin::kOr); CEL_RETURN_IF_ERROR(or_op.AddOverload(MakeOverloadDecl( StandardOverloads::kOr, BoolType(), BoolType(), BoolType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(or_op))); FunctionDecl conditional_op; conditional_op.set_name(builtin::kTernary); CEL_RETURN_IF_ERROR(conditional_op.AddOverload( MakeOverloadDecl(StandardOverloads::kConditional, TypeParamA(), BoolType(), TypeParamA(), TypeParamA()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(conditional_op))); FunctionDecl not_strictly_false; not_strictly_false.set_name(builtin::kNotStrictlyFalse); CEL_RETURN_IF_ERROR(not_strictly_false.AddOverload(MakeOverloadDecl( StandardOverloads::kNotStrictlyFalse, BoolType(), BoolType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(not_strictly_false))); FunctionDecl not_strictly_false_deprecated; not_strictly_false_deprecated.set_name(builtin::kNotStrictlyFalseDeprecated); CEL_RETURN_IF_ERROR(not_strictly_false_deprecated.AddOverload( MakeOverloadDecl(StandardOverloads::kNotStrictlyFalseDeprecated, BoolType(), BoolType()))); CEL_RETURN_IF_ERROR( builder.AddFunction(std::move(not_strictly_false_deprecated))); return absl::OkStatus(); } absl::Status AddTypeConversions(TypeCheckerBuilder& builder) { FunctionDecl to_dyn; to_dyn.set_name(builtin::kDyn); CEL_RETURN_IF_ERROR(to_dyn.AddOverload( MakeOverloadDecl(StandardOverloads::kToDyn, DynType(), TypeParamA()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(to_dyn))); FunctionDecl to_uint; to_uint.set_name(builtin::kUint); CEL_RETURN_IF_ERROR(to_uint.AddOverload(MakeOverloadDecl( StandardOverloads::kUintToUint, UintType(), UintType()))); CEL_RETURN_IF_ERROR(to_uint.AddOverload( MakeOverloadDecl(StandardOverloads::kIntToUint, UintType(), IntType()))); CEL_RETURN_IF_ERROR(to_uint.AddOverload(MakeOverloadDecl( StandardOverloads::kDoubleToUint, UintType(), DoubleType()))); CEL_RETURN_IF_ERROR(to_uint.AddOverload(MakeOverloadDecl( StandardOverloads::kStringToUint, UintType(), StringType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(to_uint))); FunctionDecl to_int; to_int.set_name(builtin::kInt); CEL_RETURN_IF_ERROR(to_int.AddOverload( MakeOverloadDecl(StandardOverloads::kIntToInt, IntType(), IntType()))); CEL_RETURN_IF_ERROR(to_int.AddOverload( MakeOverloadDecl(StandardOverloads::kUintToInt, IntType(), UintType()))); CEL_RETURN_IF_ERROR(to_int.AddOverload(MakeOverloadDecl( StandardOverloads::kDoubleToInt, IntType(), DoubleType()))); CEL_RETURN_IF_ERROR(to_int.AddOverload(MakeOverloadDecl( StandardOverloads::kStringToInt, IntType(), StringType()))); CEL_RETURN_IF_ERROR(to_int.AddOverload(MakeOverloadDecl( StandardOverloads::kTimestampToInt, IntType(), TimestampType()))); CEL_RETURN_IF_ERROR(to_int.AddOverload(MakeOverloadDecl( StandardOverloads::kDurationToInt, IntType(), DurationType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(to_int))); FunctionDecl to_double; to_double.set_name(builtin::kDouble); CEL_RETURN_IF_ERROR(to_double.AddOverload(MakeOverloadDecl( StandardOverloads::kDoubleToDouble, DoubleType(), DoubleType()))); CEL_RETURN_IF_ERROR(to_double.AddOverload(MakeOverloadDecl( StandardOverloads::kIntToDouble, DoubleType(), IntType()))); CEL_RETURN_IF_ERROR(to_double.AddOverload(MakeOverloadDecl( StandardOverloads::kUintToDouble, DoubleType(), UintType()))); CEL_RETURN_IF_ERROR(to_double.AddOverload(MakeOverloadDecl( StandardOverloads::kStringToDouble, DoubleType(), StringType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(to_double))); FunctionDecl to_bool; to_bool.set_name("bool"); CEL_RETURN_IF_ERROR(to_bool.AddOverload(MakeOverloadDecl( StandardOverloads::kBoolToBool, BoolType(), BoolType()))); CEL_RETURN_IF_ERROR(to_bool.AddOverload(MakeOverloadDecl( StandardOverloads::kStringToBool, BoolType(), StringType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(to_bool))); FunctionDecl to_string; to_string.set_name(builtin::kString); CEL_RETURN_IF_ERROR(to_string.AddOverload(MakeOverloadDecl( StandardOverloads::kStringToString, StringType(), StringType()))); CEL_RETURN_IF_ERROR(to_string.AddOverload(MakeOverloadDecl( StandardOverloads::kBytesToString, StringType(), BytesType()))); CEL_RETURN_IF_ERROR(to_string.AddOverload(MakeOverloadDecl( StandardOverloads::kBoolToString, StringType(), BoolType()))); CEL_RETURN_IF_ERROR(to_string.AddOverload(MakeOverloadDecl( StandardOverloads::kDoubleToString, StringType(), DoubleType()))); CEL_RETURN_IF_ERROR(to_string.AddOverload(MakeOverloadDecl( StandardOverloads::kIntToString, StringType(), IntType()))); CEL_RETURN_IF_ERROR(to_string.AddOverload(MakeOverloadDecl( StandardOverloads::kUintToString, StringType(), UintType()))); CEL_RETURN_IF_ERROR(to_string.AddOverload(MakeOverloadDecl( StandardOverloads::kTimestampToString, StringType(), TimestampType()))); CEL_RETURN_IF_ERROR(to_string.AddOverload(MakeOverloadDecl( StandardOverloads::kDurationToString, StringType(), DurationType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(to_string))); FunctionDecl to_bytes; to_bytes.set_name(builtin::kBytes); CEL_RETURN_IF_ERROR(to_bytes.AddOverload(MakeOverloadDecl( StandardOverloads::kBytesToBytes, BytesType(), BytesType()))); CEL_RETURN_IF_ERROR(to_bytes.AddOverload(MakeOverloadDecl( StandardOverloads::kStringToBytes, BytesType(), StringType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(to_bytes))); FunctionDecl to_timestamp; to_timestamp.set_name(builtin::kTimestamp); CEL_RETURN_IF_ERROR(to_timestamp.AddOverload( MakeOverloadDecl(StandardOverloads::kTimestampToTimestamp, TimestampType(), TimestampType()))); CEL_RETURN_IF_ERROR(to_timestamp.AddOverload(MakeOverloadDecl( StandardOverloads::kStringToTimestamp, TimestampType(), StringType()))); CEL_RETURN_IF_ERROR(to_timestamp.AddOverload(MakeOverloadDecl( StandardOverloads::kIntToTimestamp, TimestampType(), IntType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(to_timestamp))); FunctionDecl to_duration; to_duration.set_name(builtin::kDuration); CEL_RETURN_IF_ERROR(to_duration.AddOverload(MakeOverloadDecl( StandardOverloads::kDurationToDuration, DurationType(), DurationType()))); CEL_RETURN_IF_ERROR(to_duration.AddOverload(MakeOverloadDecl( StandardOverloads::kStringToDuration, DurationType(), StringType()))); CEL_RETURN_IF_ERROR(to_duration.AddOverload(MakeOverloadDecl( StandardOverloads::kIntToDuration, DurationType(), IntType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(to_duration))); FunctionDecl to_type; to_type.set_name(builtin::kType); CEL_RETURN_IF_ERROR(to_type.AddOverload(MakeOverloadDecl( StandardOverloads::kToType, Type(TypeOfA()), TypeParamA()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(to_type))); return absl::OkStatus(); } absl::Status AddEqualityOps(TypeCheckerBuilder& builder) { FunctionDecl equals_op; equals_op.set_name(builtin::kEqual); CEL_RETURN_IF_ERROR(equals_op.AddOverload(MakeOverloadDecl( StandardOverloads::kEquals, BoolType(), TypeParamA(), TypeParamA()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(equals_op))); FunctionDecl not_equals_op; not_equals_op.set_name(builtin::kInequal); CEL_RETURN_IF_ERROR(not_equals_op.AddOverload(MakeOverloadDecl( StandardOverloads::kNotEquals, BoolType(), TypeParamA(), TypeParamA()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(not_equals_op))); return absl::OkStatus(); } absl::Status AddConatainerOps(TypeCheckerBuilder& builder) { FunctionDecl index; index.set_name(builtin::kIndex); CEL_RETURN_IF_ERROR(index.AddOverload(MakeOverloadDecl( StandardOverloads::kIndexList, TypeParamA(), ListOfA(), IntType()))); CEL_RETURN_IF_ERROR(index.AddOverload(MakeOverloadDecl( StandardOverloads::kIndexMap, TypeParamB(), MapOfAB(), TypeParamA()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(index))); FunctionDecl in_op; in_op.set_name(builtin::kIn); CEL_RETURN_IF_ERROR(in_op.AddOverload(MakeOverloadDecl( StandardOverloads::kInList, BoolType(), TypeParamA(), ListOfA()))); CEL_RETURN_IF_ERROR(in_op.AddOverload(MakeOverloadDecl( StandardOverloads::kInMap, BoolType(), TypeParamA(), MapOfAB()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(in_op))); FunctionDecl in_function_deprecated; in_function_deprecated.set_name(builtin::kInFunction); CEL_RETURN_IF_ERROR(in_function_deprecated.AddOverload(MakeOverloadDecl( StandardOverloads::kInList, BoolType(), TypeParamA(), ListOfA()))); CEL_RETURN_IF_ERROR(in_function_deprecated.AddOverload(MakeOverloadDecl( StandardOverloads::kInMap, BoolType(), TypeParamA(), MapOfAB()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(in_function_deprecated))); FunctionDecl in_op_deprecated; in_op_deprecated.set_name(builtin::kInDeprecated); CEL_RETURN_IF_ERROR(in_op_deprecated.AddOverload(MakeOverloadDecl( StandardOverloads::kInList, BoolType(), TypeParamA(), ListOfA()))); CEL_RETURN_IF_ERROR(in_op_deprecated.AddOverload(MakeOverloadDecl( StandardOverloads::kInMap, BoolType(), TypeParamA(), MapOfAB()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(in_op_deprecated))); FunctionDecl size; size.set_name(builtin::kSize); CEL_RETURN_IF_ERROR(size.AddOverload( MakeOverloadDecl(StandardOverloads::kSizeList, IntType(), ListOfA()))); CEL_RETURN_IF_ERROR(size.AddOverload(MakeMemberOverloadDecl( StandardOverloads::kSizeListMember, IntType(), ListOfA()))); CEL_RETURN_IF_ERROR(size.AddOverload( MakeOverloadDecl(StandardOverloads::kSizeMap, IntType(), MapOfAB()))); CEL_RETURN_IF_ERROR(size.AddOverload(MakeMemberOverloadDecl( StandardOverloads::kSizeMapMember, IntType(), MapOfAB()))); CEL_RETURN_IF_ERROR(size.AddOverload( MakeOverloadDecl(StandardOverloads::kSizeBytes, IntType(), BytesType()))); CEL_RETURN_IF_ERROR(size.AddOverload(MakeMemberOverloadDecl( StandardOverloads::kSizeBytesMember, IntType(), BytesType()))); CEL_RETURN_IF_ERROR(size.AddOverload(MakeOverloadDecl( StandardOverloads::kSizeString, IntType(), StringType()))); CEL_RETURN_IF_ERROR(size.AddOverload(MakeMemberOverloadDecl( StandardOverloads::kSizeStringMember, IntType(), StringType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(size))); return absl::OkStatus(); } absl::Status AddRelationOps(TypeCheckerBuilder& builder) { FunctionDecl less_op; less_op.set_name(builtin::kLess); CEL_RETURN_IF_ERROR(less_op.AddOverload(MakeOverloadDecl( StandardOverloads::kLessInt, BoolType(), IntType(), IntType()))); CEL_RETURN_IF_ERROR(less_op.AddOverload(MakeOverloadDecl( StandardOverloads::kLessUint, BoolType(), UintType(), UintType()))); CEL_RETURN_IF_ERROR(less_op.AddOverload(MakeOverloadDecl( StandardOverloads::kLessDouble, BoolType(), DoubleType(), DoubleType()))); CEL_RETURN_IF_ERROR(less_op.AddOverload(MakeOverloadDecl( StandardOverloads::kLessBool, BoolType(), BoolType(), BoolType()))); CEL_RETURN_IF_ERROR(less_op.AddOverload(MakeOverloadDecl( StandardOverloads::kLessString, BoolType(), StringType(), StringType()))); CEL_RETURN_IF_ERROR(less_op.AddOverload(MakeOverloadDecl( StandardOverloads::kLessBytes, BoolType(), BytesType(), BytesType()))); CEL_RETURN_IF_ERROR(less_op.AddOverload( MakeOverloadDecl(StandardOverloads::kLessDuration, BoolType(), DurationType(), DurationType()))); CEL_RETURN_IF_ERROR(less_op.AddOverload( MakeOverloadDecl(StandardOverloads::kLessTimestamp, BoolType(), TimestampType(), TimestampType()))); FunctionDecl greater_op; greater_op.set_name(builtin::kGreater); CEL_RETURN_IF_ERROR(greater_op.AddOverload(MakeOverloadDecl( StandardOverloads::kGreaterInt, BoolType(), IntType(), IntType()))); CEL_RETURN_IF_ERROR(greater_op.AddOverload(MakeOverloadDecl( StandardOverloads::kGreaterUint, BoolType(), UintType(), UintType()))); CEL_RETURN_IF_ERROR(greater_op.AddOverload( MakeOverloadDecl(StandardOverloads::kGreaterDouble, BoolType(), DoubleType(), DoubleType()))); CEL_RETURN_IF_ERROR(greater_op.AddOverload(MakeOverloadDecl( StandardOverloads::kGreaterBool, BoolType(), BoolType(), BoolType()))); CEL_RETURN_IF_ERROR(greater_op.AddOverload( MakeOverloadDecl(StandardOverloads::kGreaterString, BoolType(), StringType(), StringType()))); CEL_RETURN_IF_ERROR(greater_op.AddOverload(MakeOverloadDecl( StandardOverloads::kGreaterBytes, BoolType(), BytesType(), BytesType()))); CEL_RETURN_IF_ERROR(greater_op.AddOverload( MakeOverloadDecl(StandardOverloads::kGreaterDuration, BoolType(), DurationType(), DurationType()))); CEL_RETURN_IF_ERROR(greater_op.AddOverload( MakeOverloadDecl(StandardOverloads::kGreaterTimestamp, BoolType(), TimestampType(), TimestampType()))); FunctionDecl less_equals_op; less_equals_op.set_name(builtin::kLessOrEqual); CEL_RETURN_IF_ERROR(less_equals_op.AddOverload(MakeOverloadDecl( StandardOverloads::kLessEqualsInt, BoolType(), IntType(), IntType()))); CEL_RETURN_IF_ERROR(less_equals_op.AddOverload(MakeOverloadDecl( StandardOverloads::kLessEqualsUint, BoolType(), UintType(), UintType()))); CEL_RETURN_IF_ERROR(less_equals_op.AddOverload( MakeOverloadDecl(StandardOverloads::kLessEqualsDouble, BoolType(), DoubleType(), DoubleType()))); CEL_RETURN_IF_ERROR(less_equals_op.AddOverload(MakeOverloadDecl( StandardOverloads::kLessEqualsBool, BoolType(), BoolType(), BoolType()))); CEL_RETURN_IF_ERROR(less_equals_op.AddOverload( MakeOverloadDecl(StandardOverloads::kLessEqualsString, BoolType(), StringType(), StringType()))); CEL_RETURN_IF_ERROR(less_equals_op.AddOverload( MakeOverloadDecl(StandardOverloads::kLessEqualsBytes, BoolType(), BytesType(), BytesType()))); CEL_RETURN_IF_ERROR(less_equals_op.AddOverload( MakeOverloadDecl(StandardOverloads::kLessEqualsDuration, BoolType(), DurationType(), DurationType()))); CEL_RETURN_IF_ERROR(less_equals_op.AddOverload( MakeOverloadDecl(StandardOverloads::kLessEqualsTimestamp, BoolType(), TimestampType(), TimestampType()))); FunctionDecl greater_equals_op; greater_equals_op.set_name(builtin::kGreaterOrEqual); CEL_RETURN_IF_ERROR(greater_equals_op.AddOverload(MakeOverloadDecl( StandardOverloads::kGreaterEqualsInt, BoolType(), IntType(), IntType()))); CEL_RETURN_IF_ERROR(greater_equals_op.AddOverload( MakeOverloadDecl(StandardOverloads::kGreaterEqualsUint, BoolType(), UintType(), UintType()))); CEL_RETURN_IF_ERROR(greater_equals_op.AddOverload( MakeOverloadDecl(StandardOverloads::kGreaterEqualsDouble, BoolType(), DoubleType(), DoubleType()))); CEL_RETURN_IF_ERROR(greater_equals_op.AddOverload( MakeOverloadDecl(StandardOverloads::kGreaterEqualsBool, BoolType(), BoolType(), BoolType()))); CEL_RETURN_IF_ERROR(greater_equals_op.AddOverload( MakeOverloadDecl(StandardOverloads::kGreaterEqualsString, BoolType(), StringType(), StringType()))); CEL_RETURN_IF_ERROR(greater_equals_op.AddOverload( MakeOverloadDecl(StandardOverloads::kGreaterEqualsBytes, BoolType(), BytesType(), BytesType()))); CEL_RETURN_IF_ERROR(greater_equals_op.AddOverload( MakeOverloadDecl(StandardOverloads::kGreaterEqualsDuration, BoolType(), DurationType(), DurationType()))); CEL_RETURN_IF_ERROR(greater_equals_op.AddOverload( MakeOverloadDecl(StandardOverloads::kGreaterEqualsTimestamp, BoolType(), TimestampType(), TimestampType()))); if (builder.options().enable_cross_numeric_comparisons) { CEL_RETURN_IF_ERROR(less_op.AddOverload(MakeOverloadDecl( StandardOverloads::kLessIntUint, BoolType(), IntType(), UintType()))); CEL_RETURN_IF_ERROR(less_op.AddOverload( MakeOverloadDecl(StandardOverloads::kLessIntDouble, BoolType(), IntType(), DoubleType()))); CEL_RETURN_IF_ERROR(less_op.AddOverload(MakeOverloadDecl( StandardOverloads::kLessUintInt, BoolType(), UintType(), IntType()))); CEL_RETURN_IF_ERROR(less_op.AddOverload( MakeOverloadDecl(StandardOverloads::kLessUintDouble, BoolType(), UintType(), DoubleType()))); CEL_RETURN_IF_ERROR(less_op.AddOverload( MakeOverloadDecl(StandardOverloads::kLessDoubleInt, BoolType(), DoubleType(), IntType()))); CEL_RETURN_IF_ERROR(less_op.AddOverload( MakeOverloadDecl(StandardOverloads::kLessDoubleUint, BoolType(), DoubleType(), UintType()))); CEL_RETURN_IF_ERROR(greater_op.AddOverload( MakeOverloadDecl(StandardOverloads::kGreaterIntUint, BoolType(), IntType(), UintType()))); CEL_RETURN_IF_ERROR(greater_op.AddOverload( MakeOverloadDecl(StandardOverloads::kGreaterIntDouble, BoolType(), IntType(), DoubleType()))); CEL_RETURN_IF_ERROR(greater_op.AddOverload( MakeOverloadDecl(StandardOverloads::kGreaterUintInt, BoolType(), UintType(), IntType()))); CEL_RETURN_IF_ERROR(greater_op.AddOverload( MakeOverloadDecl(StandardOverloads::kGreaterUintDouble, BoolType(), UintType(), DoubleType()))); CEL_RETURN_IF_ERROR(greater_op.AddOverload( MakeOverloadDecl(StandardOverloads::kGreaterDoubleInt, BoolType(), DoubleType(), IntType()))); CEL_RETURN_IF_ERROR(greater_op.AddOverload( MakeOverloadDecl(StandardOverloads::kGreaterDoubleUint, BoolType(), DoubleType(), UintType()))); CEL_RETURN_IF_ERROR(less_equals_op.AddOverload( MakeOverloadDecl(StandardOverloads::kLessEqualsIntUint, BoolType(), IntType(), UintType()))); CEL_RETURN_IF_ERROR(less_equals_op.AddOverload( MakeOverloadDecl(StandardOverloads::kLessEqualsIntDouble, BoolType(), IntType(), DoubleType()))); CEL_RETURN_IF_ERROR(less_equals_op.AddOverload( MakeOverloadDecl(StandardOverloads::kLessEqualsUintInt, BoolType(), UintType(), IntType()))); CEL_RETURN_IF_ERROR(less_equals_op.AddOverload( MakeOverloadDecl(StandardOverloads::kLessEqualsUintDouble, BoolType(), UintType(), DoubleType()))); CEL_RETURN_IF_ERROR(less_equals_op.AddOverload( MakeOverloadDecl(StandardOverloads::kLessEqualsDoubleInt, BoolType(), DoubleType(), IntType()))); CEL_RETURN_IF_ERROR(less_equals_op.AddOverload( MakeOverloadDecl(StandardOverloads::kLessEqualsDoubleUint, BoolType(), DoubleType(), UintType()))); CEL_RETURN_IF_ERROR(greater_equals_op.AddOverload( MakeOverloadDecl(StandardOverloads::kGreaterEqualsIntUint, BoolType(), IntType(), UintType()))); CEL_RETURN_IF_ERROR(greater_equals_op.AddOverload( MakeOverloadDecl(StandardOverloads::kGreaterEqualsIntDouble, BoolType(), IntType(), DoubleType()))); CEL_RETURN_IF_ERROR(greater_equals_op.AddOverload( MakeOverloadDecl(StandardOverloads::kGreaterEqualsUintInt, BoolType(), UintType(), IntType()))); CEL_RETURN_IF_ERROR(greater_equals_op.AddOverload( MakeOverloadDecl(StandardOverloads::kGreaterEqualsUintDouble, BoolType(), UintType(), DoubleType()))); CEL_RETURN_IF_ERROR(greater_equals_op.AddOverload( MakeOverloadDecl(StandardOverloads::kGreaterEqualsDoubleInt, BoolType(), DoubleType(), IntType()))); CEL_RETURN_IF_ERROR(greater_equals_op.AddOverload( MakeOverloadDecl(StandardOverloads::kGreaterEqualsDoubleUint, BoolType(), DoubleType(), UintType()))); } CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(less_op))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(greater_op))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(less_equals_op))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(greater_equals_op))); return absl::OkStatus(); } absl::Status AddStringFunctions(TypeCheckerBuilder& builder) { FunctionDecl contains; contains.set_name(builtin::kStringContains); CEL_RETURN_IF_ERROR(contains.AddOverload( MakeMemberOverloadDecl(StandardOverloads::kContainsString, BoolType(), StringType(), StringType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(contains))); FunctionDecl starts_with; starts_with.set_name(builtin::kStringStartsWith); CEL_RETURN_IF_ERROR(starts_with.AddOverload( MakeMemberOverloadDecl(StandardOverloads::kStartsWithString, BoolType(), StringType(), StringType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(starts_with))); FunctionDecl ends_with; ends_with.set_name(builtin::kStringEndsWith); CEL_RETURN_IF_ERROR(ends_with.AddOverload( MakeMemberOverloadDecl(StandardOverloads::kEndsWithString, BoolType(), StringType(), StringType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(ends_with))); return absl::OkStatus(); } absl::Status AddRegexFunctions(TypeCheckerBuilder& builder) { FunctionDecl matches; matches.set_name(builtin::kRegexMatch); CEL_RETURN_IF_ERROR(matches.AddOverload( MakeMemberOverloadDecl(StandardOverloads::kMatchesMember, BoolType(), StringType(), StringType()))); CEL_RETURN_IF_ERROR(matches.AddOverload(MakeOverloadDecl( StandardOverloads::kMatches, BoolType(), StringType(), StringType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(matches))); return absl::OkStatus(); } absl::Status AddTimeFunctions(TypeCheckerBuilder& builder) { FunctionDecl get_full_year; get_full_year.set_name(builtin::kFullYear); CEL_RETURN_IF_ERROR(get_full_year.AddOverload(MakeMemberOverloadDecl( StandardOverloads::kTimestampToYear, IntType(), TimestampType()))); CEL_RETURN_IF_ERROR(get_full_year.AddOverload( MakeMemberOverloadDecl(StandardOverloads::kTimestampToYearWithTz, IntType(), TimestampType(), StringType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(get_full_year))); FunctionDecl get_month; get_month.set_name(builtin::kMonth); CEL_RETURN_IF_ERROR(get_month.AddOverload(MakeMemberOverloadDecl( StandardOverloads::kTimestampToMonth, IntType(), TimestampType()))); CEL_RETURN_IF_ERROR(get_month.AddOverload( MakeMemberOverloadDecl(StandardOverloads::kTimestampToMonthWithTz, IntType(), TimestampType(), StringType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(get_month))); FunctionDecl get_day_of_year; get_day_of_year.set_name(builtin::kDayOfYear); CEL_RETURN_IF_ERROR(get_day_of_year.AddOverload(MakeMemberOverloadDecl( StandardOverloads::kTimestampToDayOfYear, IntType(), TimestampType()))); CEL_RETURN_IF_ERROR(get_day_of_year.AddOverload( MakeMemberOverloadDecl(StandardOverloads::kTimestampToDayOfYearWithTz, IntType(), TimestampType(), StringType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(get_day_of_year))); FunctionDecl get_day_of_month; get_day_of_month.set_name(builtin::kDayOfMonth); CEL_RETURN_IF_ERROR(get_day_of_month.AddOverload(MakeMemberOverloadDecl( StandardOverloads::kTimestampToDayOfMonth, IntType(), TimestampType()))); CEL_RETURN_IF_ERROR(get_day_of_month.AddOverload( MakeMemberOverloadDecl(StandardOverloads::kTimestampToDayOfMonthWithTz, IntType(), TimestampType(), StringType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(get_day_of_month))); FunctionDecl get_date; get_date.set_name(builtin::kDate); CEL_RETURN_IF_ERROR(get_date.AddOverload(MakeMemberOverloadDecl( StandardOverloads::kTimestampToDate, IntType(), TimestampType()))); CEL_RETURN_IF_ERROR(get_date.AddOverload( MakeMemberOverloadDecl(StandardOverloads::kTimestampToDateWithTz, IntType(), TimestampType(), StringType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(get_date))); FunctionDecl get_day_of_week; get_day_of_week.set_name(builtin::kDayOfWeek); CEL_RETURN_IF_ERROR(get_day_of_week.AddOverload(MakeMemberOverloadDecl( StandardOverloads::kTimestampToDayOfWeek, IntType(), TimestampType()))); CEL_RETURN_IF_ERROR(get_day_of_week.AddOverload( MakeMemberOverloadDecl(StandardOverloads::kTimestampToDayOfWeekWithTz, IntType(), TimestampType(), StringType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(get_day_of_week))); FunctionDecl get_hours; get_hours.set_name(builtin::kHours); CEL_RETURN_IF_ERROR(get_hours.AddOverload(MakeMemberOverloadDecl( StandardOverloads::kTimestampToHours, IntType(), TimestampType()))); CEL_RETURN_IF_ERROR(get_hours.AddOverload( MakeMemberOverloadDecl(StandardOverloads::kTimestampToHoursWithTz, IntType(), TimestampType(), StringType()))); CEL_RETURN_IF_ERROR(get_hours.AddOverload(MakeMemberOverloadDecl( StandardOverloads::kDurationToHours, IntType(), DurationType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(get_hours))); FunctionDecl get_minutes; get_minutes.set_name(builtin::kMinutes); CEL_RETURN_IF_ERROR(get_minutes.AddOverload(MakeMemberOverloadDecl( StandardOverloads::kTimestampToMinutes, IntType(), TimestampType()))); CEL_RETURN_IF_ERROR(get_minutes.AddOverload( MakeMemberOverloadDecl(StandardOverloads::kTimestampToMinutesWithTz, IntType(), TimestampType(), StringType()))); CEL_RETURN_IF_ERROR(get_minutes.AddOverload(MakeMemberOverloadDecl( StandardOverloads::kDurationToMinutes, IntType(), DurationType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(get_minutes))); FunctionDecl get_seconds; get_seconds.set_name(builtin::kSeconds); CEL_RETURN_IF_ERROR(get_seconds.AddOverload(MakeMemberOverloadDecl( StandardOverloads::kTimestampToSeconds, IntType(), TimestampType()))); CEL_RETURN_IF_ERROR(get_seconds.AddOverload( MakeMemberOverloadDecl(StandardOverloads::kTimestampToSecondsWithTz, IntType(), TimestampType(), StringType()))); CEL_RETURN_IF_ERROR(get_seconds.AddOverload(MakeMemberOverloadDecl( StandardOverloads::kDurationToSeconds, IntType(), DurationType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(get_seconds))); FunctionDecl get_milliseconds; get_milliseconds.set_name(builtin::kMilliseconds); CEL_RETURN_IF_ERROR(get_milliseconds.AddOverload( MakeMemberOverloadDecl(StandardOverloads::kTimestampToMilliseconds, IntType(), TimestampType()))); CEL_RETURN_IF_ERROR(get_milliseconds.AddOverload( MakeMemberOverloadDecl(StandardOverloads::kTimestampToMillisecondsWithTz, IntType(), TimestampType(), StringType()))); CEL_RETURN_IF_ERROR(get_milliseconds.AddOverload(MakeMemberOverloadDecl( StandardOverloads::kDurationToMilliseconds, IntType(), DurationType()))); CEL_RETURN_IF_ERROR(builder.AddFunction(std::move(get_milliseconds))); return absl::OkStatus(); } absl::Status AddTypeConstantVariables(TypeCheckerBuilder& builder) { CEL_RETURN_IF_ERROR( builder.AddVariable(MakeVariableDecl("bool", TypeBoolType()))); CEL_RETURN_IF_ERROR( builder.AddVariable(MakeVariableDecl("null_type", TypeNullType()))); CEL_RETURN_IF_ERROR( builder.AddVariable(MakeVariableDecl(builtin::kInt, TypeIntType()))); CEL_RETURN_IF_ERROR( builder.AddVariable(MakeVariableDecl(builtin::kUint, TypeUintType()))); CEL_RETURN_IF_ERROR(builder.AddVariable( MakeVariableDecl(builtin::kDouble, TypeDoubleType()))); CEL_RETURN_IF_ERROR(builder.AddVariable( MakeVariableDecl(builtin::kString, TypeStringType()))); CEL_RETURN_IF_ERROR( builder.AddVariable(MakeVariableDecl(builtin::kBytes, TypeBytesType()))); CEL_RETURN_IF_ERROR(builder.AddVariable( MakeVariableDecl(builtin::kDuration, TypeDurationType()))); CEL_RETURN_IF_ERROR(builder.AddVariable( MakeVariableDecl(builtin::kTimestamp, TypeTimestampType()))); CEL_RETURN_IF_ERROR( builder.AddVariable(MakeVariableDecl("list", TypeListType()))); CEL_RETURN_IF_ERROR( builder.AddVariable(MakeVariableDecl("map", TypeMapType()))); CEL_RETURN_IF_ERROR(builder.AddVariable(MakeVariableDecl("type", TypeOfA()))); return absl::OkStatus(); } absl::Status AddEnumConstants(TypeCheckerBuilder& builder) { VariableDecl pb_null; pb_null.set_name("google.protobuf.NullValue.NULL_VALUE"); pb_null.set_type(NullType()); pb_null.set_value(Constant(nullptr)); CEL_RETURN_IF_ERROR(builder.AddVariable(std::move(pb_null))); return absl::OkStatus(); } absl::Status AddStandardLibraryDecls(TypeCheckerBuilder& builder) { CEL_RETURN_IF_ERROR(AddLogicalOps(builder)); CEL_RETURN_IF_ERROR(AddArithmeticOps(builder)); CEL_RETURN_IF_ERROR(AddTypeConversions(builder)); CEL_RETURN_IF_ERROR(AddEqualityOps(builder)); CEL_RETURN_IF_ERROR(AddConatainerOps(builder)); CEL_RETURN_IF_ERROR(AddRelationOps(builder)); CEL_RETURN_IF_ERROR(AddStringFunctions(builder)); CEL_RETURN_IF_ERROR(AddRegexFunctions(builder)); CEL_RETURN_IF_ERROR(AddTimeFunctions(builder)); CEL_RETURN_IF_ERROR(AddTypeConstantVariables(builder)); CEL_RETURN_IF_ERROR(AddEnumConstants(builder)); return absl::OkStatus(); } } CheckerLibrary StandardLibrary() { return {"stdlib", AddStandardLibraryDecls}; } }
#include "checker/standard_library.h" #include <memory> #include <string> #include <utility> #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "base/ast_internal/ast_impl.h" #include "base/ast_internal/expr.h" #include "checker/internal/test_ast_helpers.h" #include "checker/type_checker.h" #include "checker/type_checker_builder.h" #include "checker/validation_result.h" #include "common/ast.h" #include "common/constant.h" #include "internal/testing.h" namespace cel { namespace { using ::absl_testing::IsOk; using ::absl_testing::StatusIs; using ::cel::ast_internal::AstImpl; using ::cel::ast_internal::Reference; using ::testing::IsEmpty; using ::testing::Pointee; using ::testing::Property; TEST(StandardLibraryTest, StandardLibraryAddsDecls) { TypeCheckerBuilder builder; EXPECT_THAT(builder.AddLibrary(StandardLibrary()), IsOk()); EXPECT_THAT(std::move(builder).Build(), IsOk()); } TEST(StandardLibraryTest, StandardLibraryErrorsIfAddedTwice) { TypeCheckerBuilder builder; EXPECT_THAT(builder.AddLibrary(StandardLibrary()), IsOk()); EXPECT_THAT(builder.AddLibrary(StandardLibrary()), StatusIs(absl::StatusCode::kAlreadyExists)); } class StandardLibraryDefinitionsTest : public ::testing::Test { public: void SetUp() override { TypeCheckerBuilder builder; ASSERT_THAT(builder.AddLibrary(StandardLibrary()), IsOk()); ASSERT_OK_AND_ASSIGN(stdlib_type_checker_, std::move(builder).Build()); } protected: std::unique_ptr<TypeChecker> stdlib_type_checker_; }; class StdlibTypeVarDefinitionTest : public StandardLibraryDefinitionsTest, public testing::WithParamInterface<std::string> {}; TEST_P(StdlibTypeVarDefinitionTest, DefinesTypeConstants) { auto ast = std::make_unique<AstImpl>(); ast->root_expr().mutable_ident_expr().set_name(GetParam()); ast->root_expr().set_id(1); ASSERT_OK_AND_ASSIGN(ValidationResult result, stdlib_type_checker_->Check(std::move(ast))); EXPECT_THAT(result.GetIssues(), IsEmpty()); ASSERT_OK_AND_ASSIGN(std::unique_ptr<Ast> checked_ast, result.ReleaseAst()); const auto& checked_impl = AstImpl::CastFromPublicAst(*checked_ast); EXPECT_THAT(checked_impl.GetReference(1), Pointee(Property(&Reference::name, GetParam()))); } INSTANTIATE_TEST_SUITE_P( StdlibTypeVarDefinitions, StdlibTypeVarDefinitionTest, ::testing::Values("bool", "int", "uint", "double", "string", "bytes", "list", "map", "duration", "timestamp", "null_type"), [](const auto& info) -> std::string { return info.param; }); TEST_F(StandardLibraryDefinitionsTest, DefinesProtoStructNull) { auto ast = std::make_unique<AstImpl>(); auto& enumerator = ast->root_expr(); enumerator.set_id(4); enumerator.mutable_select_expr().set_field("NULL_VALUE"); auto& enumeration = enumerator.mutable_select_expr().mutable_operand(); enumeration.set_id(3); enumeration.mutable_select_expr().set_field("NullValue"); auto& protobuf = enumeration.mutable_select_expr().mutable_operand(); protobuf.set_id(2); protobuf.mutable_select_expr().set_field("protobuf"); auto& google = protobuf.mutable_select_expr().mutable_operand(); google.set_id(1); google.mutable_ident_expr().set_name("google"); ASSERT_OK_AND_ASSIGN(ValidationResult result, stdlib_type_checker_->Check(std::move(ast))); EXPECT_THAT(result.GetIssues(), IsEmpty()); ASSERT_OK_AND_ASSIGN(std::unique_ptr<Ast> checked_ast, result.ReleaseAst()); const auto& checked_impl = AstImpl::CastFromPublicAst(*checked_ast); EXPECT_THAT(checked_impl.GetReference(4), Pointee(Property(&Reference::name, "google.protobuf.NullValue.NULL_VALUE"))); } struct DefinitionsTestCase { std::string expr; bool type_check_success = true; CheckerOptions options; }; class StdLibDefinitionsTest : public ::testing::TestWithParam<DefinitionsTestCase> { public: void SetUp() override { TypeCheckerBuilder builder; ASSERT_THAT(builder.AddLibrary(StandardLibrary()), IsOk()); ASSERT_OK_AND_ASSIGN(stdlib_type_checker_, std::move(builder).Build()); } protected: std::unique_ptr<TypeChecker> stdlib_type_checker_; }; TEST_P(StdLibDefinitionsTest, Runner) { TypeCheckerBuilder builder(GetParam().options); ASSERT_THAT(builder.AddLibrary(StandardLibrary()), IsOk()); ASSERT_OK_AND_ASSIGN(std::unique_ptr<TypeChecker> type_checker, std::move(builder).Build()); ASSERT_OK_AND_ASSIGN(std::unique_ptr<Ast> ast, checker_internal::MakeTestParsedAst(GetParam().expr)); ASSERT_OK_AND_ASSIGN(auto result, type_checker->Check(std::move(ast))); EXPECT_EQ(result.IsValid(), GetParam().type_check_success); } INSTANTIATE_TEST_SUITE_P( Strings, StdLibDefinitionsTest, ::testing::Values(DefinitionsTestCase{ "'123'.size()", }, DefinitionsTestCase{ "size('123')", }, DefinitionsTestCase{ "'123' + '123'", }, DefinitionsTestCase{ "'123' + '123'", }, DefinitionsTestCase{ "'123' + '123'", }, DefinitionsTestCase{ "'123'.endsWith('123')", }, DefinitionsTestCase{ "'123'.startsWith('123')", }, DefinitionsTestCase{ "'123'.contains('123')", }, DefinitionsTestCase{ "'123'.matches(r'123')", }, DefinitionsTestCase{ "matches('123', r'123')", })); INSTANTIATE_TEST_SUITE_P(TypeCasts, StdLibDefinitionsTest, ::testing::Values(DefinitionsTestCase{ "int(1)", }, DefinitionsTestCase{ "uint(1)", }, DefinitionsTestCase{ "double(1)", }, DefinitionsTestCase{ "string(1)", }, DefinitionsTestCase{ "bool('true')", }, DefinitionsTestCase{ "timestamp(0)", }, DefinitionsTestCase{ "duration('1s')", })); INSTANTIATE_TEST_SUITE_P(Arithmetic, StdLibDefinitionsTest, ::testing::Values(DefinitionsTestCase{ "1 + 2", }, DefinitionsTestCase{ "1 - 2", }, DefinitionsTestCase{ "1 / 2", }, DefinitionsTestCase{ "1 * 2", }, DefinitionsTestCase{ "2 % 1", }, DefinitionsTestCase{ "-1", })); INSTANTIATE_TEST_SUITE_P( TimeArithmetic, StdLibDefinitionsTest, ::testing::Values(DefinitionsTestCase{ "timestamp(0) + duration('1s')", }, DefinitionsTestCase{ "timestamp(0) - duration('1s')", }, DefinitionsTestCase{ "timestamp(0) - timestamp(0)", }, DefinitionsTestCase{ "duration('1s') + duration('1s')", }, DefinitionsTestCase{ "duration('1s') - duration('1s')", })); INSTANTIATE_TEST_SUITE_P(NumericComparisons, StdLibDefinitionsTest, ::testing::Values(DefinitionsTestCase{ "1 > 2", }, DefinitionsTestCase{ "1 < 2", }, DefinitionsTestCase{ "1 >= 2", }, DefinitionsTestCase{ "1 <= 2", })); INSTANTIATE_TEST_SUITE_P( CrossNumericComparisons, StdLibDefinitionsTest, ::testing::Values( DefinitionsTestCase{ "1u < 2", true, {.enable_cross_numeric_comparisons = true}}, DefinitionsTestCase{ "1u > 2", true, {.enable_cross_numeric_comparisons = true}}, DefinitionsTestCase{ "1u <= 2", true, {.enable_cross_numeric_comparisons = true}}, DefinitionsTestCase{ "1u >= 2", true, {.enable_cross_numeric_comparisons = true}})); INSTANTIATE_TEST_SUITE_P( TimeComparisons, StdLibDefinitionsTest, ::testing::Values(DefinitionsTestCase{ "duration('1s') < duration('1s')", }, DefinitionsTestCase{ "duration('1s') > duration('1s')", }, DefinitionsTestCase{ "duration('1s') <= duration('1s')", }, DefinitionsTestCase{ "duration('1s') >= duration('1s')", }, DefinitionsTestCase{ "timestamp(0) < timestamp(0)", }, DefinitionsTestCase{ "timestamp(0) > timestamp(0)", }, DefinitionsTestCase{ "timestamp(0) <= timestamp(0)", }, DefinitionsTestCase{ "timestamp(0) >= timestamp(0)", })); INSTANTIATE_TEST_SUITE_P( TimeAccessors, StdLibDefinitionsTest, ::testing::Values( DefinitionsTestCase{ "timestamp(0).getFullYear()", }, DefinitionsTestCase{ "timestamp(0).getFullYear('-08:00')", }, DefinitionsTestCase{ "timestamp(0).getMonth()", }, DefinitionsTestCase{ "timestamp(0).getMonth('-08:00')", }, DefinitionsTestCase{ "timestamp(0).getDayOfYear()", }, DefinitionsTestCase{ "timestamp(0).getDayOfYear('-08:00')", }, DefinitionsTestCase{ "timestamp(0).getDate()", }, DefinitionsTestCase{ "timestamp(0).getDate('-08:00')", }, DefinitionsTestCase{ "timestamp(0).getDayOfWeek()", }, DefinitionsTestCase{ "timestamp(0).getDayOfWeek('-08:00')", }, DefinitionsTestCase{ "timestamp(0).getHours()", }, DefinitionsTestCase{ "duration('1s').getHours()", }, DefinitionsTestCase{ "timestamp(0).getHours('-08:00')", }, DefinitionsTestCase{ "timestamp(0).getMinutes()", }, DefinitionsTestCase{ "duration('1s').getMinutes()", }, DefinitionsTestCase{ "timestamp(0).getMinutes('-08:00')", }, DefinitionsTestCase{ "timestamp(0).getSeconds()", }, DefinitionsTestCase{ "duration('1s').getSeconds()", }, DefinitionsTestCase{ "timestamp(0).getSeconds('-08:00')", }, DefinitionsTestCase{ "timestamp(0).getMilliseconds()", }, DefinitionsTestCase{ "duration('1s').getMilliseconds()", }, DefinitionsTestCase{ "timestamp(0).getMilliseconds('-08:00')", })); INSTANTIATE_TEST_SUITE_P(Logic, StdLibDefinitionsTest, ::testing::Values(DefinitionsTestCase{ "true || false", }, DefinitionsTestCase{ "true && false", }, DefinitionsTestCase{ "!true", })); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/checker/standard_library.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/checker/standard_library_test.cc
4552db5798fb0853b131b783d8875794334fae7f
a43301bc-e07c-4b0a-982c-f19e66c6fd34
cpp
google/cel-cpp
type_check_issue
checker/type_check_issue.cc
checker/type_check_issue_test.cc
#include "checker/type_check_issue.h" #include <string> #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "common/source.h" namespace cel { namespace { absl::string_view SeverityString(TypeCheckIssue::Severity severity) { switch (severity) { case TypeCheckIssue::Severity::kInformation: return "INFORMATION"; case TypeCheckIssue::Severity::kWarning: return "WARNING"; case TypeCheckIssue::Severity::kError: return "ERROR"; case TypeCheckIssue::Severity::kDeprecated: return "DEPRECATED"; default: return "SEVERITY_UNSPECIFIED"; } } } std::string TypeCheckIssue::ToDisplayString(const Source& source) const { return absl::StrCat( absl::StrFormat("%s: %s:%d:%d: %s", SeverityString(severity_), source.description(), location_.line, location_.column, message_), source.DisplayErrorLocation(location_)); } }
#include "checker/type_check_issue.h" #include "common/source.h" #include "internal/testing.h" namespace cel { namespace { TEST(TypeCheckIssueTest, DisplayString) { ASSERT_OK_AND_ASSIGN(auto source, NewSource("test{\n\tfield1: 123\n}")); TypeCheckIssue issue = TypeCheckIssue::CreateError(2, 2, "test error"); EXPECT_EQ(issue.ToDisplayString(*source), "ERROR: <input>:2:2: test error\n" " | field1: 123\n" " | ..^"); } TEST(TypeCheckIssueTest, DisplayStringNoPosition) { ASSERT_OK_AND_ASSIGN(auto source, NewSource("test{\n\tfield1: 123\n}")); TypeCheckIssue issue = TypeCheckIssue::CreateError(-1, -1, "test error"); EXPECT_EQ(issue.ToDisplayString(*source), "ERROR: <input>:-1:-1: test error"); } TEST(TypeCheckIssueTest, DisplayStringDeprecated) { ASSERT_OK_AND_ASSIGN(auto source, NewSource("test{\n\tfield1: 123\n}")); TypeCheckIssue issue = TypeCheckIssue(TypeCheckIssue::Severity::kDeprecated, {-1, -1}, "test error 2"); EXPECT_EQ(issue.ToDisplayString(*source), "DEPRECATED: <input>:-1:-1: test error 2"); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/checker/type_check_issue.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/checker/type_check_issue_test.cc
4552db5798fb0853b131b783d8875794334fae7f
5b441f45-3775-471c-b737-9ebb2a54c496
cpp
google/cel-cpp
type_checker_builder
checker/type_checker_builder.cc
checker/type_checker_builder_test.cc
#include "checker/type_checker_builder.h" #include <memory> #include <string> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "checker/internal/type_check_env.h" #include "checker/internal/type_checker_impl.h" #include "checker/type_checker.h" #include "common/decl.h" #include "common/type_introspector.h" namespace cel { absl::StatusOr<std::unique_ptr<TypeChecker>> TypeCheckerBuilder::Build() && { if (env_.type_providers().empty() && env_.parent() == nullptr) { env_.AddTypeProvider(std::make_unique<TypeIntrospector>()); } return std::make_unique<checker_internal::TypeCheckerImpl>(std::move(env_)); } absl::Status TypeCheckerBuilder::AddLibrary(CheckerLibrary library) { if (!library.id.empty() && !library_ids_.insert(library.id).second) { return absl::AlreadyExistsError( absl::StrCat("library '", library.id, "' already exists")); } absl::Status status = library.options(*this); libraries_.push_back(std::move(library)); return status; } absl::Status TypeCheckerBuilder::AddVariable(const VariableDecl& decl) { bool inserted = env_.InsertVariableIfAbsent(decl); if (!inserted) { return absl::AlreadyExistsError( absl::StrCat("variable '", decl.name(), "' already exists")); } return absl::OkStatus(); } absl::Status TypeCheckerBuilder::AddFunction(const FunctionDecl& decl) { bool inserted = env_.InsertFunctionIfAbsent(decl); if (!inserted) { return absl::AlreadyExistsError( absl::StrCat("function '", decl.name(), "' already exists")); } return absl::OkStatus(); } void TypeCheckerBuilder::AddTypeProvider( std::unique_ptr<TypeIntrospector> provider) { env_.AddTypeProvider(std::move(provider)); } void TypeCheckerBuilder::set_container(absl::string_view container) { env_.set_container(std::string(container)); } }
#include "checker/type_checker_builder.h" #include <utility> #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "checker/internal/test_ast_helpers.h" #include "checker/validation_result.h" #include "common/decl.h" #include "common/type.h" #include "internal/testing.h" namespace cel { namespace { using ::absl_testing::IsOk; using ::absl_testing::StatusIs; using ::cel::checker_internal::MakeTestParsedAst; using ::testing::HasSubstr; TEST(TypeCheckerBuilderTest, AddVariable) { TypeCheckerBuilder builder; ASSERT_THAT(builder.AddVariable(MakeVariableDecl("x", IntType())), IsOk()); ASSERT_OK_AND_ASSIGN(auto checker, std::move(builder).Build()); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("x")); ASSERT_OK_AND_ASSIGN(ValidationResult result, checker->Check(std::move(ast))); EXPECT_TRUE(result.IsValid()); } TEST(TypeCheckerBuilderTest, AddVariableRedeclaredError) { TypeCheckerBuilder builder; ASSERT_THAT(builder.AddVariable(MakeVariableDecl("x", IntType())), IsOk()); EXPECT_THAT(builder.AddVariable(MakeVariableDecl("x", IntType())), StatusIs(absl::StatusCode::kAlreadyExists)); } TEST(TypeCheckerBuilderTest, AddFunction) { TypeCheckerBuilder builder; ASSERT_OK_AND_ASSIGN( auto fn_decl, MakeFunctionDecl( "add", MakeOverloadDecl("add_int", IntType(), IntType(), IntType()))); ASSERT_THAT(builder.AddFunction(fn_decl), IsOk()); ASSERT_OK_AND_ASSIGN(auto checker, std::move(builder).Build()); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("add(1, 2)")); ASSERT_OK_AND_ASSIGN(ValidationResult result, checker->Check(std::move(ast))); EXPECT_TRUE(result.IsValid()); } TEST(TypeCheckerBuilderTest, AddFunctionRedeclaredError) { TypeCheckerBuilder builder; ASSERT_OK_AND_ASSIGN( auto fn_decl, MakeFunctionDecl( "add", MakeOverloadDecl("add_int", IntType(), IntType(), IntType()))); ASSERT_THAT(builder.AddFunction(fn_decl), IsOk()); EXPECT_THAT(builder.AddFunction(fn_decl), StatusIs(absl::StatusCode::kAlreadyExists)); } TEST(TypeCheckerBuilderTest, AddLibrary) { TypeCheckerBuilder builder; ASSERT_OK_AND_ASSIGN( auto fn_decl, MakeFunctionDecl( "add", MakeOverloadDecl("add_int", IntType(), IntType(), IntType()))); ASSERT_THAT(builder.AddLibrary({"", [&](TypeCheckerBuilder& b) { return builder.AddFunction(fn_decl); }}), IsOk()); ASSERT_OK_AND_ASSIGN(auto checker, std::move(builder).Build()); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("add(1, 2)")); ASSERT_OK_AND_ASSIGN(ValidationResult result, checker->Check(std::move(ast))); EXPECT_TRUE(result.IsValid()); } TEST(TypeCheckerBuilderTest, AddLibraryRedeclaredError) { TypeCheckerBuilder builder; ASSERT_OK_AND_ASSIGN( auto fn_decl, MakeFunctionDecl( "add", MakeOverloadDecl("add_int", IntType(), IntType(), IntType()))); ASSERT_THAT(builder.AddLibrary({"testlib", [&](TypeCheckerBuilder& b) { return builder.AddFunction(fn_decl); }}), IsOk()); EXPECT_THAT(builder.AddLibrary({"testlib", [&](TypeCheckerBuilder& b) { return builder.AddFunction(fn_decl); }}), StatusIs(absl::StatusCode::kAlreadyExists, HasSubstr("testlib"))); } TEST(TypeCheckerBuilderTest, AddLibraryForwardsErrors) { TypeCheckerBuilder builder; ASSERT_OK_AND_ASSIGN( auto fn_decl, MakeFunctionDecl( "add", MakeOverloadDecl("add_int", IntType(), IntType(), IntType()))); ASSERT_THAT(builder.AddLibrary({"", [&](TypeCheckerBuilder& b) { return builder.AddFunction(fn_decl); }}), IsOk()); EXPECT_THAT(builder.AddLibrary({"", [](TypeCheckerBuilder& b) { return absl::InternalError("test error"); }}), StatusIs(absl::StatusCode::kInternal, HasSubstr("test error"))); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/checker/type_checker_builder.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/checker/type_checker_builder_test.cc
4552db5798fb0853b131b783d8875794334fae7f
de709be8-4825-4ab0-be7a-004f6ea800d0
cpp
google/cel-cpp
type_checker_impl
checker/internal/type_checker_impl.cc
checker/internal/type_checker_impl_test.cc
#include "checker/internal/type_checker_impl.h" #include <cstddef> #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/base/no_destructor.h" #include "absl/base/nullability.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "absl/types/optional.h" #include "absl/types/span.h" #include "base/ast_internal/ast_impl.h" #include "base/ast_internal/expr.h" #include "checker/internal/builtins_arena.h" #include "checker/internal/namespace_generator.h" #include "checker/internal/type_check_env.h" #include "checker/internal/type_inference_context.h" #include "checker/type_check_issue.h" #include "checker/validation_result.h" #include "common/ast.h" #include "common/ast_rewrite.h" #include "common/ast_traverse.h" #include "common/ast_visitor.h" #include "common/ast_visitor_base.h" #include "common/constant.h" #include "common/decl.h" #include "common/expr.h" #include "common/memory.h" #include "common/source.h" #include "common/type.h" #include "common/type_factory.h" #include "common/type_kind.h" #include "extensions/protobuf/memory_manager.h" #include "internal/status_macros.h" #include "google/protobuf/arena.h" namespace cel::checker_internal { namespace { class TrivialTypeFactory : public TypeFactory { public: explicit TrivialTypeFactory(absl::Nonnull<google::protobuf::Arena*> arena) : arena_(arena) {} MemoryManagerRef GetMemoryManager() const override { return extensions::ProtoMemoryManagerRef(arena_); } private: absl::Nonnull<google::protobuf::Arena*> arena_; }; using cel::ast_internal::AstImpl; using AstType = cel::ast_internal::Type; using Severity = TypeCheckIssue::Severity; Type FreeListType() { static absl::NoDestructor<Type> kInstance( Type(ListType(BuiltinsArena(), TypeParamType("element_type")))); return *kInstance; } Type FreeMapType() { static absl::NoDestructor<Type> kInstance( Type(MapType(BuiltinsArena(), TypeParamType("key_type"), TypeParamType("value_type")))); return *kInstance; } std::string FormatCandidate(absl::Span<const std::string> qualifiers) { return absl::StrJoin(qualifiers, "."); } SourceLocation ComputeSourceLocation(const AstImpl& ast, int64_t expr_id) { const auto& source_info = ast.source_info(); auto iter = source_info.positions().find(expr_id); if (iter == source_info.positions().end()) { return SourceLocation{}; } int32_t absolute_position = iter->second; int32_t line_idx = -1; for (int32_t offset : source_info.line_offsets()) { if (absolute_position >= offset) { break; } ++line_idx; } if (line_idx < 0 || line_idx >= source_info.line_offsets().size()) { return SourceLocation{1, absolute_position}; } int32_t rel_position = absolute_position - source_info.line_offsets()[line_idx] + 1; return SourceLocation{line_idx + 1, rel_position}; } absl::StatusOr<AstType> FlattenType(const Type& type); absl::StatusOr<AstType> FlattenAbstractType(const OpaqueType& type) { std::vector<AstType> parameter_types; parameter_types.reserve(type.GetParameters().size()); for (const auto& param : type.GetParameters()) { CEL_ASSIGN_OR_RETURN(auto param_type, FlattenType(param)); parameter_types.push_back(std::move(param_type)); } return AstType(ast_internal::AbstractType(std::string(type.name()), std::move(parameter_types))); } absl::StatusOr<AstType> FlattenMapType(const MapType& type) { CEL_ASSIGN_OR_RETURN(auto key, FlattenType(type.key())); CEL_ASSIGN_OR_RETURN(auto value, FlattenType(type.value())); return AstType( ast_internal::MapType(std::make_unique<AstType>(std::move(key)), std::make_unique<AstType>(std::move(value)))); } absl::StatusOr<AstType> FlattenListType(const ListType& type) { CEL_ASSIGN_OR_RETURN(auto elem, FlattenType(type.element())); return AstType( ast_internal::ListType(std::make_unique<AstType>(std::move(elem)))); } absl::StatusOr<AstType> FlattenMessageType(const StructType& type) { return AstType(ast_internal::MessageType(std::string(type.name()))); } absl::StatusOr<AstType> FlattenTypeType(const TypeType& type) { if (type.GetParameters().size() > 1) { return absl::InternalError( absl::StrCat("Unsupported type: ", type.DebugString())); } if (type.GetParameters().empty()) { return AstType(std::make_unique<AstType>()); } CEL_ASSIGN_OR_RETURN(auto param, FlattenType(type.GetParameters()[0])); return AstType(std::make_unique<AstType>(std::move(param))); } absl::StatusOr<AstType> FlattenType(const Type& type) { switch (type.kind()) { case TypeKind::kDyn: return AstType(ast_internal::DynamicType()); case TypeKind::kError: return AstType(ast_internal::ErrorType()); case TypeKind::kNull: return AstType(ast_internal::NullValue()); case TypeKind::kBool: return AstType(ast_internal::PrimitiveType::kBool); case TypeKind::kInt: return AstType(ast_internal::PrimitiveType::kInt64); case TypeKind::kUint: return AstType(ast_internal::PrimitiveType::kUint64); case TypeKind::kDouble: return AstType(ast_internal::PrimitiveType::kDouble); case TypeKind::kString: return AstType(ast_internal::PrimitiveType::kString); case TypeKind::kBytes: return AstType(ast_internal::PrimitiveType::kBytes); case TypeKind::kDuration: return AstType(ast_internal::WellKnownType::kDuration); case TypeKind::kTimestamp: return AstType(ast_internal::WellKnownType::kTimestamp); case TypeKind::kStruct: return FlattenMessageType(type.GetStruct()); case TypeKind::kList: return FlattenListType(type.GetList()); case TypeKind::kMap: return FlattenMapType(type.GetMap()); case TypeKind::kOpaque: return FlattenAbstractType(type.GetOpaque()); case TypeKind::kBoolWrapper: return AstType(ast_internal::PrimitiveTypeWrapper( ast_internal::PrimitiveType::kBool)); case TypeKind::kIntWrapper: return AstType(ast_internal::PrimitiveTypeWrapper( ast_internal::PrimitiveType::kInt64)); case TypeKind::kUintWrapper: return AstType(ast_internal::PrimitiveTypeWrapper( ast_internal::PrimitiveType::kUint64)); case TypeKind::kDoubleWrapper: return AstType(ast_internal::PrimitiveTypeWrapper( ast_internal::PrimitiveType::kDouble)); case TypeKind::kStringWrapper: return AstType(ast_internal::PrimitiveTypeWrapper( ast_internal::PrimitiveType::kString)); case TypeKind::kBytesWrapper: return AstType(ast_internal::PrimitiveTypeWrapper( ast_internal::PrimitiveType::kBytes)); case TypeKind::kTypeParam: return AstType(ast_internal::DynamicType()); case TypeKind::kType: return FlattenTypeType(type.GetType()); case TypeKind::kAny: return AstType(ast_internal::WellKnownType::kAny); default: return absl::InternalError( absl::StrCat("Unsupported type: ", type.DebugString())); } } class ResolveVisitor : public AstVisitorBase { public: struct FunctionResolution { const FunctionDecl* decl; bool namespace_rewrite; }; ResolveVisitor(absl::string_view container, NamespaceGenerator namespace_generator, const TypeCheckEnv& env, const AstImpl& ast, TypeInferenceContext& inference_context, std::vector<TypeCheckIssue>& issues, absl::Nonnull<google::protobuf::Arena*> arena, TypeFactory& type_factory) : container_(container), namespace_generator_(std::move(namespace_generator)), env_(&env), inference_context_(&inference_context), issues_(&issues), ast_(&ast), root_scope_(env.MakeVariableScope()), arena_(arena), type_factory_(&type_factory), current_scope_(&root_scope_) {} void PreVisitExpr(const Expr& expr) override { expr_stack_.push_back(&expr); } void PostVisitExpr(const Expr& expr) override { if (expr_stack_.empty()) { return; } expr_stack_.pop_back(); } void PostVisitConst(const Expr& expr, const Constant& constant) override; void PreVisitComprehension(const Expr& expr, const ComprehensionExpr& comprehension) override; void PostVisitComprehension(const Expr& expr, const ComprehensionExpr& comprehension) override; void PostVisitMap(const Expr& expr, const MapExpr& map) override; void PostVisitList(const Expr& expr, const ListExpr& list) override; void PreVisitComprehensionSubexpression( const Expr& expr, const ComprehensionExpr& comprehension, ComprehensionArg comprehension_arg) override; void PostVisitComprehensionSubexpression( const Expr& expr, const ComprehensionExpr& comprehension, ComprehensionArg comprehension_arg) override; void PostVisitIdent(const Expr& expr, const IdentExpr& ident) override; void PostVisitSelect(const Expr& expr, const SelectExpr& select) override; void PostVisitCall(const Expr& expr, const CallExpr& call) override; void PostVisitStruct(const Expr& expr, const StructExpr& create_struct) override; const absl::flat_hash_map<const Expr*, FunctionResolution>& functions() const { return functions_; } const absl::flat_hash_map<const Expr*, const VariableDecl*>& attributes() const { return attributes_; } const absl::flat_hash_map<const Expr*, std::string>& struct_types() const { return struct_types_; } const absl::flat_hash_map<const Expr*, Type>& types() const { return types_; } const absl::Status& status() const { return status_; } private: struct ComprehensionScope { const Expr* comprehension_expr; const VariableScope* parent; VariableScope* accu_scope; VariableScope* iter_scope; }; struct FunctionOverloadMatch { Type result_type; const FunctionDecl* decl; }; void ResolveSimpleIdentifier(const Expr& expr, absl::string_view name); void ResolveQualifiedIdentifier(const Expr& expr, absl::Span<const std::string> qualifiers); const FunctionDecl* ResolveFunctionCallShape(const Expr& expr, absl::string_view function_name, int arg_count, bool is_receiver); absl::Nullable<const VariableDecl*> LookupIdentifier(absl::string_view name); void ResolveFunctionOverloads(const Expr& expr, const FunctionDecl& decl, int arg_count, bool is_receiver, bool is_namespaced); void ResolveSelectOperation(const Expr& expr, absl::string_view field, const Expr& operand); void ReportMissingReference(const Expr& expr, absl::string_view name) { issues_->push_back(TypeCheckIssue::CreateError( ComputeSourceLocation(*ast_, expr.id()), absl::StrCat("undeclared reference to '", name, "' (in container '", container_, "')"))); } void ReportUndefinedField(int64_t expr_id, absl::string_view field_name, absl::string_view struct_name) { issues_->push_back(TypeCheckIssue::CreateError( ComputeSourceLocation(*ast_, expr_id), absl::StrCat("undefined field '", field_name, "' not found in struct '", struct_name, "'"))); } absl::Status CheckFieldAssignments(const Expr& expr, const StructExpr& create_struct, Type struct_type, absl::string_view resolved_name) { for (const auto& field : create_struct.fields()) { const Expr* value = &field.value(); Type value_type = GetTypeOrDyn(value); CEL_ASSIGN_OR_RETURN( absl::optional<StructTypeField> field_info, env_->LookupStructField(*type_factory_, resolved_name, field.name())); if (!field_info.has_value()) { ReportUndefinedField(field.id(), field.name(), resolved_name); continue; } Type field_type = field_info->GetType(); if (field.optional()) { field_type = OptionalType(arena_, field_type); } if (!inference_context_->IsAssignable(value_type, field_type)) { issues_->push_back(TypeCheckIssue::CreateError( ComputeSourceLocation(*ast_, field.id()), absl::StrCat("expected type of field '", field_info->name(), "' is '", field_type.DebugString(), "' but provided type is '", value_type.DebugString(), "'"))); continue; } } return absl::OkStatus(); } Type GetTypeOrDyn(const Expr* expr) { auto iter = types_.find(expr); return iter != types_.end() ? iter->second : DynType(); } absl::string_view container_; NamespaceGenerator namespace_generator_; absl::Nonnull<const TypeCheckEnv*> env_; absl::Nonnull<TypeInferenceContext*> inference_context_; absl::Nonnull<std::vector<TypeCheckIssue>*> issues_; absl::Nonnull<const ast_internal::AstImpl*> ast_; VariableScope root_scope_; absl::Nonnull<google::protobuf::Arena*> arena_; absl::Nonnull<TypeFactory*> type_factory_; const VariableScope* current_scope_; std::vector<const Expr*> expr_stack_; absl::flat_hash_map<const Expr*, std::vector<std::string>> maybe_namespaced_functions_; absl::flat_hash_set<const Expr*> deferred_select_operations_; absl::Status status_; std::vector<std::unique_ptr<VariableScope>> comprehension_vars_; std::vector<ComprehensionScope> comprehension_scopes_; absl::flat_hash_map<const Expr*, FunctionResolution> functions_; absl::flat_hash_map<const Expr*, const VariableDecl*> attributes_; absl::flat_hash_map<const Expr*, std::string> struct_types_; absl::flat_hash_map<const Expr*, Type> types_; }; void ResolveVisitor::PostVisitIdent(const Expr& expr, const IdentExpr& ident) { if (expr_stack_.size() == 1) { ResolveSimpleIdentifier(expr, ident.name()); return; } int stack_pos = expr_stack_.size() - 1; std::vector<std::string> qualifiers; qualifiers.push_back(ident.name()); const Expr* receiver_call = nullptr; const Expr* root_candidate = expr_stack_[stack_pos]; while (stack_pos > 0) { --stack_pos; const Expr* parent = expr_stack_[stack_pos]; if (parent->has_call_expr() && (&parent->call_expr().target() == root_candidate)) { receiver_call = parent; break; } else if (!parent->has_select_expr()) { break; } qualifiers.push_back(parent->select_expr().field()); deferred_select_operations_.insert(parent); root_candidate = parent; if (parent->select_expr().test_only()) { break; } } if (receiver_call == nullptr) { ResolveQualifiedIdentifier(*root_candidate, qualifiers); } else { maybe_namespaced_functions_[receiver_call] = std::move(qualifiers); } } void ResolveVisitor::PostVisitConst(const Expr& expr, const Constant& constant) { switch (constant.kind().index()) { case ConstantKindIndexOf<std::nullptr_t>(): types_[&expr] = NullType(); break; case ConstantKindIndexOf<bool>(): types_[&expr] = BoolType(); break; case ConstantKindIndexOf<int64_t>(): types_[&expr] = IntType(); break; case ConstantKindIndexOf<uint64_t>(): types_[&expr] = UintType(); break; case ConstantKindIndexOf<double>(): types_[&expr] = DoubleType(); break; case ConstantKindIndexOf<BytesConstant>(): types_[&expr] = BytesType(); break; case ConstantKindIndexOf<StringConstant>(): types_[&expr] = StringType(); break; case ConstantKindIndexOf<absl::Duration>(): types_[&expr] = DurationType(); break; case ConstantKindIndexOf<absl::Time>(): types_[&expr] = TimestampType(); break; default: issues_->push_back(TypeCheckIssue::CreateError( ComputeSourceLocation(*ast_, expr.id()), absl::StrCat("unsupported constant type: ", constant.kind().index()))); break; } } bool IsSupportedKeyType(const Type& type) { switch (type.kind()) { case TypeKind::kBool: case TypeKind::kInt: case TypeKind::kUint: case TypeKind::kString: case TypeKind::kDyn: return true; default: return false; } } void ResolveVisitor::PostVisitMap(const Expr& expr, const MapExpr& map) { absl::optional<Type> overall_key_type; absl::optional<Type> overall_value_type; for (const auto& entry : map.entries()) { const Expr* key = &entry.key(); Type key_type = GetTypeOrDyn(key); if (!IsSupportedKeyType(key_type)) { issues_->push_back(TypeCheckIssue( Severity::kWarning, ComputeSourceLocation(*ast_, key->id()), absl::StrCat("unsupported map key type: ", key_type.DebugString()))); } if (overall_key_type.has_value()) { if (key_type != *overall_key_type) { overall_key_type = DynType(); } } else { overall_key_type = key_type; } const Expr* value = &entry.value(); Type value_type = GetTypeOrDyn(value); if (entry.optional()) { if (value_type.IsOptional()) { value_type = value_type.GetOptional().GetParameter(); } } if (overall_value_type.has_value()) { if (value_type != *overall_value_type) { overall_value_type = DynType(); } } else { overall_value_type = value_type; } } if (overall_value_type.has_value() && overall_key_type.has_value()) { types_[&expr] = MapType(arena_, *overall_key_type, *overall_value_type); return; } else if (overall_value_type.has_value() != overall_key_type.has_value()) { status_.Update(absl::InternalError( "Map has mismatched key and value type inference resolution")); return; } types_[&expr] = inference_context_->InstantiateTypeParams(FreeMapType()); } void ResolveVisitor::PostVisitList(const Expr& expr, const ListExpr& list) { absl::optional<Type> overall_value_type; for (const auto& element : list.elements()) { const Expr* value = &element.expr(); Type value_type = GetTypeOrDyn(value); if (element.optional()) { if (value_type.IsOptional()) { value_type = value_type.GetOptional().GetParameter(); } } if (overall_value_type.has_value()) { if (value_type != *overall_value_type) { overall_value_type = DynType(); } } else { overall_value_type = value_type; } } if (overall_value_type.has_value()) { types_[&expr] = ListType(arena_, *overall_value_type); return; } types_[&expr] = inference_context_->InstantiateTypeParams(FreeListType()); } void ResolveVisitor::PostVisitStruct(const Expr& expr, const StructExpr& create_struct) { absl::Status status; std::string resolved_name; Type resolved_type; namespace_generator_.GenerateCandidates( create_struct.name(), [&](const absl::string_view name) { auto type = env_->LookupTypeName(*type_factory_, name); if (!type.ok()) { status.Update(type.status()); return false; } else if (type->has_value()) { resolved_name = name; resolved_type = **type; return false; } return true; }); if (!status.ok()) { status_.Update(status); return; } if (resolved_name.empty()) { ReportMissingReference(expr, create_struct.name()); return; } if (resolved_type.kind() != TypeKind::kStruct && !IsWellKnownMessageType(resolved_name)) { issues_->push_back(TypeCheckIssue::CreateError( ComputeSourceLocation(*ast_, expr.id()), absl::StrCat("type '", resolved_name, "' does not support message creation"))); return; } types_[&expr] = resolved_type; struct_types_[&expr] = resolved_name; status_.Update( CheckFieldAssignments(expr, create_struct, resolved_type, resolved_name)); } void ResolveVisitor::PostVisitCall(const Expr& expr, const CallExpr& call) { if (auto iter = maybe_namespaced_functions_.find(&expr); iter != maybe_namespaced_functions_.end()) { std::string namespaced_name = absl::StrCat(FormatCandidate(iter->second), ".", call.function()); const FunctionDecl* decl = ResolveFunctionCallShape(expr, namespaced_name, call.args().size(), false); if (decl != nullptr) { ResolveFunctionOverloads(expr, *decl, call.args().size(), false, true); return; } ResolveQualifiedIdentifier(call.target(), iter->second); } int arg_count = call.args().size(); if (call.has_target()) { ++arg_count; } const FunctionDecl* decl = ResolveFunctionCallShape( expr, call.function(), arg_count, call.has_target()); if (decl != nullptr) { ResolveFunctionOverloads(expr, *decl, arg_count, call.has_target(), false); return; } ReportMissingReference(expr, call.function()); } void ResolveVisitor::PreVisitComprehension( const Expr& expr, const ComprehensionExpr& comprehension) { std::unique_ptr<VariableScope> accu_scope = current_scope_->MakeNestedScope(); auto* accu_scope_ptr = accu_scope.get(); std::unique_ptr<VariableScope> iter_scope = accu_scope->MakeNestedScope(); auto* iter_scope_ptr = iter_scope.get(); comprehension_vars_.push_back(std::move(accu_scope)); comprehension_vars_.push_back(std::move(iter_scope)); comprehension_scopes_.push_back( {&expr, current_scope_, accu_scope_ptr, iter_scope_ptr}); } void ResolveVisitor::PostVisitComprehension( const Expr& expr, const ComprehensionExpr& comprehension) { comprehension_scopes_.pop_back(); types_[&expr] = GetTypeOrDyn(&comprehension.result()); } void ResolveVisitor::PreVisitComprehensionSubexpression( const Expr& expr, const ComprehensionExpr& comprehension, ComprehensionArg comprehension_arg) { if (comprehension_scopes_.empty()) { status_.Update(absl::InternalError( "Comprehension scope stack is empty in comprehension")); return; } auto& scope = comprehension_scopes_.back(); if (scope.comprehension_expr != &expr) { status_.Update(absl::InternalError("Comprehension scope stack broken")); return; } switch (comprehension_arg) { case ComprehensionArg::LOOP_CONDITION: current_scope_ = scope.accu_scope; break; case ComprehensionArg::LOOP_STEP: current_scope_ = scope.iter_scope; break; case ComprehensionArg::RESULT: current_scope_ = scope.accu_scope; break; default: current_scope_ = scope.parent; break; } } void ResolveVisitor::PostVisitComprehensionSubexpression( const Expr& expr, const ComprehensionExpr& comprehension, ComprehensionArg comprehension_arg) { if (comprehension_scopes_.empty()) { status_.Update(absl::InternalError( "Comprehension scope stack is empty in comprehension")); return; } auto& scope = comprehension_scopes_.back(); if (scope.comprehension_expr != &expr) { status_.Update(absl::InternalError("Comprehension scope stack broken")); return; } current_scope_ = scope.parent; switch (comprehension_arg) { case ComprehensionArg::ACCU_INIT: scope.accu_scope->InsertVariableIfAbsent(MakeVariableDecl( comprehension.accu_var(), GetTypeOrDyn(&comprehension.accu_init()))); break; case ComprehensionArg::ITER_RANGE: { Type range_type = GetTypeOrDyn(&comprehension.iter_range()); Type iter_type = DynType(); switch (range_type.kind()) { case TypeKind::kList: iter_type = range_type.GetList().element(); break; case TypeKind::kMap: iter_type = range_type.GetMap().key(); break; case TypeKind::kDyn: break; default: issues_->push_back(TypeCheckIssue::CreateError( ComputeSourceLocation(*ast_, expr.id()), absl::StrCat("expression of type '", range_type.DebugString(), "' cannot be the range of a comprehension (must be " "list, map, or dynamic)"))); break; } scope.iter_scope->InsertVariableIfAbsent( MakeVariableDecl(comprehension.iter_var(), iter_type)); break; } case ComprehensionArg::RESULT: types_[&expr] = types_[&expr]; break; default: break; } } void ResolveVisitor::PostVisitSelect(const Expr& expr, const SelectExpr& select) { if (!deferred_select_operations_.contains(&expr)) { ResolveSelectOperation(expr, select.field(), select.operand()); } } const FunctionDecl* ResolveVisitor::ResolveFunctionCallShape( const Expr& expr, absl::string_view function_name, int arg_count, bool is_receiver) { const FunctionDecl* decl = nullptr; namespace_generator_.GenerateCandidates( function_name, [&, this](absl::string_view candidate) -> bool { decl = env_->LookupFunction(candidate); if (decl == nullptr) { return true; } for (const auto& ovl : decl->overloads()) { if (ovl.member() == is_receiver && ovl.args().size() == arg_count) { return false; } } decl = nullptr; return true; }); return decl; } void ResolveVisitor::ResolveFunctionOverloads(const Expr& expr, const FunctionDecl& decl, int arg_count, bool is_receiver, bool is_namespaced) { std::vector<Type> arg_types; arg_types.reserve(arg_count); if (is_receiver) { arg_types.push_back(GetTypeOrDyn(&expr.call_expr().target())); } for (int i = 0; i < expr.call_expr().args().size(); ++i) { arg_types.push_back(GetTypeOrDyn(&expr.call_expr().args()[i])); } absl::optional<TypeInferenceContext::OverloadResolution> resolution = inference_context_->ResolveOverload(decl, arg_types, is_receiver); if (!resolution.has_value()) { issues_->push_back(TypeCheckIssue::CreateError( ComputeSourceLocation(*ast_, expr.id()), absl::StrCat("found no matching overload for '", decl.name(), "' applied to (", absl::StrJoin(arg_types, ", ", [](std::string* out, const Type& type) { out->append(type.DebugString()); }), ")"))); return; } auto* result_decl = google::protobuf::Arena::Create<FunctionDecl>(arena_); result_decl->set_name(decl.name()); for (const auto& ovl : resolution->overloads) { absl::Status s = result_decl->AddOverload(ovl); if (!s.ok()) { status_.Update(absl::InternalError(absl::StrCat( "failed to add overload to resolved function declaration: ", s))); } } functions_[&expr] = {result_decl, is_namespaced}; types_[&expr] = resolution->result_type; } absl::Nullable<const VariableDecl*> ResolveVisitor::LookupIdentifier( absl::string_view name) { if (const VariableDecl* decl = current_scope_->LookupVariable(name); decl != nullptr) { return decl; } absl::StatusOr<absl::optional<VariableDecl>> constant = env_->LookupTypeConstant(*type_factory_, arena_, name); if (!constant.ok()) { status_.Update(constant.status()); return nullptr; } if (constant->has_value()) { if (constant->value().type().kind() == TypeKind::kEnum) { constant->value().set_type(IntType()); } return google::protobuf::Arena::Create<VariableDecl>( arena_, std::move(constant).value().value()); } return nullptr; } void ResolveVisitor::ResolveSimpleIdentifier(const Expr& expr, absl::string_view name) { const VariableDecl* decl = nullptr; namespace_generator_.GenerateCandidates( name, [&decl, this](absl::string_view candidate) { decl = LookupIdentifier(candidate); return decl == nullptr; }); if (decl == nullptr) { ReportMissingReference(expr, name); return; } attributes_[&expr] = decl; types_[&expr] = inference_context_->InstantiateTypeParams(decl->type()); } void ResolveVisitor::ResolveQualifiedIdentifier( const Expr& expr, absl::Span<const std::string> qualifiers) { if (qualifiers.size() == 1) { ResolveSimpleIdentifier(expr, qualifiers[0]); return; } absl::Nullable<const VariableDecl*> decl = nullptr; int segment_index_out = -1; namespace_generator_.GenerateCandidates( qualifiers, [&decl, &segment_index_out, this](absl::string_view candidate, int segment_index) { decl = LookupIdentifier(candidate); if (decl != nullptr) { segment_index_out = segment_index; return false; } return true; }); if (decl == nullptr) { ReportMissingReference(expr, FormatCandidate(qualifiers)); return; } const int num_select_opts = qualifiers.size() - segment_index_out - 1; const Expr* root = &expr; std::vector<const Expr*> select_opts; select_opts.reserve(num_select_opts); for (int i = 0; i < num_select_opts; ++i) { select_opts.push_back(root); root = &root->select_expr().operand(); } attributes_[root] = decl; types_[root] = inference_context_->InstantiateTypeParams(decl->type()); for (auto iter = select_opts.rbegin(); iter != select_opts.rend(); ++iter) { ResolveSelectOperation(**iter, (*iter)->select_expr().field(), (*iter)->select_expr().operand()); } } void ResolveVisitor::ResolveSelectOperation(const Expr& expr, absl::string_view field, const Expr& operand) { auto impl = [&](const Type& operand_type) -> absl::optional<Type> { if (operand_type.kind() == TypeKind::kDyn || operand_type.kind() == TypeKind::kAny) { return DynType(); } if (operand_type.kind() == TypeKind::kStruct) { StructType struct_type = operand_type.GetStruct(); auto field_info = env_->LookupStructField(*type_factory_, struct_type.name(), field); if (!field_info.ok()) { status_.Update(field_info.status()); return absl::nullopt; } if (!field_info->has_value()) { ReportUndefinedField(expr.id(), field, struct_type.name()); return absl::nullopt; } auto type = field_info->value().GetType(); if (type.kind() == TypeKind::kEnum) { return IntType(); } return type; } if (operand_type.kind() == TypeKind::kMap) { MapType map_type = operand_type.GetMap(); if (inference_context_->IsAssignable(StringType(), map_type.GetKey())) { return map_type.GetValue(); } } issues_->push_back(TypeCheckIssue::CreateError( ComputeSourceLocation(*ast_, expr.id()), absl::StrCat("expression of type '", operand_type.DebugString(), "' cannot be the operand of a select operation"))); return absl::nullopt; }; const Type& operand_type = GetTypeOrDyn(&operand); absl::optional<Type> result_type; if (operand_type.IsOptional()) { auto optional_type = operand_type.GetOptional(); Type held_type = optional_type.GetParameter(); result_type = impl(held_type); } else { result_type = impl(operand_type); } if (result_type.has_value()) { if (expr.select_expr().test_only()) { types_[&expr] = BoolType(); } else { types_[&expr] = *result_type; } } } class ResolveRewriter : public AstRewriterBase { public: explicit ResolveRewriter(const ResolveVisitor& visitor, const TypeInferenceContext& inference_context, AstImpl::ReferenceMap& references, AstImpl::TypeMap& types) : visitor_(visitor), inference_context_(inference_context), reference_map_(references), type_map_(types) {} bool PostVisitRewrite(Expr& expr) override { bool rewritten = false; if (auto iter = visitor_.attributes().find(&expr); iter != visitor_.attributes().end()) { const VariableDecl* decl = iter->second; auto& ast_ref = reference_map_[expr.id()]; ast_ref.set_name(decl->name()); if (decl->has_value()) { ast_ref.set_value(decl->value()); } expr.mutable_ident_expr().set_name(decl->name()); rewritten = true; } else if (auto iter = visitor_.functions().find(&expr); iter != visitor_.functions().end()) { const FunctionDecl* decl = iter->second.decl; const bool needs_rewrite = iter->second.namespace_rewrite; auto& ast_ref = reference_map_[expr.id()]; ast_ref.set_name(decl->name()); for (const auto& overload : decl->overloads()) { ast_ref.mutable_overload_id().push_back(overload.id()); } expr.mutable_call_expr().set_function(decl->name()); if (needs_rewrite && expr.call_expr().has_target()) { expr.mutable_call_expr().set_target(nullptr); } rewritten = true; } else if (auto iter = visitor_.struct_types().find(&expr); iter != visitor_.struct_types().end()) { auto& ast_ref = reference_map_[expr.id()]; ast_ref.set_name(iter->second); if (expr.has_struct_expr()) { expr.mutable_struct_expr().set_name(iter->second); } rewritten = true; } if (auto iter = visitor_.types().find(&expr); iter != visitor_.types().end()) { auto flattened_type = FlattenType(inference_context_.FinalizeType(iter->second)); if (!flattened_type.ok()) { status_.Update(flattened_type.status()); return rewritten; } type_map_[expr.id()] = *std::move(flattened_type); rewritten = true; } return rewritten; } const absl::Status& status() const { return status_; } private: absl::Status status_; const ResolveVisitor& visitor_; const TypeInferenceContext& inference_context_; AstImpl::ReferenceMap& reference_map_; AstImpl::TypeMap& type_map_; }; } absl::StatusOr<ValidationResult> TypeCheckerImpl::Check( std::unique_ptr<Ast> ast) const { auto& ast_impl = AstImpl::CastFromPublicAst(*ast); google::protobuf::Arena type_arena; std::vector<TypeCheckIssue> issues; CEL_ASSIGN_OR_RETURN(auto generator, NamespaceGenerator::Create(env_.container())); TypeInferenceContext type_inference_context(&type_arena); TrivialTypeFactory type_factory(&type_arena); ResolveVisitor visitor(env_.container(), std::move(generator), env_, ast_impl, type_inference_context, issues, &type_arena, type_factory); TraversalOptions opts; opts.use_comprehension_callbacks = true; AstTraverse(ast_impl.root_expr(), visitor, opts); CEL_RETURN_IF_ERROR(visitor.status()); for (const auto& issue : issues) { if (issue.severity() == Severity::kError) { return ValidationResult(std::move(issues)); } } ResolveRewriter rewriter(visitor, type_inference_context, ast_impl.reference_map(), ast_impl.type_map()); AstRewrite(ast_impl.root_expr(), rewriter); CEL_RETURN_IF_ERROR(rewriter.status()); ast_impl.set_is_checked(true); return ValidationResult(std::move(ast), std::move(issues)); } }
#include "checker/internal/type_checker_impl.h" #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/base/no_destructor.h" #include "absl/base/nullability.h" #include "absl/container/flat_hash_set.h" #include "absl/log/absl_check.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "base/ast_internal/ast_impl.h" #include "base/ast_internal/expr.h" #include "checker/internal/test_ast_helpers.h" #include "checker/internal/type_check_env.h" #include "checker/type_check_issue.h" #include "checker/validation_result.h" #include "common/ast.h" #include "common/decl.h" #include "common/type.h" #include "common/type_introspector.h" #include "extensions/protobuf/type_reflector.h" #include "internal/status_macros.h" #include "internal/testing.h" #include "proto/test/v1/proto2/test_all_types.pb.h" #include "proto/test/v1/proto3/test_all_types.pb.h" #include "google/protobuf/arena.h" #include "google/protobuf/message.h" namespace cel { namespace checker_internal { namespace { using ::absl_testing::IsOk; using ::cel::ast_internal::AstImpl; using ::cel::ast_internal::Reference; using ::google::api::expr::test::v1::proto3::TestAllTypes; using ::testing::_; using ::testing::Contains; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::IsEmpty; using ::testing::Pair; using ::testing::Property; using AstType = ast_internal::Type; using Severity = TypeCheckIssue::Severity; namespace testpb3 = ::google::api::expr::test::v1::proto3; std::string SevString(Severity severity) { switch (severity) { case Severity::kDeprecated: return "Deprecated"; case Severity::kError: return "Error"; case Severity::kWarning: return "Warning"; case Severity::kInformation: return "Information"; } } } } template <typename Sink> void AbslStringify(Sink& sink, const TypeCheckIssue& issue) { absl::Format(&sink, "TypeCheckIssue(%s): %s", checker_internal::SevString(issue.severity()), issue.message()); } namespace checker_internal { namespace { absl::Nonnull<google::protobuf::Arena*> TestTypeArena() { static absl::NoDestructor<google::protobuf::Arena> kArena; return &(*kArena); } FunctionDecl MakeIdentFunction() { auto decl = MakeFunctionDecl( "identity", MakeOverloadDecl("identity", TypeParamType("A"), TypeParamType("A"))); ABSL_CHECK_OK(decl.status()); return decl.value(); } MATCHER_P2(IsIssueWithSubstring, severity, substring, "") { const TypeCheckIssue& issue = arg; if (issue.severity() == severity && absl::StrContains(issue.message(), substring)) { return true; } *result_listener << "expected: " << SevString(severity) << " " << substring << "\nactual: " << SevString(issue.severity()) << " " << issue.message(); return false; } MATCHER_P(IsVariableReference, var_name, "") { const Reference& reference = arg; if (reference.name() == var_name) { return true; } *result_listener << "expected: " << var_name << "\nactual: " << reference.name(); return false; } MATCHER_P2(IsFunctionReference, fn_name, overloads, "") { const Reference& reference = arg; if (reference.name() != fn_name) { *result_listener << "expected: " << fn_name << "\nactual: " << reference.name(); } absl::flat_hash_set<std::string> got_overload_set( reference.overload_id().begin(), reference.overload_id().end()); absl::flat_hash_set<std::string> want_overload_set(overloads.begin(), overloads.end()); if (got_overload_set != want_overload_set) { *result_listener << "expected overload_ids: " << absl::StrJoin(want_overload_set, ",") << "\nactual: " << absl::StrJoin(got_overload_set, ","); } return reference.name() == fn_name && got_overload_set == want_overload_set; } absl::Status RegisterMinimalBuiltins(absl::Nonnull<google::protobuf::Arena*> arena, TypeCheckEnv& env) { Type list_of_a = ListType(arena, TypeParamType("A")); FunctionDecl add_op; add_op.set_name("_+_"); CEL_RETURN_IF_ERROR(add_op.AddOverload( MakeOverloadDecl("add_int_int", IntType(), IntType(), IntType()))); CEL_RETURN_IF_ERROR(add_op.AddOverload( MakeOverloadDecl("add_uint_uint", UintType(), UintType(), UintType()))); CEL_RETURN_IF_ERROR(add_op.AddOverload(MakeOverloadDecl( "add_double_double", DoubleType(), DoubleType(), DoubleType()))); CEL_RETURN_IF_ERROR(add_op.AddOverload( MakeOverloadDecl("add_list", list_of_a, list_of_a, list_of_a))); FunctionDecl not_op; not_op.set_name("!_"); CEL_RETURN_IF_ERROR(not_op.AddOverload( MakeOverloadDecl("logical_not", BoolType{}, BoolType{}))); FunctionDecl not_strictly_false; not_strictly_false.set_name("@not_strictly_false"); CEL_RETURN_IF_ERROR(not_strictly_false.AddOverload( MakeOverloadDecl("not_strictly_false", BoolType{}, DynType{}))); FunctionDecl mult_op; mult_op.set_name("_*_"); CEL_RETURN_IF_ERROR(mult_op.AddOverload( MakeOverloadDecl("mult_int_int", IntType(), IntType(), IntType()))); FunctionDecl or_op; or_op.set_name("_||_"); CEL_RETURN_IF_ERROR(or_op.AddOverload( MakeOverloadDecl("logical_or", BoolType{}, BoolType{}, BoolType{}))); FunctionDecl and_op; and_op.set_name("_&&_"); CEL_RETURN_IF_ERROR(and_op.AddOverload( MakeOverloadDecl("logical_and", BoolType{}, BoolType{}, BoolType{}))); FunctionDecl lt_op; lt_op.set_name("_<_"); CEL_RETURN_IF_ERROR(lt_op.AddOverload( MakeOverloadDecl("lt_int_int", BoolType{}, IntType(), IntType()))); FunctionDecl gt_op; gt_op.set_name("_>_"); CEL_RETURN_IF_ERROR(gt_op.AddOverload( MakeOverloadDecl("gt_int_int", BoolType{}, IntType(), IntType()))); FunctionDecl eq_op; eq_op.set_name("_==_"); CEL_RETURN_IF_ERROR(eq_op.AddOverload(MakeOverloadDecl( "equals", BoolType{}, TypeParamType("A"), TypeParamType("A")))); FunctionDecl ternary_op; ternary_op.set_name("_?_:_"); CEL_RETURN_IF_ERROR(eq_op.AddOverload(MakeOverloadDecl( "conditional", TypeParamType("A"), BoolType{}, TypeParamType("A"), TypeParamType("A")))); FunctionDecl to_int; to_int.set_name("int"); CEL_RETURN_IF_ERROR(to_int.AddOverload( MakeOverloadDecl("to_int", IntType(), DynType()))); FunctionDecl to_duration; to_duration.set_name("duration"); CEL_RETURN_IF_ERROR(to_duration.AddOverload( MakeOverloadDecl("to_duration", DurationType(), StringType()))); FunctionDecl to_timestamp; to_timestamp.set_name("timestamp"); CEL_RETURN_IF_ERROR(to_timestamp.AddOverload( MakeOverloadDecl("to_timestamp", TimestampType(), IntType()))); FunctionDecl to_dyn; to_dyn.set_name("dyn"); CEL_RETURN_IF_ERROR(to_dyn.AddOverload( MakeOverloadDecl("to_dyn", DynType(), TypeParamType("A")))); FunctionDecl to_type; to_type.set_name("type"); CEL_RETURN_IF_ERROR(to_type.AddOverload( MakeOverloadDecl("to_type", TypeType(arena, TypeParamType("A")), TypeParamType("A")))); env.InsertFunctionIfAbsent(std::move(not_op)); env.InsertFunctionIfAbsent(std::move(not_strictly_false)); env.InsertFunctionIfAbsent(std::move(add_op)); env.InsertFunctionIfAbsent(std::move(mult_op)); env.InsertFunctionIfAbsent(std::move(or_op)); env.InsertFunctionIfAbsent(std::move(and_op)); env.InsertFunctionIfAbsent(std::move(lt_op)); env.InsertFunctionIfAbsent(std::move(gt_op)); env.InsertFunctionIfAbsent(std::move(to_int)); env.InsertFunctionIfAbsent(std::move(eq_op)); env.InsertFunctionIfAbsent(std::move(ternary_op)); env.InsertFunctionIfAbsent(std::move(to_dyn)); env.InsertFunctionIfAbsent(std::move(to_type)); env.InsertFunctionIfAbsent(std::move(to_duration)); env.InsertFunctionIfAbsent(std::move(to_timestamp)); return absl::OkStatus(); } TEST(TypeCheckerImplTest, SmokeTest) { TypeCheckEnv env; google::protobuf::Arena arena; ASSERT_THAT(RegisterMinimalBuiltins(&arena, env), IsOk()); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("1 + 2")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); EXPECT_TRUE(result.IsValid()); EXPECT_THAT(result.GetIssues(), IsEmpty()); } TEST(TypeCheckerImplTest, SimpleIdentsResolved) { TypeCheckEnv env; google::protobuf::Arena arena; ASSERT_THAT(RegisterMinimalBuiltins(&arena, env), IsOk()); env.InsertVariableIfAbsent(MakeVariableDecl("x", IntType())); env.InsertVariableIfAbsent(MakeVariableDecl("y", IntType())); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("x + y")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); EXPECT_TRUE(result.IsValid()); EXPECT_THAT(result.GetIssues(), IsEmpty()); } TEST(TypeCheckerImplTest, ReportMissingIdentDecl) { TypeCheckEnv env; google::protobuf::Arena arena; ASSERT_THAT(RegisterMinimalBuiltins(&arena, env), IsOk()); env.InsertVariableIfAbsent(MakeVariableDecl("x", IntType())); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("x + y")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); EXPECT_FALSE(result.IsValid()); EXPECT_THAT(result.GetIssues(), ElementsAre(IsIssueWithSubstring(Severity::kError, "undeclared reference to 'y'"))); } TEST(TypeCheckerImplTest, QualifiedIdentsResolved) { TypeCheckEnv env; google::protobuf::Arena arena; ASSERT_THAT(RegisterMinimalBuiltins(&arena, env), IsOk()); env.InsertVariableIfAbsent(MakeVariableDecl("x.y", IntType())); env.InsertVariableIfAbsent(MakeVariableDecl("x.z", IntType())); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("x.y + x.z")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); EXPECT_TRUE(result.IsValid()); EXPECT_THAT(result.GetIssues(), IsEmpty()); } TEST(TypeCheckerImplTest, ReportMissingQualifiedIdentDecl) { TypeCheckEnv env; google::protobuf::Arena arena; ASSERT_THAT(RegisterMinimalBuiltins(&arena, env), IsOk()); env.InsertVariableIfAbsent(MakeVariableDecl("x", IntType())); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("y.x")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); EXPECT_FALSE(result.IsValid()); EXPECT_THAT(result.GetIssues(), ElementsAre(IsIssueWithSubstring( Severity::kError, "undeclared reference to 'y.x'"))); } TEST(TypeCheckerImplTest, ResolveMostQualfiedIdent) { TypeCheckEnv env; google::protobuf::Arena arena; ASSERT_THAT(RegisterMinimalBuiltins(&arena, env), IsOk()); env.InsertVariableIfAbsent(MakeVariableDecl("x", IntType())); env.InsertVariableIfAbsent(MakeVariableDecl("x.y", MapType())); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("x.y.z")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); ASSERT_OK_AND_ASSIGN(auto checked_ast, result.ReleaseAst()); auto& ast_impl = AstImpl::CastFromPublicAst(*checked_ast); EXPECT_THAT(ast_impl.reference_map(), Contains(Pair(_, IsVariableReference("x.y")))); } TEST(TypeCheckerImplTest, MemberFunctionCallResolved) { TypeCheckEnv env; env.InsertVariableIfAbsent(MakeVariableDecl("x", IntType())); env.InsertVariableIfAbsent(MakeVariableDecl("y", IntType())); FunctionDecl foo; foo.set_name("foo"); ASSERT_THAT(foo.AddOverload(MakeMemberOverloadDecl("int_foo_int", IntType(), IntType(), IntType())), IsOk()); env.InsertFunctionIfAbsent(std::move(foo)); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("x.foo(y)")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); EXPECT_TRUE(result.IsValid()); EXPECT_THAT(result.GetIssues(), IsEmpty()); } TEST(TypeCheckerImplTest, MemberFunctionCallNotDeclared) { TypeCheckEnv env; env.InsertVariableIfAbsent(MakeVariableDecl("x", IntType())); env.InsertVariableIfAbsent(MakeVariableDecl("y", IntType())); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("x.foo(y)")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); EXPECT_FALSE(result.IsValid()); EXPECT_THAT(result.GetIssues(), ElementsAre(IsIssueWithSubstring( Severity::kError, "undeclared reference to 'foo'"))); } TEST(TypeCheckerImplTest, FunctionShapeMismatch) { TypeCheckEnv env; ASSERT_OK_AND_ASSIGN( auto foo, MakeFunctionDecl("foo", MakeOverloadDecl("foo_int_int", IntType(), IntType(), IntType()))); env.InsertFunctionIfAbsent(foo); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("foo(1, 2, 3)")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); EXPECT_FALSE(result.IsValid()); EXPECT_THAT(result.GetIssues(), ElementsAre(IsIssueWithSubstring( Severity::kError, "undeclared reference to 'foo'"))); } TEST(TypeCheckerImplTest, NamespaceFunctionCallResolved) { TypeCheckEnv env; env.InsertVariableIfAbsent(MakeVariableDecl("x", IntType())); env.InsertVariableIfAbsent(MakeVariableDecl("y", IntType())); FunctionDecl foo; foo.set_name("x.foo"); ASSERT_THAT( foo.AddOverload(MakeOverloadDecl("x_foo_int", IntType(), IntType())), IsOk()); env.InsertFunctionIfAbsent(std::move(foo)); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("x.foo(y)")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); EXPECT_TRUE(result.IsValid()); EXPECT_THAT(result.GetIssues(), IsEmpty()); ASSERT_OK_AND_ASSIGN(auto checked_ast, result.ReleaseAst()); auto& ast_impl = AstImpl::CastFromPublicAst(*checked_ast); EXPECT_TRUE(ast_impl.root_expr().has_call_expr()) << absl::StrCat("kind: ", ast_impl.root_expr().kind().index()); EXPECT_EQ(ast_impl.root_expr().call_expr().function(), "x.foo"); EXPECT_FALSE(ast_impl.root_expr().call_expr().has_target()); } TEST(TypeCheckerImplTest, NamespacedFunctionSkipsFieldCheck) { TypeCheckEnv env; env.InsertVariableIfAbsent(MakeVariableDecl("x", IntType())); FunctionDecl foo; foo.set_name("x.y.foo"); ASSERT_THAT( foo.AddOverload(MakeOverloadDecl("x_y_foo_int", IntType(), IntType())), IsOk()); env.InsertFunctionIfAbsent(std::move(foo)); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("x.y.foo(x)")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); EXPECT_TRUE(result.IsValid()); EXPECT_THAT(result.GetIssues(), IsEmpty()); ASSERT_OK_AND_ASSIGN(auto checked_ast, result.ReleaseAst()); auto& ast_impl = AstImpl::CastFromPublicAst(*checked_ast); EXPECT_TRUE(ast_impl.root_expr().has_call_expr()) << absl::StrCat("kind: ", ast_impl.root_expr().kind().index()); EXPECT_EQ(ast_impl.root_expr().call_expr().function(), "x.y.foo"); EXPECT_FALSE(ast_impl.root_expr().call_expr().has_target()); } TEST(TypeCheckerImplTest, MixedListTypeToDyn) { TypeCheckEnv env; google::protobuf::Arena arena; ASSERT_THAT(RegisterMinimalBuiltins(&arena, env), IsOk()); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("[1, 'a']")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); ASSERT_TRUE(result.IsValid()); EXPECT_THAT(result.GetIssues(), IsEmpty()); auto& ast_impl = AstImpl::CastFromPublicAst(*result.GetAst()); EXPECT_TRUE(ast_impl.type_map().at(1).list_type().elem_type().has_dyn()); } TEST(TypeCheckerImplTest, FreeListTypeToDyn) { TypeCheckEnv env; google::protobuf::Arena arena; ASSERT_THAT(RegisterMinimalBuiltins(&arena, env), IsOk()); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("[]")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); ASSERT_TRUE(result.IsValid()); EXPECT_THAT(result.GetIssues(), IsEmpty()); auto& ast_impl = AstImpl::CastFromPublicAst(*result.GetAst()); EXPECT_TRUE(ast_impl.type_map().at(1).list_type().elem_type().has_dyn()); } TEST(TypeCheckerImplTest, FreeMapTypeToDyn) { TypeCheckEnv env; google::protobuf::Arena arena; ASSERT_THAT(RegisterMinimalBuiltins(&arena, env), IsOk()); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("{}")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); ASSERT_TRUE(result.IsValid()); EXPECT_THAT(result.GetIssues(), IsEmpty()); auto& ast_impl = AstImpl::CastFromPublicAst(*result.GetAst()); EXPECT_TRUE(ast_impl.type_map().at(1).map_type().key_type().has_dyn()); EXPECT_TRUE(ast_impl.type_map().at(1).map_type().value_type().has_dyn()); } TEST(TypeCheckerImplTest, MapTypeWithMixedKeys) { TypeCheckEnv env; google::protobuf::Arena arena; ASSERT_THAT(RegisterMinimalBuiltins(&arena, env), IsOk()); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("{'a': 1, 2: 3}")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); ASSERT_TRUE(result.IsValid()); EXPECT_THAT(result.GetIssues(), IsEmpty()); auto& ast_impl = AstImpl::CastFromPublicAst(*result.GetAst()); EXPECT_TRUE(ast_impl.type_map().at(1).map_type().key_type().has_dyn()); EXPECT_EQ(ast_impl.type_map().at(1).map_type().value_type().primitive(), ast_internal::PrimitiveType::kInt64); } TEST(TypeCheckerImplTest, MapTypeUnsupportedKeyWarns) { TypeCheckEnv env; google::protobuf::Arena arena; ASSERT_THAT(RegisterMinimalBuiltins(&arena, env), IsOk()); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("{{}: 'a'}")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); ASSERT_TRUE(result.IsValid()); EXPECT_THAT(result.GetIssues(), ElementsAre(IsIssueWithSubstring(Severity::kWarning, "unsupported map key type:"))); } TEST(TypeCheckerImplTest, MapTypeWithMixedValues) { TypeCheckEnv env; google::protobuf::Arena arena; ASSERT_THAT(RegisterMinimalBuiltins(&arena, env), IsOk()); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("{'a': 1, 'b': '2'}")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); ASSERT_TRUE(result.IsValid()); EXPECT_THAT(result.GetIssues(), IsEmpty()); auto& ast_impl = AstImpl::CastFromPublicAst(*result.GetAst()); EXPECT_EQ(ast_impl.type_map().at(1).map_type().key_type().primitive(), ast_internal::PrimitiveType::kString); EXPECT_TRUE(ast_impl.type_map().at(1).map_type().value_type().has_dyn()); } TEST(TypeCheckerImplTest, ComprehensionVariablesResolved) { TypeCheckEnv env; google::protobuf::Arena arena; ASSERT_THAT(RegisterMinimalBuiltins(&arena, env), IsOk()); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("[1, 2, 3].exists(x, x * x > 10)")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); EXPECT_TRUE(result.IsValid()); EXPECT_THAT(result.GetIssues(), IsEmpty()); } TEST(TypeCheckerImplTest, MapComprehensionVariablesResolved) { TypeCheckEnv env; google::protobuf::Arena arena; ASSERT_THAT(RegisterMinimalBuiltins(&arena, env), IsOk()); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("{1: 3, 2: 4}.exists(x, x == 2)")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); EXPECT_TRUE(result.IsValid()); EXPECT_THAT(result.GetIssues(), IsEmpty()); } TEST(TypeCheckerImplTest, NestedComprehensions) { TypeCheckEnv env; google::protobuf::Arena arena; ASSERT_THAT(RegisterMinimalBuiltins(&arena, env), IsOk()); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN( auto ast, MakeTestParsedAst("[1, 2].all(x, ['1', '2'].exists(y, int(y) == x))")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); EXPECT_TRUE(result.IsValid()); EXPECT_THAT(result.GetIssues(), IsEmpty()); } TEST(TypeCheckerImplTest, ComprehensionVarsFollowNamespacePriorityRules) { TypeCheckEnv env; env.set_container("com"); google::protobuf::Arena arena; ASSERT_THAT(RegisterMinimalBuiltins(&arena, env), IsOk()); env.InsertVariableIfAbsent(MakeVariableDecl("com.x", IntType())); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("['1', '2'].all(x, x == 2)")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); EXPECT_TRUE(result.IsValid()); EXPECT_THAT(result.GetIssues(), IsEmpty()); ASSERT_OK_AND_ASSIGN(auto checked_ast, result.ReleaseAst()); auto& ast_impl = AstImpl::CastFromPublicAst(*checked_ast); EXPECT_THAT(ast_impl.reference_map(), Contains(Pair(_, IsVariableReference("com.x")))); } TEST(TypeCheckerImplTest, ComprehensionVarsFollowQualifiedIdentPriority) { TypeCheckEnv env; google::protobuf::Arena arena; ASSERT_THAT(RegisterMinimalBuiltins(&arena, env), IsOk()); env.InsertVariableIfAbsent(MakeVariableDecl("x.y", IntType())); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("[{'y': '2'}].all(x, x.y == 2)")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); EXPECT_TRUE(result.IsValid()); EXPECT_THAT(result.GetIssues(), IsEmpty()); ASSERT_OK_AND_ASSIGN(auto checked_ast, result.ReleaseAst()); auto& ast_impl = AstImpl::CastFromPublicAst(*checked_ast); EXPECT_THAT(ast_impl.reference_map(), Contains(Pair(_, IsVariableReference("x.y")))); } struct PrimitiveLiteralsTestCase { std::string expr; ast_internal::PrimitiveType expected_type; }; class PrimitiveLiteralsTest : public testing::TestWithParam<PrimitiveLiteralsTestCase> {}; TEST_P(PrimitiveLiteralsTest, LiteralsTypeInferred) { TypeCheckEnv env; const PrimitiveLiteralsTestCase& test_case = GetParam(); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst(test_case.expr)); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); ASSERT_TRUE(result.IsValid()); ASSERT_OK_AND_ASSIGN(auto checked_ast, result.ReleaseAst()); auto& ast_impl = AstImpl::CastFromPublicAst(*checked_ast); EXPECT_EQ(ast_impl.type_map()[1].primitive(), test_case.expected_type); } INSTANTIATE_TEST_SUITE_P( PrimitiveLiteralsTests, PrimitiveLiteralsTest, ::testing::Values( PrimitiveLiteralsTestCase{ .expr = "1", .expected_type = ast_internal::PrimitiveType::kInt64, }, PrimitiveLiteralsTestCase{ .expr = "1.0", .expected_type = ast_internal::PrimitiveType::kDouble, }, PrimitiveLiteralsTestCase{ .expr = "1u", .expected_type = ast_internal::PrimitiveType::kUint64, }, PrimitiveLiteralsTestCase{ .expr = "'string'", .expected_type = ast_internal::PrimitiveType::kString, }, PrimitiveLiteralsTestCase{ .expr = "b'bytes'", .expected_type = ast_internal::PrimitiveType::kBytes, }, PrimitiveLiteralsTestCase{ .expr = "false", .expected_type = ast_internal::PrimitiveType::kBool, })); struct AstTypeConversionTestCase { Type decl_type; ast_internal::Type expected_type; }; class AstTypeConversionTest : public testing::TestWithParam<AstTypeConversionTestCase> {}; TEST_P(AstTypeConversionTest, TypeConversion) { TypeCheckEnv env; ASSERT_TRUE( env.InsertVariableIfAbsent(MakeVariableDecl("x", GetParam().decl_type))); const AstTypeConversionTestCase& test_case = GetParam(); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("x")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); ASSERT_TRUE(result.IsValid()); ASSERT_OK_AND_ASSIGN(auto checked_ast, result.ReleaseAst()); auto& ast_impl = AstImpl::CastFromPublicAst(*checked_ast); EXPECT_EQ(ast_impl.type_map()[1], test_case.expected_type) << GetParam().decl_type.DebugString(); } INSTANTIATE_TEST_SUITE_P( Primitives, AstTypeConversionTest, ::testing::Values( AstTypeConversionTestCase{ .decl_type = NullType(), .expected_type = AstType(ast_internal::NullValue()), }, AstTypeConversionTestCase{ .decl_type = DynType(), .expected_type = AstType(ast_internal::DynamicType()), }, AstTypeConversionTestCase{ .decl_type = BoolType(), .expected_type = AstType(ast_internal::PrimitiveType::kBool), }, AstTypeConversionTestCase{ .decl_type = IntType(), .expected_type = AstType(ast_internal::PrimitiveType::kInt64), }, AstTypeConversionTestCase{ .decl_type = UintType(), .expected_type = AstType(ast_internal::PrimitiveType::kUint64), }, AstTypeConversionTestCase{ .decl_type = DoubleType(), .expected_type = AstType(ast_internal::PrimitiveType::kDouble), }, AstTypeConversionTestCase{ .decl_type = StringType(), .expected_type = AstType(ast_internal::PrimitiveType::kString), }, AstTypeConversionTestCase{ .decl_type = BytesType(), .expected_type = AstType(ast_internal::PrimitiveType::kBytes), }, AstTypeConversionTestCase{ .decl_type = TimestampType(), .expected_type = AstType(ast_internal::WellKnownType::kTimestamp), }, AstTypeConversionTestCase{ .decl_type = DurationType(), .expected_type = AstType(ast_internal::WellKnownType::kDuration), })); INSTANTIATE_TEST_SUITE_P( Wrappers, AstTypeConversionTest, ::testing::Values( AstTypeConversionTestCase{ .decl_type = IntWrapperType(), .expected_type = AstType(ast_internal::PrimitiveTypeWrapper( ast_internal::PrimitiveType::kInt64)), }, AstTypeConversionTestCase{ .decl_type = UintWrapperType(), .expected_type = AstType(ast_internal::PrimitiveTypeWrapper( ast_internal::PrimitiveType::kUint64)), }, AstTypeConversionTestCase{ .decl_type = DoubleWrapperType(), .expected_type = AstType(ast_internal::PrimitiveTypeWrapper( ast_internal::PrimitiveType::kDouble)), }, AstTypeConversionTestCase{ .decl_type = BoolWrapperType(), .expected_type = AstType(ast_internal::PrimitiveTypeWrapper( ast_internal::PrimitiveType::kBool)), }, AstTypeConversionTestCase{ .decl_type = StringWrapperType(), .expected_type = AstType(ast_internal::PrimitiveTypeWrapper( ast_internal::PrimitiveType::kString)), }, AstTypeConversionTestCase{ .decl_type = BytesWrapperType(), .expected_type = AstType(ast_internal::PrimitiveTypeWrapper( ast_internal::PrimitiveType::kBytes)), })); INSTANTIATE_TEST_SUITE_P( ComplexTypes, AstTypeConversionTest, ::testing::Values( AstTypeConversionTestCase{ .decl_type = ListType(TestTypeArena(), IntType()), .expected_type = AstType(ast_internal::ListType(std::make_unique<AstType>( ast_internal::PrimitiveType::kInt64))), }, AstTypeConversionTestCase{ .decl_type = MapType(TestTypeArena(), IntType(), IntType()), .expected_type = AstType(ast_internal::MapType( std::make_unique<AstType>(ast_internal::PrimitiveType::kInt64), std::make_unique<AstType>( ast_internal::PrimitiveType::kInt64))), }, AstTypeConversionTestCase{ .decl_type = TypeType(TestTypeArena(), IntType()), .expected_type = AstType( std::make_unique<AstType>(ast_internal::PrimitiveType::kInt64)), }, AstTypeConversionTestCase{ .decl_type = OpaqueType(TestTypeArena(), "tuple", {IntType(), IntType()}), .expected_type = AstType(ast_internal::AbstractType( "tuple", {AstType(ast_internal::PrimitiveType::kInt64), AstType(ast_internal::PrimitiveType::kInt64)})), }, AstTypeConversionTestCase{ .decl_type = StructType(MessageType(TestAllTypes::descriptor())), .expected_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes"))})); TEST(TypeCheckerImplTest, NullLiteral) { TypeCheckEnv env; TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("null")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); ASSERT_TRUE(result.IsValid()); ASSERT_OK_AND_ASSIGN(auto checked_ast, result.ReleaseAst()); auto& ast_impl = AstImpl::CastFromPublicAst(*checked_ast); EXPECT_TRUE(ast_impl.type_map()[1].has_null()); } TEST(TypeCheckerImplTest, ComprehensionUnsupportedRange) { TypeCheckEnv env; google::protobuf::Arena arena; ASSERT_THAT(RegisterMinimalBuiltins(&arena, env), IsOk()); env.InsertVariableIfAbsent(MakeVariableDecl("y", IntType())); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("'abc'.all(x, y == 2)")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); EXPECT_FALSE(result.IsValid()); EXPECT_THAT(result.GetIssues(), Contains(IsIssueWithSubstring( Severity::kError, "expression of type 'string' cannot be " "the range of a comprehension"))); } TEST(TypeCheckerImplTest, ComprehensionDynRange) { TypeCheckEnv env; google::protobuf::Arena arena; ASSERT_THAT(RegisterMinimalBuiltins(&arena, env), IsOk()); env.InsertVariableIfAbsent(MakeVariableDecl("range", DynType())); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("range.all(x, x == 2)")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); EXPECT_TRUE(result.IsValid()); EXPECT_THAT(result.GetIssues(), IsEmpty()); } TEST(TypeCheckerImplTest, BasicOvlResolution) { TypeCheckEnv env; google::protobuf::Arena arena; ASSERT_THAT(RegisterMinimalBuiltins(&arena, env), IsOk()); env.InsertVariableIfAbsent(MakeVariableDecl("x", DoubleType())); env.InsertVariableIfAbsent(MakeVariableDecl("y", DoubleType())); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("x + y")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); EXPECT_TRUE(result.IsValid()); EXPECT_THAT(result.GetIssues(), IsEmpty()); ASSERT_OK_AND_ASSIGN(auto checked_ast, result.ReleaseAst()); auto& ast_impl = AstImpl::CastFromPublicAst(*checked_ast); EXPECT_THAT(ast_impl.reference_map()[2], IsFunctionReference( "_+_", std::vector<std::string>{"add_double_double"})); } TEST(TypeCheckerImplTest, OvlResolutionMultipleOverloads) { TypeCheckEnv env; google::protobuf::Arena arena; ASSERT_THAT(RegisterMinimalBuiltins(&arena, env), IsOk()); env.InsertVariableIfAbsent(MakeVariableDecl("x", DoubleType())); env.InsertVariableIfAbsent(MakeVariableDecl("y", DoubleType())); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("dyn(x) + dyn(y)")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); EXPECT_TRUE(result.IsValid()); EXPECT_THAT(result.GetIssues(), IsEmpty()); ASSERT_OK_AND_ASSIGN(auto checked_ast, result.ReleaseAst()); auto& ast_impl = AstImpl::CastFromPublicAst(*checked_ast); EXPECT_THAT(ast_impl.reference_map()[3], IsFunctionReference("_+_", std::vector<std::string>{ "add_double_double", "add_int_int", "add_list", "add_uint_uint"})); } TEST(TypeCheckerImplTest, BasicFunctionResultTypeResolution) { TypeCheckEnv env; google::protobuf::Arena arena; ASSERT_THAT(RegisterMinimalBuiltins(&arena, env), IsOk()); env.InsertVariableIfAbsent(MakeVariableDecl("x", DoubleType())); env.InsertVariableIfAbsent(MakeVariableDecl("y", DoubleType())); env.InsertVariableIfAbsent(MakeVariableDecl("z", DoubleType())); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("x + y + z")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); EXPECT_TRUE(result.IsValid()); EXPECT_THAT(result.GetIssues(), IsEmpty()); ASSERT_OK_AND_ASSIGN(auto checked_ast, result.ReleaseAst()); auto& ast_impl = AstImpl::CastFromPublicAst(*checked_ast); EXPECT_THAT(ast_impl.reference_map()[2], IsFunctionReference( "_+_", std::vector<std::string>{"add_double_double"})); EXPECT_THAT(ast_impl.reference_map()[4], IsFunctionReference( "_+_", std::vector<std::string>{"add_double_double"})); int64_t root_id = ast_impl.root_expr().id(); EXPECT_EQ(ast_impl.type_map()[root_id].primitive(), ast_internal::PrimitiveType::kDouble); } TEST(TypeCheckerImplTest, BasicOvlResolutionNoMatch) { TypeCheckEnv env; google::protobuf::Arena arena; ASSERT_THAT(RegisterMinimalBuiltins(&arena, env), IsOk()); env.InsertVariableIfAbsent(MakeVariableDecl("x", IntType())); env.InsertVariableIfAbsent(MakeVariableDecl("y", StringType())); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("x + y")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); EXPECT_FALSE(result.IsValid()); EXPECT_THAT(result.GetIssues(), Contains(IsIssueWithSubstring(Severity::kError, "no matching overload for '_+_'" " applied to (int, string)"))); } TEST(TypeCheckerImplTest, ParmeterizedOvlResolutionMatch) { TypeCheckEnv env; google::protobuf::Arena arena; ASSERT_THAT(RegisterMinimalBuiltins(&arena, env), IsOk()); env.InsertVariableIfAbsent(MakeVariableDecl("x", IntType())); env.InsertVariableIfAbsent(MakeVariableDecl("y", StringType())); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("([x] + []) == [x]")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); EXPECT_TRUE(result.IsValid()); } TEST(TypeCheckerImplTest, AliasedTypeVarSameType) { TypeCheckEnv env; google::protobuf::Arena arena; ASSERT_THAT(RegisterMinimalBuiltins(&arena, env), IsOk()); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("[].exists(x, x == 10 || x == '10')")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); EXPECT_FALSE(result.IsValid()); EXPECT_THAT( result.GetIssues(), ElementsAre(IsIssueWithSubstring( Severity::kError, "no matching overload for '_==_' applied to"))); } TEST(TypeCheckerImplTest, TypeVarRange) { TypeCheckEnv env; google::protobuf::Arena arena; ASSERT_THAT(RegisterMinimalBuiltins(&arena, env), IsOk()); env.InsertFunctionIfAbsent(MakeIdentFunction()); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("identity([]).exists(x, x == 10 )")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); EXPECT_TRUE(result.IsValid()) << absl::StrJoin(result.GetIssues(), "\n"); } TEST(TypeCheckerImplTest, WellKnownTypeCreation) { TypeCheckEnv env; env.AddTypeProvider(std::make_unique<TypeIntrospector>()); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN( auto ast, MakeTestParsedAst("google.protobuf.Int32Value{value: 10}")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); ASSERT_OK_AND_ASSIGN(std::unique_ptr<Ast> checked_ast, result.ReleaseAst()); const auto& ast_impl = AstImpl::CastFromPublicAst(*checked_ast); EXPECT_THAT(ast_impl.type_map(), Contains(Pair(ast_impl.root_expr().id(), Eq(AstType(ast_internal::PrimitiveTypeWrapper( ast_internal::PrimitiveType::kInt64)))))); EXPECT_THAT(ast_impl.reference_map(), Contains(Pair(ast_impl.root_expr().id(), Property(&ast_internal::Reference::name, "google.protobuf.Int32Value")))); } TEST(TypeCheckerImplTest, TypeInferredFromStructCreation) { TypeCheckEnv env; env.AddTypeProvider(std::make_unique<TypeIntrospector>()); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("google.protobuf.Struct{fields: {}}")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); ASSERT_OK_AND_ASSIGN(std::unique_ptr<Ast> checked_ast, result.ReleaseAst()); const auto& ast_impl = AstImpl::CastFromPublicAst(*checked_ast); int64_t map_expr_id = ast_impl.root_expr().struct_expr().fields().at(0).value().id(); ASSERT_NE(map_expr_id, 0); EXPECT_THAT( ast_impl.type_map(), Contains(Pair( map_expr_id, Eq(AstType(ast_internal::MapType( std::make_unique<AstType>(ast_internal::PrimitiveType::kString), std::make_unique<AstType>(ast_internal::DynamicType()))))))); } TEST(TypeCheckerImplTest, ContainerLookupForMessageCreation) { TypeCheckEnv env; env.set_container("google.protobuf"); env.AddTypeProvider(std::make_unique<TypeIntrospector>()); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("Int32Value{value: 10}")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); ASSERT_OK_AND_ASSIGN(std::unique_ptr<Ast> checked_ast, result.ReleaseAst()); const auto& ast_impl = AstImpl::CastFromPublicAst(*checked_ast); EXPECT_THAT(ast_impl.type_map(), Contains(Pair(ast_impl.root_expr().id(), Eq(AstType(ast_internal::PrimitiveTypeWrapper( ast_internal::PrimitiveType::kInt64)))))); EXPECT_THAT(ast_impl.reference_map(), Contains(Pair(ast_impl.root_expr().id(), Property(&ast_internal::Reference::name, "google.protobuf.Int32Value")))); } TEST(TypeCheckerImplTest, EnumValueCopiedToReferenceMap) { TypeCheckEnv env; env.set_container("google.api.expr.test.v1.proto3"); env.AddTypeProvider(std::make_unique<cel::extensions::ProtoTypeReflector>()); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst("TestAllTypes.NestedEnum.BAZ")); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); ASSERT_OK_AND_ASSIGN(std::unique_ptr<Ast> checked_ast, result.ReleaseAst()); const auto& ast_impl = AstImpl::CastFromPublicAst(*checked_ast); auto ref_iter = ast_impl.reference_map().find(ast_impl.root_expr().id()); ASSERT_NE(ref_iter, ast_impl.reference_map().end()); EXPECT_EQ(ref_iter->second.name(), "google.api.expr.test.v1.proto3.TestAllTypes.NestedEnum.BAZ"); EXPECT_EQ(ref_iter->second.value().int_value(), 2); } struct CheckedExprTestCase { std::string expr; ast_internal::Type expected_result_type; std::string error_substring; }; class WktCreationTest : public testing::TestWithParam<CheckedExprTestCase> {}; TEST_P(WktCreationTest, MessageCreation) { const CheckedExprTestCase& test_case = GetParam(); TypeCheckEnv env; env.AddTypeProvider(std::make_unique<TypeIntrospector>()); env.set_container("google.protobuf"); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst(test_case.expr)); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); if (!test_case.error_substring.empty()) { EXPECT_THAT(result.GetIssues(), Contains(IsIssueWithSubstring(Severity::kError, test_case.error_substring))); return; } ASSERT_TRUE(result.IsValid()) << absl::StrJoin(result.GetIssues(), "\n", [](std::string* out, const TypeCheckIssue& issue) { absl::StrAppend(out, issue.message()); }); ASSERT_OK_AND_ASSIGN(std::unique_ptr<Ast> checked_ast, result.ReleaseAst()); const auto& ast_impl = AstImpl::CastFromPublicAst(*checked_ast); EXPECT_THAT(ast_impl.type_map(), Contains(Pair(ast_impl.root_expr().id(), Eq(test_case.expected_result_type)))); } INSTANTIATE_TEST_SUITE_P( WellKnownTypes, WktCreationTest, ::testing::Values( CheckedExprTestCase{ .expr = "google.protobuf.Int32Value{value: 10}", .expected_result_type = AstType(ast_internal::PrimitiveTypeWrapper( ast_internal::PrimitiveType::kInt64)), }, CheckedExprTestCase{ .expr = ".google.protobuf.Int32Value{value: 10}", .expected_result_type = AstType(ast_internal::PrimitiveTypeWrapper( ast_internal::PrimitiveType::kInt64)), }, CheckedExprTestCase{ .expr = "Int32Value{value: 10}", .expected_result_type = AstType(ast_internal::PrimitiveTypeWrapper( ast_internal::PrimitiveType::kInt64)), }, CheckedExprTestCase{ .expr = "google.protobuf.Int32Value{value: '10'}", .expected_result_type = AstType(), .error_substring = "expected type of field 'value' is 'int' but " "provided type is 'string'"}, CheckedExprTestCase{ .expr = "google.protobuf.Int32Value{not_a_field: '10'}", .expected_result_type = AstType(), .error_substring = "undefined field 'not_a_field' not found in " "struct 'google.protobuf.Int32Value'"}, CheckedExprTestCase{ .expr = "NotAType{not_a_field: '10'}", .expected_result_type = AstType(), .error_substring = "undeclared reference to 'NotAType' (in container " "'google.protobuf')"}, CheckedExprTestCase{ .expr = ".protobuf.Int32Value{value: 10}", .expected_result_type = AstType(), .error_substring = "undeclared reference to '.protobuf.Int32Value' (in container " "'google.protobuf')"}, CheckedExprTestCase{ .expr = "Int32Value{value: 10}.value", .expected_result_type = AstType(), .error_substring = "expression of type 'google.protobuf.Int64Value' cannot be the " "operand of a select operation"}, CheckedExprTestCase{ .expr = "Int64Value{value: 10}", .expected_result_type = AstType(ast_internal::PrimitiveTypeWrapper( ast_internal::PrimitiveType::kInt64)), }, CheckedExprTestCase{ .expr = "BoolValue{value: true}", .expected_result_type = AstType(ast_internal::PrimitiveTypeWrapper( ast_internal::PrimitiveType::kBool)), }, CheckedExprTestCase{ .expr = "UInt64Value{value: 10u}", .expected_result_type = AstType(ast_internal::PrimitiveTypeWrapper( ast_internal::PrimitiveType::kUint64)), }, CheckedExprTestCase{ .expr = "UInt32Value{value: 10u}", .expected_result_type = AstType(ast_internal::PrimitiveTypeWrapper( ast_internal::PrimitiveType::kUint64)), }, CheckedExprTestCase{ .expr = "FloatValue{value: 1.25}", .expected_result_type = AstType(ast_internal::PrimitiveTypeWrapper( ast_internal::PrimitiveType::kDouble)), }, CheckedExprTestCase{ .expr = "DoubleValue{value: 1.25}", .expected_result_type = AstType(ast_internal::PrimitiveTypeWrapper( ast_internal::PrimitiveType::kDouble)), }, CheckedExprTestCase{ .expr = "StringValue{value: 'test'}", .expected_result_type = AstType(ast_internal::PrimitiveTypeWrapper( ast_internal::PrimitiveType::kString)), }, CheckedExprTestCase{ .expr = "BytesValue{value: b'test'}", .expected_result_type = AstType(ast_internal::PrimitiveTypeWrapper( ast_internal::PrimitiveType::kBytes)), }, CheckedExprTestCase{ .expr = "Duration{seconds: 10, nanos: 11}", .expected_result_type = AstType(ast_internal::WellKnownType::kDuration), }, CheckedExprTestCase{ .expr = "Timestamp{seconds: 10, nanos: 11}", .expected_result_type = AstType(ast_internal::WellKnownType::kTimestamp), }, CheckedExprTestCase{ .expr = "Struct{fields: {'key': 'value'}}", .expected_result_type = AstType(ast_internal::MapType( std::make_unique<AstType>(ast_internal::PrimitiveType::kString), std::make_unique<AstType>(ast_internal::DynamicType()))), }, CheckedExprTestCase{ .expr = "ListValue{values: [1, 2, 3]}", .expected_result_type = AstType(ast_internal::ListType( std::make_unique<AstType>(ast_internal::DynamicType()))), }, CheckedExprTestCase{ .expr = R"cel( Any{ type_url:'type.googleapis.com/google.protobuf.Int32Value', value: b'' })cel", .expected_result_type = AstType(ast_internal::WellKnownType::kAny), })); class GenericMessagesTest : public testing::TestWithParam<CheckedExprTestCase> { }; TEST_P(GenericMessagesTest, TypeChecksProto3) { const CheckedExprTestCase& test_case = GetParam(); google::protobuf::Arena arena; TypeCheckEnv env; env.AddTypeProvider(std::make_unique<cel::extensions::ProtoTypeReflector>()); env.set_container("google.api.expr.test.v1.proto3"); google::protobuf::LinkMessageReflection<testpb3::TestAllTypes>(); ASSERT_TRUE(env.InsertVariableIfAbsent(MakeVariableDecl( "test_msg", MessageType(testpb3::TestAllTypes::descriptor())))); ASSERT_THAT(RegisterMinimalBuiltins(&arena, env), IsOk()); TypeCheckerImpl impl(std::move(env)); ASSERT_OK_AND_ASSIGN(auto ast, MakeTestParsedAst(test_case.expr)); ASSERT_OK_AND_ASSIGN(ValidationResult result, impl.Check(std::move(ast))); if (!test_case.error_substring.empty()) { EXPECT_THAT(result.GetIssues(), Contains(IsIssueWithSubstring(Severity::kError, test_case.error_substring))); return; } ASSERT_TRUE(result.IsValid()) << absl::StrJoin(result.GetIssues(), "\n", [](std::string* out, const TypeCheckIssue& issue) { absl::StrAppend(out, issue.message()); }); ASSERT_OK_AND_ASSIGN(std::unique_ptr<Ast> checked_ast, result.ReleaseAst()); const auto& ast_impl = AstImpl::CastFromPublicAst(*checked_ast); EXPECT_THAT(ast_impl.type_map(), Contains(Pair(ast_impl.root_expr().id(), Eq(test_case.expected_result_type)))); } INSTANTIATE_TEST_SUITE_P( TestAllTypesCreation, GenericMessagesTest, ::testing::Values( CheckedExprTestCase{ .expr = "TestAllTypes{not_a_field: 10}", .expected_result_type = AstType(), .error_substring = "undefined field 'not_a_field' not found in " "struct 'google.api.expr.test.v1.proto3.TestAllTypes'"}, CheckedExprTestCase{ .expr = "TestAllTypes{single_int64: 10}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_int64: 'string'}", .expected_result_type = AstType(), .error_substring = "expected type of field 'single_int64' is 'int' but " "provided type is 'string'"}, CheckedExprTestCase{ .expr = "TestAllTypes{single_int32: 10}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_uint64: 10u}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_uint32: 10u}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_sint64: 10}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_sint32: 10}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_fixed64: 10u}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_fixed32: 10u}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_sfixed64: 10}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_sfixed32: 10}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_double: 1.25}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_float: 1.25}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_string: 'string'}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_bool: true}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_bytes: b'string'}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_any: TestAllTypes{single_int64: 10}}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_any: 1}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_any: 'string'}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_any: ['string']}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_duration: duration('1s')}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_timestamp: timestamp(0)}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_struct: {}}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_struct: {'key': 'value'}}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_struct: {1: 2}}", .expected_result_type = AstType(), .error_substring = "expected type of field 'single_struct' is " "'map<string, dyn>' but " "provided type is 'map<int, int>'"}, CheckedExprTestCase{ .expr = "TestAllTypes{list_value: [1, 2, 3]}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{list_value: []}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{list_value: 1}", .expected_result_type = AstType(), .error_substring = "expected type of field 'list_value' is 'list<dyn>' but " "provided type is 'int'"}, CheckedExprTestCase{ .expr = "TestAllTypes{single_int64_wrapper: 1}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_int64_wrapper: null}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_value: null}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_value: 1.0}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_value: 'string'}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_value: {'string': 'string'}}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_value: ['string']}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{repeated_int64: [1, 2, 3]}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{repeated_int64: ['string']}", .expected_result_type = AstType(), .error_substring = "expected type of field 'repeated_int64' is 'list<int>'"}, CheckedExprTestCase{ .expr = "TestAllTypes{map_string_int64: ['string']}", .expected_result_type = AstType(), .error_substring = "expected type of field 'map_string_int64' is " "'map<string, int>'"}, CheckedExprTestCase{ .expr = "TestAllTypes{map_string_int64: {'string': 1}}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_nested_enum: 1}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes{single_nested_enum: TestAllTypes.NestedEnum.BAR}", .expected_result_type = AstType(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes")), }, CheckedExprTestCase{ .expr = "TestAllTypes.NestedEnum.BAR", .expected_result_type = AstType(ast_internal::PrimitiveType::kInt64), }, CheckedExprTestCase{ .expr = "TestAllTypes", .expected_result_type = AstType(std::make_unique<AstType>(ast_internal::MessageType( "google.api.expr.test.v1.proto3.TestAllTypes"))), }, CheckedExprTestCase{ .expr = "TestAllTypes == type(TestAllTypes{})", .expected_result_type = AstType(ast_internal::PrimitiveType::kBool), })); INSTANTIATE_TEST_SUITE_P( TestAllTypesFieldSelection, GenericMessagesTest, ::testing::Values( CheckedExprTestCase{ .expr = "test_msg.not_a_field", .expected_result_type = AstType(), .error_substring = "undefined field 'not_a_field' not found in " "struct 'google.api.expr.test.v1.proto3.TestAllTypes'"}, CheckedExprTestCase{ .expr = "test_msg.single_int64", .expected_result_type = AstType(ast_internal::PrimitiveType::kInt64), }, CheckedExprTestCase{ .expr = "test_msg.single_nested_enum", .expected_result_type = AstType(ast_internal::PrimitiveType::kInt64), }, CheckedExprTestCase{ .expr = "test_msg.single_nested_enum == 1", .expected_result_type = AstType(ast_internal::PrimitiveType::kBool), }, CheckedExprTestCase{ .expr = "test_msg.single_nested_enum == TestAllTypes.NestedEnum.BAR", .expected_result_type = AstType(ast_internal::PrimitiveType::kBool), }, CheckedExprTestCase{ .expr = "has(test_msg.not_a_field)", .expected_result_type = AstType(), .error_substring = "undefined field 'not_a_field' not found in " "struct 'google.api.expr.test.v1.proto3.TestAllTypes'"}, CheckedExprTestCase{ .expr = "has(test_msg.single_int64)", .expected_result_type = AstType(ast_internal::PrimitiveType::kBool), }, CheckedExprTestCase{ .expr = "test_msg.single_int32", .expected_result_type = AstType(ast_internal::PrimitiveType::kInt64), }, CheckedExprTestCase{ .expr = "test_msg.single_uint64", .expected_result_type = AstType(ast_internal::PrimitiveType::kUint64), }, CheckedExprTestCase{ .expr = "test_msg.single_uint32", .expected_result_type = AstType(ast_internal::PrimitiveType::kUint64), }, CheckedExprTestCase{ .expr = "test_msg.single_sint64", .expected_result_type = AstType(ast_internal::PrimitiveType::kInt64), }, CheckedExprTestCase{ .expr = "test_msg.single_sint32", .expected_result_type = AstType(ast_internal::PrimitiveType::kInt64), }, CheckedExprTestCase{ .expr = "test_msg.single_fixed64", .expected_result_type = AstType(ast_internal::PrimitiveType::kUint64), }, CheckedExprTestCase{ .expr = "test_msg.single_fixed32", .expected_result_type = AstType(ast_internal::PrimitiveType::kUint64), }, CheckedExprTestCase{ .expr = "test_msg.single_sfixed64", .expected_result_type = AstType(ast_internal::PrimitiveType::kInt64), }, CheckedExprTestCase{ .expr = "test_msg.single_sfixed32", .expected_result_type = AstType(ast_internal::PrimitiveType::kInt64), }, CheckedExprTestCase{ .expr = "test_msg.single_float", .expected_result_type = AstType(ast_internal::PrimitiveType::kDouble), }, CheckedExprTestCase{ .expr = "test_msg.single_double", .expected_result_type = AstType(ast_internal::PrimitiveType::kDouble), }, CheckedExprTestCase{ .expr = "test_msg.single_string", .expected_result_type = AstType(ast_internal::PrimitiveType::kString), }, CheckedExprTestCase{ .expr = "test_msg.single_bool", .expected_result_type = AstType(ast_internal::PrimitiveType::kBool), }, CheckedExprTestCase{ .expr = "test_msg.single_bytes", .expected_result_type = AstType(ast_internal::PrimitiveType::kBytes), }, CheckedExprTestCase{ .expr = "test_msg.repeated_int32", .expected_result_type = AstType(ast_internal::ListType(std::make_unique<AstType>( ast_internal::PrimitiveType::kInt64))), }, CheckedExprTestCase{ .expr = "test_msg.repeated_string", .expected_result_type = AstType(ast_internal::ListType(std::make_unique<AstType>( ast_internal::PrimitiveType::kString))), }, CheckedExprTestCase{ .expr = "test_msg.map_bool_bool", .expected_result_type = AstType(ast_internal::MapType( std::make_unique<AstType>(ast_internal::PrimitiveType::kBool), std::make_unique<AstType>(ast_internal::PrimitiveType::kBool))), }, CheckedExprTestCase{ .expr = "test_msg.map_bool_bool.field_like_key", .expected_result_type = AstType(), .error_substring = "expression of type 'map<bool, bool>' cannot be the operand" " of a select operation", }, CheckedExprTestCase{ .expr = "test_msg.map_string_int64", .expected_result_type = AstType(ast_internal::MapType( std::make_unique<AstType>(ast_internal::PrimitiveType::kString), std::make_unique<AstType>( ast_internal::PrimitiveType::kInt64))), }, CheckedExprTestCase{ .expr = "test_msg.map_string_int64.field_like_key", .expected_result_type = AstType(ast_internal::PrimitiveType::kInt64), }, CheckedExprTestCase{ .expr = "test_msg.single_duration", .expected_result_type = AstType(ast_internal::WellKnownType::kDuration), }, CheckedExprTestCase{ .expr = "test_msg.single_timestamp", .expected_result_type = AstType(ast_internal::WellKnownType::kTimestamp), }, CheckedExprTestCase{ .expr = "test_msg.single_any", .expected_result_type = AstType(ast_internal::WellKnownType::kAny), }, CheckedExprTestCase{ .expr = "test_msg.single_int64_wrapper", .expected_result_type = AstType(ast_internal::PrimitiveTypeWrapper( ast_internal::PrimitiveType::kInt64)), }, CheckedExprTestCase{ .expr = "test_msg.single_struct", .expected_result_type = AstType(ast_internal::MapType( std::make_unique<AstType>(ast_internal::PrimitiveType::kString), std::make_unique<AstType>(ast_internal::DynamicType()))), }, CheckedExprTestCase{ .expr = "test_msg.list_value", .expected_result_type = AstType(ast_internal::ListType( std::make_unique<AstType>(ast_internal::DynamicType()))), }, CheckedExprTestCase{ .expr = "test_msg.list_value", .expected_result_type = AstType(ast_internal::ListType( std::make_unique<AstType>(ast_internal::DynamicType()))), }, CheckedExprTestCase{ .expr = "NestedTestAllTypes{}.child.child.payload.single_int64", .expected_result_type = AstType(ast_internal::PrimitiveType::kInt64), } )); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/checker/internal/type_checker_impl.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/checker/internal/type_checker_impl_test.cc
4552db5798fb0853b131b783d8875794334fae7f
6341b9aa-dd73-4d54-8e8c-dc99790e9be6
cpp
google/cel-cpp
type_inference_context
checker/internal/type_inference_context.cc
checker/internal/type_inference_context_test.cc
#include "checker/internal/type_inference_context.h" #include <cstddef> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/log/absl_check.h" #include "absl/log/absl_log.h" #include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "absl/types/span.h" #include "common/decl.h" #include "common/type.h" #include "common/type_kind.h" namespace cel::checker_internal { namespace { bool IsWildCardType(Type type) { switch (type.kind()) { case TypeKind::kAny: case TypeKind::kDyn: case TypeKind::kError: return true; default: return false; } } bool IsTypeVar(absl::string_view name) { return absl::StartsWith(name, "T%"); } bool IsUnionType(Type t) { switch (t.kind()) { case TypeKind::kAny: case TypeKind::kBoolWrapper: case TypeKind::kBytesWrapper: case TypeKind::kDyn: case TypeKind::kDoubleWrapper: case TypeKind::kIntWrapper: case TypeKind::kStringWrapper: case TypeKind::kUintWrapper: return true; default: return false; } } bool IsSubsetOf(Type a, Type b) { switch (b.kind()) { case TypeKind::kAny: return true; case TypeKind::kBoolWrapper: return a.IsBool() || a.IsNull(); case TypeKind::kBytesWrapper: return a.IsBytes() || a.IsNull(); case TypeKind::kDoubleWrapper: return a.IsDouble() || a.IsNull(); case TypeKind::kDyn: return true; case TypeKind::kIntWrapper: return a.IsInt() || a.IsNull(); case TypeKind::kStringWrapper: return a.IsString() || a.IsNull(); case TypeKind::kUintWrapper: return a.IsUint() || a.IsNull(); default: return false; } } struct FunctionOverloadInstance { Type result_type; std::vector<Type> param_types; }; FunctionOverloadInstance InstantiateFunctionOverload( TypeInferenceContext& inference_context, const OverloadDecl& ovl) { FunctionOverloadInstance result; result.param_types.reserve(ovl.args().size()); TypeInferenceContext::InstanceMap substitutions; result.result_type = inference_context.InstantiateTypeParams(ovl.result(), substitutions); for (int i = 0; i < ovl.args().size(); ++i) { result.param_types.push_back( inference_context.InstantiateTypeParams(ovl.args()[i], substitutions)); } return result; } bool OccursWithin(absl::string_view var_name, Type t) { if (t.kind() == TypeKind::kTypeParam && t.AsTypeParam()->name() == var_name) { return true; } for (const auto& param : t.GetParameters()) { if (OccursWithin(var_name, param)) { return true; } } return false; } absl::optional<Type> WrapperToPrimitive(const Type& t) { switch (t.kind()) { case TypeKind::kBoolWrapper: return BoolType(); case TypeKind::kBytesWrapper: return BytesType(); case TypeKind::kDoubleWrapper: return DoubleType(); case TypeKind::kStringWrapper: return StringType(); case TypeKind::kIntWrapper: return IntType(); case TypeKind::kUintWrapper: return UintType(); default: return absl::nullopt; } } } Type TypeInferenceContext::InstantiateTypeParams(const Type& type) { InstanceMap substitutions; return InstantiateTypeParams(type, substitutions); } Type TypeInferenceContext::InstantiateTypeParams( const Type& type, absl::flat_hash_map<std::string, absl::string_view>& substitutions) { switch (type.kind()) { case TypeKind::kAny: case TypeKind::kBool: case TypeKind::kBoolWrapper: case TypeKind::kBytes: case TypeKind::kBytesWrapper: case TypeKind::kDouble: case TypeKind::kDoubleWrapper: case TypeKind::kDuration: case TypeKind::kDyn: case TypeKind::kError: case TypeKind::kInt: case TypeKind::kNull: case TypeKind::kString: case TypeKind::kStringWrapper: case TypeKind::kStruct: case TypeKind::kTimestamp: case TypeKind::kUint: case TypeKind::kIntWrapper: case TypeKind::kUintWrapper: return type; case TypeKind::kTypeParam: { absl::string_view name = type.AsTypeParam()->name(); if (IsTypeVar(name)) { return type; } if (auto it = substitutions.find(name); it != substitutions.end()) { return TypeParamType(it->second); } absl::string_view substitution = NewTypeVar(); substitutions[type.AsTypeParam()->name()] = substitution; return TypeParamType(substitution); } case TypeKind::kType: { auto type_type = type.AsType(); auto parameters = type_type->GetParameters(); if (parameters.size() == 1) { Type param = InstantiateTypeParams(parameters[0], substitutions); return TypeType(arena_, param); } else if (parameters.size() > 1) { return ErrorType(); } else { return type; } } case TypeKind::kList: { Type elem = InstantiateTypeParams(type.AsList()->element(), substitutions); return ListType(arena_, elem); } case TypeKind::kMap: { Type key = InstantiateTypeParams(type.AsMap()->key(), substitutions); Type value = InstantiateTypeParams(type.AsMap()->value(), substitutions); return MapType(arena_, key, value); } case TypeKind::kOpaque: { auto opaque_type = type.AsOpaque(); auto parameters = opaque_type->GetParameters(); std::vector<Type> param_instances; param_instances.reserve(parameters.size()); for (int i = 0; i < parameters.size(); ++i) { param_instances.push_back( InstantiateTypeParams(parameters[i], substitutions)); } return OpaqueType(arena_, type.AsOpaque()->name(), param_instances); } default: return ErrorType(); } } bool TypeInferenceContext::IsAssignable(const Type& from, const Type& to) { SubstitutionMap prospective_substitutions; bool result = IsAssignableInternal(from, to, prospective_substitutions); if (result) { UpdateTypeParameterBindings(prospective_substitutions); } return result; } bool TypeInferenceContext::IsAssignableInternal( const Type& from, const Type& to, SubstitutionMap& prospective_substitutions) { Type to_subs = Substitute(to, prospective_substitutions); Type from_subs = Substitute(from, prospective_substitutions); if (to_subs == from_subs) { return true; } if (to_subs.kind() == TypeKind::kTypeParam || from_subs.kind() == TypeKind::kTypeParam) { return IsAssignableWithConstraints(from_subs, to_subs, prospective_substitutions); } if (absl::optional<Type> wrapped_type = WrapperToPrimitive(to_subs); wrapped_type.has_value()) { return IsAssignableInternal(NullType(), from_subs, prospective_substitutions) || IsAssignableInternal(*wrapped_type, from_subs, prospective_substitutions); } if ( to.kind() == TypeKind::kTypeParam && prospective_substitutions.contains(to.AsTypeParam()->name()) && IsUnionType(from_subs) && IsSubsetOf(to_subs, from_subs)) { prospective_substitutions[to.AsTypeParam()->name()] = from_subs; return true; } if (from_subs.kind() == TypeKind::kType && to_subs.kind() == TypeKind::kType) { return true; } if (to_subs.kind() == TypeKind::kEnum && from_subs.kind() == TypeKind::kInt) { return true; } if (IsWildCardType(from_subs) || IsWildCardType(to_subs)) { return true; } if (to_subs.kind() != from_subs.kind() || to_subs.name() != from_subs.name()) { return false; } auto to_params = to_subs.GetParameters(); auto from_params = from_subs.GetParameters(); const auto params_size = to_params.size(); if (params_size != from_params.size()) { return false; } for (size_t i = 0; i < params_size; ++i) { if (!IsAssignableInternal(from_params[i], to_params[i], prospective_substitutions)) { return false; } } return true; } Type TypeInferenceContext::Substitute( const Type& type, const SubstitutionMap& substitutions) const { Type subs = type; while (subs.kind() == TypeKind::kTypeParam) { TypeParamType t = subs.GetTypeParam(); if (auto it = substitutions.find(t.name()); it != substitutions.end()) { subs = it->second; continue; } if (auto it = type_parameter_bindings_.find(t.name()); it != type_parameter_bindings_.end()) { if (it->second.has_value()) { subs = *it->second; continue; } } break; } return subs; } bool TypeInferenceContext::IsAssignableWithConstraints( const Type& from, const Type& to, SubstitutionMap& prospective_substitutions) { if (to.kind() == TypeKind::kTypeParam && from.kind() == TypeKind::kTypeParam) { if (to.AsTypeParam()->name() != from.AsTypeParam()->name()) { prospective_substitutions[from.AsTypeParam()->name()] = to; } return true; } if (to.kind() == TypeKind::kTypeParam) { absl::string_view name = to.AsTypeParam()->name(); if (!OccursWithin(name, from)) { prospective_substitutions[to.AsTypeParam()->name()] = from; return true; } } if (from.kind() == TypeKind::kTypeParam) { absl::string_view name = from.AsTypeParam()->name(); if (!OccursWithin(name, to)) { prospective_substitutions[from.AsTypeParam()->name()] = to; return true; } } if (IsWildCardType(from) || IsWildCardType(to)) { return true; } return false; } absl::optional<TypeInferenceContext::OverloadResolution> TypeInferenceContext::ResolveOverload(const FunctionDecl& decl, absl::Span<const Type> argument_types, bool is_receiver) { absl::optional<Type> result_type; std::vector<OverloadDecl> matching_overloads; for (const auto& ovl : decl.overloads()) { if (ovl.member() != is_receiver || argument_types.size() != ovl.args().size()) { continue; } auto call_type_instance = InstantiateFunctionOverload(*this, ovl); ABSL_DCHECK_EQ(argument_types.size(), call_type_instance.param_types.size()); bool is_match = true; SubstitutionMap prospective_substitutions; for (int i = 0; i < argument_types.size(); ++i) { if (!IsAssignableInternal(argument_types[i], call_type_instance.param_types[i], prospective_substitutions)) { is_match = false; break; } } if (is_match) { matching_overloads.push_back(ovl); UpdateTypeParameterBindings(prospective_substitutions); if (!result_type.has_value()) { result_type = call_type_instance.result_type; } else { if (!TypeEquivalent(*result_type, call_type_instance.result_type)) { result_type = DynType(); } } } } if (!result_type.has_value() || matching_overloads.empty()) { return absl::nullopt; } return OverloadResolution{ .result_type = FullySubstitute(*result_type, false), .overloads = std::move(matching_overloads), }; } void TypeInferenceContext::UpdateTypeParameterBindings( const SubstitutionMap& prospective_substitutions) { if (prospective_substitutions.empty()) { return; } for (auto iter = prospective_substitutions.begin(); iter != prospective_substitutions.end(); ++iter) { if (auto binding_iter = type_parameter_bindings_.find(iter->first); binding_iter != type_parameter_bindings_.end()) { binding_iter->second = iter->second; } else { ABSL_LOG(WARNING) << "Uninstantiated type parameter: " << iter->first; } } } bool TypeInferenceContext::TypeEquivalent(const Type& a, const Type& b) { return a == b; } Type TypeInferenceContext::FullySubstitute(const Type& type, bool free_to_dyn) const { switch (type.kind()) { case TypeKind::kTypeParam: { Type subs = Substitute(type, {}); if (subs.kind() == TypeKind::kTypeParam) { if (free_to_dyn) { return DynType(); } return subs; } return FullySubstitute(subs, free_to_dyn); } case TypeKind::kType: { if (type.AsType()->GetParameters().empty()) { return type; } Type param = FullySubstitute(type.AsType()->GetType(), free_to_dyn); return TypeType(arena_, param); } case TypeKind::kList: { Type elem = FullySubstitute(type.AsList()->GetElement(), free_to_dyn); return ListType(arena_, elem); } case TypeKind::kMap: { Type key = FullySubstitute(type.AsMap()->GetKey(), free_to_dyn); Type value = FullySubstitute(type.AsMap()->GetValue(), free_to_dyn); return MapType(arena_, key, value); } case TypeKind::kOpaque: { std::vector<Type> types; for (const auto& param : type.AsOpaque()->GetParameters()) { types.push_back(FullySubstitute(param, free_to_dyn)); } return OpaqueType(arena_, type.AsOpaque()->name(), types); } default: return type; } } }
#include "checker/internal/type_inference_context.h" #include <utility> #include <vector> #include "absl/log/absl_check.h" #include "absl/types/optional.h" #include "common/decl.h" #include "common/type.h" #include "common/type_kind.h" #include "internal/testing.h" #include "google/protobuf/arena.h" namespace cel::checker_internal { namespace { using ::testing::ElementsAre; using ::testing::IsEmpty; using ::testing::SafeMatcherCast; using ::testing::SizeIs; MATCHER_P(IsTypeParam, param, "") { const Type& got = arg; if (got.kind() != TypeKind::kTypeParam) { return false; } TypeParamType type = got.GetTypeParam(); return type.name() == param; } MATCHER_P(IsListType, elems_matcher, "") { const Type& got = arg; if (got.kind() != TypeKind::kList) { return false; } ListType type = got.GetList(); Type elem = type.element(); return SafeMatcherCast<Type>(elems_matcher) .MatchAndExplain(elem, result_listener); } MATCHER_P2(IsMapType, key_matcher, value_matcher, "") { const Type& got = arg; if (got.kind() != TypeKind::kMap) { return false; } MapType type = got.GetMap(); Type key = type.key(); Type value = type.value(); return SafeMatcherCast<Type>(key_matcher) .MatchAndExplain(key, result_listener) && SafeMatcherCast<Type>(value_matcher) .MatchAndExplain(value, result_listener); } MATCHER_P(IsTypeKind, kind, "") { const Type& got = arg; TypeKind want_kind = kind; if (got.kind() == want_kind) { return true; } *result_listener << "got: " << TypeKindToString(got.kind()); *result_listener << "\n"; *result_listener << "wanted: " << TypeKindToString(want_kind); return false; } MATCHER_P(IsTypeType, matcher, "") { const Type& got = arg; if (got.kind() != TypeKind::kType) { return false; } TypeType type_type = got.GetType(); if (type_type.GetParameters().size() != 1) { return false; } return SafeMatcherCast<Type>(matcher).MatchAndExplain(got.GetParameters()[0], result_listener); } TEST(TypeInferenceContextTest, InstantiateTypeParams) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); Type type = context.InstantiateTypeParams(TypeParamType("MyType")); EXPECT_THAT(type, IsTypeParam("T%1")); Type type2 = context.InstantiateTypeParams(TypeParamType("MyType")); EXPECT_THAT(type2, IsTypeParam("T%2")); } TEST(TypeInferenceContextTest, InstantiateTypeParamsWithSubstitutions) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); TypeInferenceContext::InstanceMap instance_map; Type type = context.InstantiateTypeParams(TypeParamType("MyType"), instance_map); EXPECT_THAT(type, IsTypeParam("T%1")); Type type2 = context.InstantiateTypeParams(TypeParamType("MyType"), instance_map); EXPECT_THAT(type2, IsTypeParam("T%1")); } TEST(TypeInferenceContextTest, InstantiateTypeParamsUnparameterized) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); Type type = context.InstantiateTypeParams(IntType()); EXPECT_TRUE(type.IsInt()); } TEST(TypeInferenceContextTest, InstantiateTypeParamsList) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); Type list_type = ListType(&arena, TypeParamType("MyType")); Type type = context.InstantiateTypeParams(list_type); EXPECT_THAT(type, IsListType(IsTypeParam("T%1"))); } TEST(TypeInferenceContextTest, InstantiateTypeParamsListPrimitive) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); Type list_type = ListType(&arena, IntType()); Type type = context.InstantiateTypeParams(list_type); EXPECT_THAT(type, IsListType(IsTypeKind(TypeKind::kInt))); } TEST(TypeInferenceContextTest, InstantiateTypeParamsMap) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); Type map_type = MapType(&arena, TypeParamType("K"), TypeParamType("V")); Type type = context.InstantiateTypeParams(map_type); EXPECT_THAT(type, IsMapType(IsTypeParam("T%1"), IsTypeParam("T%2"))); } TEST(TypeInferenceContextTest, InstantiateTypeParamsMapSameParam) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); Type map_type = MapType(&arena, TypeParamType("E"), TypeParamType("E")); Type type = context.InstantiateTypeParams(map_type); EXPECT_THAT(type, IsMapType(IsTypeParam("T%1"), IsTypeParam("T%1"))); } TEST(TypeInferenceContextTest, InstantiateTypeParamsMapPrimitive) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); Type map_type = MapType(&arena, StringType(), IntType()); Type type = context.InstantiateTypeParams(map_type); EXPECT_THAT(type, IsMapType(IsTypeKind(TypeKind::kString), IsTypeKind(TypeKind::kInt))); } TEST(TypeInferenceContextTest, InstantiateTypeParamsType) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); Type type_type = TypeType(&arena, TypeParamType("T")); Type type = context.InstantiateTypeParams(type_type); EXPECT_THAT(type, IsTypeType(IsTypeParam("T%1"))); } TEST(TypeInferenceContextTest, InstantiateTypeParamsTypeEmpty) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); Type type_type = TypeType(); Type type = context.InstantiateTypeParams(type_type); EXPECT_THAT(type, IsTypeKind(TypeKind::kType)); EXPECT_THAT(type.AsType()->GetParameters(), IsEmpty()); } TEST(TypeInferenceContextTest, InstantiateTypeParamsOpaque) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); std::vector<Type> parameters = {TypeParamType("T"), IntType(), TypeParamType("U"), TypeParamType("T")}; Type type_type = OpaqueType(&arena, "MyTuple", parameters); Type type = context.InstantiateTypeParams(type_type); ASSERT_THAT(type, IsTypeKind(TypeKind::kOpaque)); EXPECT_EQ(type.AsOpaque()->name(), "MyTuple"); EXPECT_THAT(type.AsOpaque()->GetParameters(), ElementsAre(IsTypeParam("T%1"), IsTypeKind(TypeKind::kInt), IsTypeParam("T%2"), IsTypeParam("T%1"))); } TEST(TypeInferenceContextTest, OpaqueTypeAssignable) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); std::vector<Type> parameters = {TypeParamType("T"), IntType()}; Type type_type = OpaqueType(&arena, "MyTuple", parameters); Type type = context.InstantiateTypeParams(type_type); ASSERT_THAT(type, IsTypeKind(TypeKind::kOpaque)); EXPECT_TRUE(context.IsAssignable(type, type)); } TEST(TypeInferenceContextTest, WrapperTypeAssignable) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); EXPECT_TRUE(context.IsAssignable(StringType(), StringWrapperType())); EXPECT_TRUE(context.IsAssignable(NullType(), StringWrapperType())); } TEST(TypeInferenceContextTest, MismatchedTypeNotAssignable) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); EXPECT_FALSE(context.IsAssignable(IntType(), StringWrapperType())); } TEST(TypeInferenceContextTest, OverloadResolution) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); ASSERT_OK_AND_ASSIGN( auto decl, MakeFunctionDecl( "foo", MakeOverloadDecl("foo_int_int", IntType(), IntType(), IntType()), MakeOverloadDecl("foo_double_double", DoubleType(), DoubleType(), DoubleType()))); auto resolution = context.ResolveOverload(decl, {IntType(), IntType()}, false); ASSERT_TRUE(resolution.has_value()); EXPECT_THAT(resolution->result_type, IsTypeKind(TypeKind::kInt)); EXPECT_THAT(resolution->overloads, SizeIs(1)); } TEST(TypeInferenceContextTest, MultipleOverloadsResultTypeDyn) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); ASSERT_OK_AND_ASSIGN( auto decl, MakeFunctionDecl( "foo", MakeOverloadDecl("foo_int_int", IntType(), IntType(), IntType()), MakeOverloadDecl("foo_double_double", DoubleType(), DoubleType(), DoubleType()))); auto resolution = context.ResolveOverload(decl, {DynType(), DynType()}, false); ASSERT_TRUE(resolution.has_value()); EXPECT_THAT(resolution->result_type, IsTypeKind(TypeKind::kDyn)); EXPECT_THAT(resolution->overloads, SizeIs(2)); } MATCHER_P(IsOverloadDecl, name, "") { const OverloadDecl& got = arg; return got.id() == name; } TEST(TypeInferenceContextTest, ResolveOverloadBasic) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); ASSERT_OK_AND_ASSIGN( FunctionDecl decl, MakeFunctionDecl( "_+_", MakeOverloadDecl("add_int", IntType(), IntType(), IntType()), MakeOverloadDecl("add_double", DoubleType(), DoubleType(), DoubleType()))); absl::optional<TypeInferenceContext::OverloadResolution> resolution = context.ResolveOverload(decl, {IntType(), IntType()}, false); ASSERT_TRUE(resolution.has_value()); EXPECT_THAT(resolution->result_type, IsTypeKind(TypeKind::kInt)); EXPECT_THAT(resolution->overloads, ElementsAre(IsOverloadDecl("add_int"))); } TEST(TypeInferenceContextTest, ResolveOverloadFails) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); ASSERT_OK_AND_ASSIGN( FunctionDecl decl, MakeFunctionDecl( "_+_", MakeOverloadDecl("add_int", IntType(), IntType(), IntType()), MakeOverloadDecl("add_double", DoubleType(), DoubleType(), DoubleType()))); absl::optional<TypeInferenceContext::OverloadResolution> resolution = context.ResolveOverload(decl, {IntType(), DoubleType()}, false); ASSERT_FALSE(resolution.has_value()); } TEST(TypeInferenceContextTest, ResolveOverloadWithParamsNoMatch) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); ASSERT_OK_AND_ASSIGN( FunctionDecl decl, MakeFunctionDecl( "_==_", MakeOverloadDecl("equals", BoolType(), TypeParamType("A"), TypeParamType("A")))); absl::optional<TypeInferenceContext::OverloadResolution> resolution = context.ResolveOverload(decl, {IntType(), DoubleType()}, false); ASSERT_FALSE(resolution.has_value()); } TEST(TypeInferenceContextTest, ResolveOverloadWithMixedParamsMatch) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); Type list_of_a = ListType(&arena, TypeParamType("A")); ASSERT_OK_AND_ASSIGN( FunctionDecl decl, MakeFunctionDecl( "_==_", MakeOverloadDecl("equals", BoolType(), TypeParamType("A"), TypeParamType("A")))); absl::optional<TypeInferenceContext::OverloadResolution> resolution = context.ResolveOverload(decl, {list_of_a, list_of_a}, false); ASSERT_TRUE(resolution.has_value()) << context.DebugString(); } TEST(TypeInferenceContextTest, ResolveOverloadWithMixedParamsMatch2) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); Type list_of_a = ListType(&arena, TypeParamType("A")); Type list_of_int = ListType(&arena, IntType()); ASSERT_OK_AND_ASSIGN( FunctionDecl decl, MakeFunctionDecl( "_==_", MakeOverloadDecl("equals", BoolType(), TypeParamType("A"), TypeParamType("A")))); absl::optional<TypeInferenceContext::OverloadResolution> resolution = context.ResolveOverload(decl, {list_of_a, list_of_int}, false); ASSERT_TRUE(resolution.has_value()) << context.DebugString(); EXPECT_THAT(resolution->overloads, ElementsAre(IsOverloadDecl("equals"))); } TEST(TypeInferenceContextTest, ResolveOverloadWithParamsMatches) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); ASSERT_OK_AND_ASSIGN( FunctionDecl decl, MakeFunctionDecl( "_==_", MakeOverloadDecl("equals", BoolType(), TypeParamType("A"), TypeParamType("A")))); absl::optional<TypeInferenceContext::OverloadResolution> resolution = context.ResolveOverload(decl, {IntType(), IntType()}, false); ASSERT_TRUE(resolution.has_value()); EXPECT_TRUE(resolution->result_type.IsBool()); EXPECT_THAT(resolution->overloads, ElementsAre(IsOverloadDecl("equals"))); } TEST(TypeInferenceContextTest, ResolveOverloadWithNestedParamsMatch) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); Type list_of_a = ListType(&arena, TypeParamType("A")); ASSERT_OK_AND_ASSIGN( FunctionDecl decl, MakeFunctionDecl("_+_", MakeOverloadDecl("add_list", list_of_a, list_of_a, list_of_a))); Type list_of_a_instance = context.InstantiateTypeParams(list_of_a); absl::optional<TypeInferenceContext::OverloadResolution> resolution = context.ResolveOverload( decl, {list_of_a_instance, ListType(&arena, IntType())}, false); ASSERT_TRUE(resolution.has_value()); EXPECT_TRUE(resolution->result_type.IsList()); EXPECT_THAT( context.FinalizeType(resolution->result_type).AsList()->GetElement(), IsTypeKind(TypeKind::kInt)) << context.DebugString(); EXPECT_THAT(resolution->overloads, ElementsAre(IsOverloadDecl("add_list"))); absl::optional<TypeInferenceContext::OverloadResolution> resolution2 = context.ResolveOverload( decl, {ListType(&arena, IntType()), list_of_a_instance}, false); ASSERT_TRUE(resolution2.has_value()); EXPECT_TRUE(resolution2->result_type.IsList()); EXPECT_THAT( context.FinalizeType(resolution2->result_type).AsList()->GetElement(), IsTypeKind(TypeKind::kInt)) << context.DebugString(); EXPECT_THAT(resolution2->overloads, ElementsAre(IsOverloadDecl("add_list"))); } TEST(TypeInferenceContextTest, ResolveOverloadWithNestedParamsNoMatch) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); Type list_of_a = ListType(&arena, TypeParamType("A")); ASSERT_OK_AND_ASSIGN( FunctionDecl decl, MakeFunctionDecl("_+_", MakeOverloadDecl("add_list", list_of_a, list_of_a, list_of_a))); Type list_of_a_instance = context.InstantiateTypeParams(list_of_a); absl::optional<TypeInferenceContext::OverloadResolution> resolution = context.ResolveOverload(decl, {list_of_a_instance, IntType()}, false); EXPECT_FALSE(resolution.has_value()); } TEST(TypeInferenceContextTest, InferencesAccumulate) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); Type list_of_a = ListType(&arena, TypeParamType("A")); ASSERT_OK_AND_ASSIGN( FunctionDecl decl, MakeFunctionDecl("_+_", MakeOverloadDecl("add_list", list_of_a, list_of_a, list_of_a))); Type list_of_a_instance = context.InstantiateTypeParams(list_of_a); absl::optional<TypeInferenceContext::OverloadResolution> resolution1 = context.ResolveOverload(decl, {list_of_a_instance, list_of_a_instance}, false); ASSERT_TRUE(resolution1.has_value()); EXPECT_TRUE(resolution1->result_type.IsList()); absl::optional<TypeInferenceContext::OverloadResolution> resolution2 = context.ResolveOverload( decl, {resolution1->result_type, ListType(&arena, IntType())}, false); ASSERT_TRUE(resolution2.has_value()); EXPECT_TRUE(resolution2->result_type.IsList()); EXPECT_THAT( context.FinalizeType(resolution2->result_type).AsList()->GetElement(), IsTypeKind(TypeKind::kInt)); EXPECT_THAT(resolution2->overloads, ElementsAre(IsOverloadDecl("add_list"))); } TEST(TypeInferenceContextTest, DebugString) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); Type list_of_a = ListType(&arena, TypeParamType("A")); Type list_of_int = ListType(&arena, IntType()); ASSERT_OK_AND_ASSIGN( FunctionDecl decl, MakeFunctionDecl("_+_", MakeOverloadDecl("add_list", list_of_a, list_of_a, list_of_a))); absl::optional<TypeInferenceContext::OverloadResolution> resolution = context.ResolveOverload(decl, {list_of_int, list_of_int}, false); ASSERT_TRUE(resolution.has_value()); EXPECT_TRUE(resolution->result_type.IsList()); EXPECT_EQ(context.DebugString(), "type_parameter_bindings: T%1 -> int"); } struct TypeInferenceContextWrapperTypesTestCase { Type wrapper_type; Type wrapped_primitive_type; }; class TypeInferenceContextWrapperTypesTest : public ::testing::TestWithParam< TypeInferenceContextWrapperTypesTestCase> { public: TypeInferenceContextWrapperTypesTest() : context_(&arena_) { auto decl = MakeFunctionDecl( "_?_:_", MakeOverloadDecl("ternary", TypeParamType("A"), BoolType(), TypeParamType("A"), TypeParamType("A"))); ABSL_CHECK_OK(decl.status()); ternary_decl_ = *std::move(decl); } protected: google::protobuf::Arena arena_; TypeInferenceContext context_{&arena_}; FunctionDecl ternary_decl_; }; TEST_P(TypeInferenceContextWrapperTypesTest, ResolvePrimitiveArg) { const TypeInferenceContextWrapperTypesTestCase& test_case = GetParam(); absl::optional<TypeInferenceContext::OverloadResolution> resolution = context_.ResolveOverload(ternary_decl_, {BoolType(), test_case.wrapper_type, test_case.wrapped_primitive_type}, false); ASSERT_TRUE(resolution.has_value()); EXPECT_THAT(context_.FinalizeType(resolution->result_type), IsTypeKind(test_case.wrapper_type.kind())) << context_.DebugString(); EXPECT_THAT(resolution->overloads, ElementsAre(IsOverloadDecl("ternary"))); } TEST_P(TypeInferenceContextWrapperTypesTest, ResolveWrapperArg) { const TypeInferenceContextWrapperTypesTestCase& test_case = GetParam(); absl::optional<TypeInferenceContext::OverloadResolution> resolution = context_.ResolveOverload( ternary_decl_, {BoolType(), test_case.wrapper_type, test_case.wrapper_type}, false); ASSERT_TRUE(resolution.has_value()); EXPECT_THAT(context_.FinalizeType(resolution->result_type), IsTypeKind(test_case.wrapper_type.kind())) << context_.DebugString(); EXPECT_THAT(resolution->overloads, ElementsAre(IsOverloadDecl("ternary"))); } TEST_P(TypeInferenceContextWrapperTypesTest, ResolveNullArg) { const TypeInferenceContextWrapperTypesTestCase& test_case = GetParam(); absl::optional<TypeInferenceContext::OverloadResolution> resolution = context_.ResolveOverload(ternary_decl_, {BoolType(), test_case.wrapper_type, NullType()}, false); ASSERT_TRUE(resolution.has_value()); EXPECT_THAT(context_.FinalizeType(resolution->result_type), IsTypeKind(test_case.wrapper_type.kind())) << context_.DebugString(); EXPECT_THAT(resolution->overloads, ElementsAre(IsOverloadDecl("ternary"))); } TEST_P(TypeInferenceContextWrapperTypesTest, NullWidens) { const TypeInferenceContextWrapperTypesTestCase& test_case = GetParam(); absl::optional<TypeInferenceContext::OverloadResolution> resolution = context_.ResolveOverload(ternary_decl_, {BoolType(), NullType(), test_case.wrapper_type}, false); ASSERT_TRUE(resolution.has_value()); EXPECT_THAT(context_.FinalizeType(resolution->result_type), IsTypeKind(test_case.wrapper_type.kind())) << context_.DebugString(); EXPECT_THAT(resolution->overloads, ElementsAre(IsOverloadDecl("ternary"))); } TEST_P(TypeInferenceContextWrapperTypesTest, PrimitiveWidens) { const TypeInferenceContextWrapperTypesTestCase& test_case = GetParam(); absl::optional<TypeInferenceContext::OverloadResolution> resolution = context_.ResolveOverload(ternary_decl_, {BoolType(), test_case.wrapped_primitive_type, test_case.wrapper_type}, false); ASSERT_TRUE(resolution.has_value()); EXPECT_THAT(context_.FinalizeType(resolution->result_type), IsTypeKind(test_case.wrapper_type.kind())) << context_.DebugString(); EXPECT_THAT(resolution->overloads, ElementsAre(IsOverloadDecl("ternary"))); } INSTANTIATE_TEST_SUITE_P( Types, TypeInferenceContextWrapperTypesTest, ::testing::Values( TypeInferenceContextWrapperTypesTestCase{IntWrapperType(), IntType()}, TypeInferenceContextWrapperTypesTestCase{UintWrapperType(), UintType()}, TypeInferenceContextWrapperTypesTestCase{DoubleWrapperType(), DoubleType()}, TypeInferenceContextWrapperTypesTestCase{StringWrapperType(), StringType()}, TypeInferenceContextWrapperTypesTestCase{BytesWrapperType(), BytesType()}, TypeInferenceContextWrapperTypesTestCase{BoolWrapperType(), BoolType()}, TypeInferenceContextWrapperTypesTestCase{DynType(), IntType()})); TEST(TypeInferenceContextTest, ResolveOverloadWithUnionTypePromotion) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); ASSERT_OK_AND_ASSIGN( FunctionDecl decl, MakeFunctionDecl( "_?_:_", MakeOverloadDecl("ternary", TypeParamType("A"), BoolType(), TypeParamType("A"), TypeParamType("A")))); absl::optional<TypeInferenceContext::OverloadResolution> resolution = context.ResolveOverload(decl, {BoolType(), NullType(), IntWrapperType()}, false); ASSERT_TRUE(resolution.has_value()); EXPECT_THAT(context.FinalizeType(resolution->result_type), IsTypeKind(TypeKind::kIntWrapper)) << context.DebugString(); EXPECT_THAT(resolution->overloads, ElementsAre(IsOverloadDecl("ternary"))); } TEST(TypeInferenceContextTest, ResolveOverloadWithTypeType) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); ASSERT_OK_AND_ASSIGN( FunctionDecl decl, MakeFunctionDecl("type", MakeOverloadDecl("to_type", TypeType(&arena, TypeParamType("A")), TypeParamType("A")))); absl::optional<TypeInferenceContext::OverloadResolution> resolution = context.ResolveOverload(decl, {StringType()}, false); ASSERT_TRUE(resolution.has_value()); auto result_type = context.FinalizeType(resolution->result_type); ASSERT_THAT(result_type, IsTypeKind(TypeKind::kType)); EXPECT_THAT(result_type.AsType()->GetParameters(), ElementsAre(IsTypeKind(TypeKind::kString))); EXPECT_THAT(resolution->overloads, ElementsAre(IsOverloadDecl("to_type"))); } TEST(TypeInferenceContextTest, ResolveOverloadWithInferredTypeType) { google::protobuf::Arena arena; TypeInferenceContext context(&arena); ASSERT_OK_AND_ASSIGN( FunctionDecl to_type_decl, MakeFunctionDecl("type", MakeOverloadDecl("to_type", TypeType(&arena, TypeParamType("A")), TypeParamType("A")))); ASSERT_OK_AND_ASSIGN( FunctionDecl equals_decl, MakeFunctionDecl("_==_", MakeOverloadDecl("equals", BoolType(), TypeParamType("A"), TypeParamType("A")))); absl::optional<TypeInferenceContext::OverloadResolution> resolution = context.ResolveOverload(to_type_decl, {StringType()}, false); ASSERT_TRUE(resolution.has_value()); auto lhs_result_type = resolution->result_type; ASSERT_THAT(lhs_result_type, IsTypeKind(TypeKind::kType)); resolution = context.ResolveOverload(to_type_decl, {IntType()}, false); ASSERT_TRUE(resolution.has_value()); auto rhs_result_type = resolution->result_type; ASSERT_THAT(rhs_result_type, IsTypeKind(TypeKind::kType)); resolution = context.ResolveOverload( equals_decl, {rhs_result_type, lhs_result_type}, false); ASSERT_TRUE(resolution.has_value()); auto result_type = context.FinalizeType(resolution->result_type); ASSERT_THAT(result_type, IsTypeKind(TypeKind::kBool)); auto inferred_lhs = context.FinalizeType(lhs_result_type); auto inferred_rhs = context.FinalizeType(rhs_result_type); ASSERT_THAT(inferred_rhs, IsTypeKind(TypeKind::kType)); ASSERT_THAT(inferred_lhs, IsTypeKind(TypeKind::kType)); ASSERT_THAT(inferred_lhs.AsType()->GetParameters(), ElementsAre(IsTypeKind(TypeKind::kString))); ASSERT_THAT(inferred_rhs.AsType()->GetParameters(), ElementsAre(IsTypeKind(TypeKind::kInt))); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/checker/internal/type_inference_context.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/checker/internal/type_inference_context_test.cc
4552db5798fb0853b131b783d8875794334fae7f
94c058e2-6312-47f4-a0e8-a7bfebcf8345
cpp
google/cel-cpp
namespace_generator
checker/internal/namespace_generator.cc
checker/internal/namespace_generator_test.cc
#include "checker/internal/namespace_generator.h" #include <algorithm> #include <string> #include <utility> #include <vector> #include "absl/functional/function_ref.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "internal/lexis.h" namespace cel::checker_internal { namespace { bool FieldSelectInterpretationCandidates( absl::string_view prefix, absl::Span<const std::string> partly_qualified_name, absl::FunctionRef<bool(absl::string_view, int)> callback) { for (int i = 0; i < partly_qualified_name.size(); ++i) { std::string buf; int count = partly_qualified_name.size() - i; auto end_idx = count - 1; auto ident = absl::StrJoin(partly_qualified_name.subspan(0, count), "."); absl::string_view candidate = ident; if (absl::StartsWith(candidate, ".")) { candidate = candidate.substr(1); } if (!prefix.empty()) { buf = absl::StrCat(prefix, ".", candidate); candidate = buf; } if (!callback(candidate, end_idx)) { return false; } } return true; } } absl::StatusOr<NamespaceGenerator> NamespaceGenerator::Create( absl::string_view container) { std::vector<std::string> candidates; if (container.empty()) { return NamespaceGenerator(std::move(candidates)); } if (absl::StartsWith(container, ".")) { return absl::InvalidArgumentError("container must not start with a '.'"); } std::string prefix; for (auto segment : absl::StrSplit(container, '.')) { if (!internal::LexisIsIdentifier(segment)) { return absl::InvalidArgumentError( "container must only contain valid identifier segments"); } if (prefix.empty()) { prefix = segment; } else { absl::StrAppend(&prefix, ".", segment); } candidates.push_back(prefix); } std::reverse(candidates.begin(), candidates.end()); return NamespaceGenerator(std::move(candidates)); } void NamespaceGenerator::GenerateCandidates( absl::string_view unqualified_name, absl::FunctionRef<bool(absl::string_view)> callback) { if (absl::StartsWith(unqualified_name, ".")) { callback(unqualified_name.substr(1)); return; } for (const auto& prefix : candidates_) { std::string candidate = absl::StrCat(prefix, ".", unqualified_name); if (!callback(candidate)) { return; } } callback(unqualified_name); } void NamespaceGenerator::GenerateCandidates( absl::Span<const std::string> partly_qualified_name, absl::FunctionRef<bool(absl::string_view, int)> callback) { if (!partly_qualified_name.empty() && absl::StartsWith(partly_qualified_name[0], ".")) { FieldSelectInterpretationCandidates("", partly_qualified_name, callback); return; } for (const auto& prefix : candidates_) { if (!FieldSelectInterpretationCandidates(prefix, partly_qualified_name, callback)) { return; } } FieldSelectInterpretationCandidates("", partly_qualified_name, callback); } }
#include "checker/internal/namespace_generator.h" #include <string> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "internal/testing.h" namespace cel::checker_internal { namespace { using ::absl_testing::StatusIs; using ::testing::ElementsAre; using ::testing::Pair; TEST(NamespaceGeneratorTest, EmptyContainer) { ASSERT_OK_AND_ASSIGN(auto generator, NamespaceGenerator::Create("")); std::vector<std::string> candidates; generator.GenerateCandidates("foo", [&](absl::string_view candidate) { candidates.push_back(std::string(candidate)); return true; }); EXPECT_THAT(candidates, ElementsAre("foo")); } TEST(NamespaceGeneratorTest, MultipleSegments) { ASSERT_OK_AND_ASSIGN(auto generator, NamespaceGenerator::Create("com.example")); std::vector<std::string> candidates; generator.GenerateCandidates("foo", [&](absl::string_view candidate) { candidates.push_back(std::string(candidate)); return true; }); EXPECT_THAT(candidates, ElementsAre("com.example.foo", "com.foo", "foo")); } TEST(NamespaceGeneratorTest, MultipleSegmentsRootNamespace) { ASSERT_OK_AND_ASSIGN(auto generator, NamespaceGenerator::Create("com.example")); std::vector<std::string> candidates; generator.GenerateCandidates(".foo", [&](absl::string_view candidate) { candidates.push_back(std::string(candidate)); return true; }); EXPECT_THAT(candidates, ElementsAre("foo")); } TEST(NamespaceGeneratorTest, InvalidContainers) { EXPECT_THAT(NamespaceGenerator::Create(".com.example"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(NamespaceGenerator::Create("com..example"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(NamespaceGenerator::Create("com.$example"), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(NamespaceGeneratorTest, MultipleSegmentsSelectInterpretation) { ASSERT_OK_AND_ASSIGN(auto generator, NamespaceGenerator::Create("com.example")); std::vector<std::string> qualified_ident = {"foo", "Bar"}; std::vector<std::pair<std::string, int>> candidates; generator.GenerateCandidates( qualified_ident, [&](absl::string_view candidate, int segment_index) { candidates.push_back(std::pair(std::string(candidate), segment_index)); return true; }); EXPECT_THAT( candidates, ElementsAre(Pair("com.example.foo.Bar", 1), Pair("com.example.foo", 0), Pair("com.foo.Bar", 1), Pair("com.foo", 0), Pair("foo.Bar", 1), Pair("foo", 0))); } TEST(NamespaceGeneratorTest, MultipleSegmentsSelectInterpretationRootNamespace) { ASSERT_OK_AND_ASSIGN(auto generator, NamespaceGenerator::Create("com.example")); std::vector<std::string> qualified_ident = {".foo", "Bar"}; std::vector<std::pair<std::string, int>> candidates; generator.GenerateCandidates( qualified_ident, [&](absl::string_view candidate, int segment_index) { candidates.push_back(std::pair(std::string(candidate), segment_index)); return true; }); EXPECT_THAT(candidates, ElementsAre(Pair("foo.Bar", 1), Pair("foo", 0))); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/checker/internal/namespace_generator.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/checker/internal/namespace_generator_test.cc
4552db5798fb0853b131b783d8875794334fae7f
67126d38-e555-4752-b7c6-e14f7ad54bc5
cpp
google/cel-cpp
test_ast_helpers
checker/internal/test_ast_helpers.cc
checker/internal/test_ast_helpers_test.cc
#include "checker/internal/test_ast_helpers.h" #include <memory> #include <utility> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "common/ast.h" #include "extensions/protobuf/ast_converters.h" #include "internal/status_macros.h" #include "parser/parser.h" namespace cel::checker_internal { using ::cel::extensions::CreateAstFromParsedExpr; using ::google::api::expr::parser::Parse; absl::StatusOr<std::unique_ptr<Ast>> MakeTestParsedAst( absl::string_view expression) { CEL_ASSIGN_OR_RETURN(auto parsed, Parse(expression)); return CreateAstFromParsedExpr(std::move(parsed)); } }
#include "checker/internal/test_ast_helpers.h" #include <memory> #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "base/ast_internal/ast_impl.h" #include "common/ast.h" #include "internal/testing.h" namespace cel::checker_internal { namespace { using ::absl_testing::StatusIs; using ::cel::ast_internal::AstImpl; TEST(MakeTestParsedAstTest, Works) { ASSERT_OK_AND_ASSIGN(std::unique_ptr<Ast> ast, MakeTestParsedAst("123")); AstImpl& impl = AstImpl::CastFromPublicAst(*ast); EXPECT_TRUE(impl.root_expr().has_const_expr()); } TEST(MakeTestParsedAstTest, ForwardsParseError) { EXPECT_THAT(MakeTestParsedAst("%123"), StatusIs(absl::StatusCode::kInvalidArgument)); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/checker/internal/test_ast_helpers.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/checker/internal/test_ast_helpers_test.cc
4552db5798fb0853b131b783d8875794334fae7f
fa3c515e-8091-4bad-ae30-67dfec5081b0
cpp
google/cel-cpp
exercise2
codelab/solutions/exercise2.cc
codelab/exercise2_test.cc
#include "codelab/exercise2.h" #include <memory> #include <string> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "google/protobuf/arena.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "eval/public/activation.h" #include "eval/public/activation_bind_helper.h" #include "eval/public/builtin_func_registrar.h" #include "eval/public/cel_expr_builder_factory.h" #include "eval/public/cel_expression.h" #include "eval/public/cel_options.h" #include "eval/public/cel_value.h" #include "internal/status_macros.h" #include "parser/parser.h" namespace google::api::expr::codelab { namespace { using ::google::api::expr::v1alpha1::ParsedExpr; using ::google::api::expr::parser::Parse; using ::google::api::expr::runtime::Activation; using ::google::api::expr::runtime::BindProtoToActivation; using ::google::api::expr::runtime::CelError; using ::google::api::expr::runtime::CelExpression; using ::google::api::expr::runtime::CelExpressionBuilder; using ::google::api::expr::runtime::CelValue; using ::google::api::expr::runtime::CreateCelExpressionBuilder; using ::google::api::expr::runtime::InterpreterOptions; using ::google::api::expr::runtime::ProtoUnsetFieldOptions; using ::google::api::expr::runtime::RegisterBuiltinFunctions; using ::google::rpc::context::AttributeContext; absl::StatusOr<bool> ParseAndEvaluate(absl::string_view cel_expr, const Activation& activation, google::protobuf::Arena* arena) { CEL_ASSIGN_OR_RETURN(ParsedExpr parsed_expr, Parse(cel_expr)); InterpreterOptions options; std::unique_ptr<CelExpressionBuilder> builder = CreateCelExpressionBuilder(options); CEL_RETURN_IF_ERROR( RegisterBuiltinFunctions(builder->GetRegistry(), options)); CEL_ASSIGN_OR_RETURN(std::unique_ptr<CelExpression> expression_plan, builder->CreateExpression(&parsed_expr.expr(), &parsed_expr.source_info())); CEL_ASSIGN_OR_RETURN(CelValue result, expression_plan->Evaluate(activation, arena)); if (bool value; result.GetValue(&value)) { return value; } else if (const CelError * value; result.GetValue(&value)) { return *value; } else { return absl::InvalidArgumentError(absl::StrCat( "expected 'bool' result got '", result.DebugString(), "'")); } } } absl::StatusOr<bool> ParseAndEvaluate(absl::string_view cel_expr, bool bool_var) { Activation activation; google::protobuf::Arena arena; activation.InsertValue("bool_var", CelValue::CreateBool(bool_var)); return ParseAndEvaluate(cel_expr, activation, &arena); } absl::StatusOr<bool> ParseAndEvaluate(absl::string_view cel_expr, const AttributeContext& context) { Activation activation; google::protobuf::Arena arena; CEL_RETURN_IF_ERROR(BindProtoToActivation( &context, &arena, &activation, ProtoUnsetFieldOptions::kBindDefault)); return ParseAndEvaluate(cel_expr, activation, &arena); } }
#include "codelab/exercise2.h" #include "google/rpc/context/attribute_context.pb.h" #include "internal/testing.h" #include "google/protobuf/text_format.h" namespace google::api::expr::codelab { namespace { using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::google::rpc::context::AttributeContext; using ::google::protobuf::TextFormat; using ::testing::HasSubstr; TEST(Exercise2Var, Simple) { EXPECT_THAT(ParseAndEvaluate("bool_var", false), IsOkAndHolds(false)); EXPECT_THAT(ParseAndEvaluate("bool_var", true), IsOkAndHolds(true)); EXPECT_THAT(ParseAndEvaluate("bool_var || true", false), IsOkAndHolds(true)); EXPECT_THAT(ParseAndEvaluate("bool_var && false", true), IsOkAndHolds(false)); } TEST(Exercise2Var, WrongTypeResultError) { EXPECT_THAT(ParseAndEvaluate("'not a bool'", false), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected 'bool' result got 'string"))); } TEST(Exercise2Context, Simple) { AttributeContext context; ASSERT_TRUE(TextFormat::ParseFromString(R"pb( source { ip: "192.168.28.1" } request { host: "www.example.com" } destination { ip: "192.168.56.1" } )pb", &context)); EXPECT_THAT(ParseAndEvaluate("source.ip == '192.168.28.1'", context), IsOkAndHolds(true)); EXPECT_THAT(ParseAndEvaluate("request.host == 'api.example.com'", context), IsOkAndHolds(false)); EXPECT_THAT(ParseAndEvaluate("request.host == 'www.example.com'", context), IsOkAndHolds(true)); EXPECT_THAT(ParseAndEvaluate("destination.ip != '192.168.56.1'", context), IsOkAndHolds(false)); } TEST(Exercise2Context, WrongTypeResultError) { AttributeContext context; EXPECT_THAT(ParseAndEvaluate("request.host", context), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected 'bool' result got 'string"))); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/codelab/solutions/exercise2.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/codelab/exercise2_test.cc
4552db5798fb0853b131b783d8875794334fae7f
b05f06be-edfe-47f9-b53c-9ba3c2f004b0
cpp
google/cel-cpp
exercise1
codelab/solutions/exercise1.cc
codelab/exercise1_test.cc
#include "codelab/exercise1.h" #include <memory> #include <string> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "google/protobuf/arena.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "eval/public/activation.h" #include "eval/public/builtin_func_registrar.h" #include "eval/public/cel_expr_builder_factory.h" #include "eval/public/cel_expression.h" #include "eval/public/cel_options.h" #include "eval/public/cel_value.h" #include "internal/status_macros.h" #include "parser/parser.h" namespace google::api::expr::codelab { namespace { using ::google::api::expr::v1alpha1::ParsedExpr; using ::google::api::expr::parser::Parse; using ::google::api::expr::runtime::Activation; using ::google::api::expr::runtime::CelExpression; using ::google::api::expr::runtime::CelExpressionBuilder; using ::google::api::expr::runtime::CelValue; using ::google::api::expr::runtime::CreateCelExpressionBuilder; using ::google::api::expr::runtime::InterpreterOptions; using ::google::api::expr::runtime::RegisterBuiltinFunctions; absl::StatusOr<std::string> ConvertResult(const CelValue& value) { if (CelValue::StringHolder inner_value; value.GetValue(&inner_value)) { return std::string(inner_value.value()); } else { return absl::InvalidArgumentError(absl::StrCat( "expected string result got '", CelValue::TypeName(value.type()), "'")); } } } absl::StatusOr<std::string> ParseAndEvaluate(absl::string_view cel_expr) { InterpreterOptions options; std::unique_ptr<CelExpressionBuilder> builder = CreateCelExpressionBuilder(options); CEL_RETURN_IF_ERROR( RegisterBuiltinFunctions(builder->GetRegistry(), options)); ParsedExpr parsed_expr; CEL_ASSIGN_OR_RETURN(parsed_expr, Parse(cel_expr)); google::protobuf::Arena arena; Activation activation; CEL_ASSIGN_OR_RETURN(std::unique_ptr<CelExpression> expression_plan, builder->CreateExpression(&parsed_expr.expr(), &parsed_expr.source_info())); CEL_ASSIGN_OR_RETURN(CelValue result, expression_plan->Evaluate(activation, &arena)); return ConvertResult(result); } }
#include "codelab/exercise1.h" #include "internal/testing.h" namespace google::api::expr::codelab { namespace { using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; TEST(Exercise1, PrintHelloWorld) { EXPECT_THAT(ParseAndEvaluate("'Hello, World!'"), IsOkAndHolds("Hello, World!")); } TEST(Exercise1, WrongTypeResultError) { EXPECT_THAT(ParseAndEvaluate("true"), StatusIs(absl::StatusCode::kInvalidArgument, "expected string result got 'bool'")); } TEST(Exercise1, Conditional) { EXPECT_THAT(ParseAndEvaluate("(1 < 0)? 'Hello, World!' : '¡Hola, Mundo!'"), IsOkAndHolds("¡Hola, Mundo!")); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/codelab/solutions/exercise1.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/codelab/exercise1_test.cc
4552db5798fb0853b131b783d8875794334fae7f
c4a404f6-3ce8-42e1-9890-5427ba37c72f
cpp
google/cel-cpp
reference_resolver
runtime/reference_resolver.cc
runtime/reference_resolver_test.cc
#include "runtime/reference_resolver.h" #include "absl/base/macros.h" #include "absl/log/absl_log.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "common/native_type.h" #include "eval/compiler/qualified_reference_resolver.h" #include "internal/casts.h" #include "internal/status_macros.h" #include "runtime/internal/runtime_friend_access.h" #include "runtime/internal/runtime_impl.h" #include "runtime/runtime.h" #include "runtime/runtime_builder.h" namespace cel { namespace { using ::cel::internal::down_cast; using ::cel::runtime_internal::RuntimeFriendAccess; using ::cel::runtime_internal::RuntimeImpl; absl::StatusOr<RuntimeImpl*> RuntimeImplFromBuilder(RuntimeBuilder& builder) { Runtime& runtime = RuntimeFriendAccess::GetMutableRuntime(builder); if (RuntimeFriendAccess::RuntimeTypeId(runtime) != NativeTypeId::For<RuntimeImpl>()) { return absl::UnimplementedError( "regex precompilation only supported on the default cel::Runtime " "implementation."); } RuntimeImpl& runtime_impl = down_cast<RuntimeImpl&>(runtime); return &runtime_impl; } google::api::expr::runtime::ReferenceResolverOption Convert( ReferenceResolverEnabled enabled) { switch (enabled) { case ReferenceResolverEnabled::kCheckedExpressionOnly: return google::api::expr::runtime::ReferenceResolverOption::kCheckedOnly; case ReferenceResolverEnabled::kAlways: return google::api::expr::runtime::ReferenceResolverOption::kAlways; } ABSL_LOG(FATAL) << "unsupported ReferenceResolverEnabled enumerator: " << static_cast<int>(enabled); } } absl::Status EnableReferenceResolver(RuntimeBuilder& builder, ReferenceResolverEnabled enabled) { CEL_ASSIGN_OR_RETURN(RuntimeImpl * runtime_impl, RuntimeImplFromBuilder(builder)); ABSL_ASSERT(runtime_impl != nullptr); runtime_impl->expr_builder().AddAstTransform( NewReferenceResolverExtension(Convert(enabled))); return absl::OkStatus(); } }
#include "runtime/reference_resolver.h" #include <cstdint> #include <utility> #include "google/api/expr/v1alpha1/checked.pb.h" #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "base/function_adapter.h" #include "common/value.h" #include "extensions/protobuf/runtime_adapter.h" #include "internal/testing.h" #include "parser/parser.h" #include "runtime/activation.h" #include "runtime/managed_value_factory.h" #include "runtime/register_function_helper.h" #include "runtime/runtime_builder.h" #include "runtime/runtime_options.h" #include "runtime/standard_runtime_builder_factory.h" #include "google/protobuf/text_format.h" namespace cel { namespace { using ::cel::extensions::ProtobufRuntimeAdapter; using ::google::api::expr::v1alpha1::CheckedExpr; using ::google::api::expr::v1alpha1::Expr; using ::google::api::expr::v1alpha1::ParsedExpr; using ::google::api::expr::parser::Parse; using ::absl_testing::StatusIs; using ::testing::HasSubstr; TEST(ReferenceResolver, ResolveQualifiedFunctions) { RuntimeOptions options; ASSERT_OK_AND_ASSIGN(RuntimeBuilder builder, CreateStandardRuntimeBuilder(options)); ASSERT_OK( EnableReferenceResolver(builder, ReferenceResolverEnabled::kAlways)); absl::Status status = RegisterHelper<BinaryFunctionAdapter<int64_t, int64_t, int64_t>>:: RegisterGlobalOverload( "com.example.Exp", [](ValueManager& value_factory, int64_t base, int64_t exp) -> int64_t { int64_t result = 1; for (int64_t i = 0; i < exp; ++i) { result *= base; } return result; }, builder.function_registry()); ASSERT_OK(status); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr, Parse("com.example.Exp(2, 3) == 8")); ASSERT_OK_AND_ASSIGN(auto program, ProtobufRuntimeAdapter::CreateProgram( *runtime, parsed_expr)); ManagedValueFactory value_factory(program->GetTypeProvider(), MemoryManagerRef::ReferenceCounting()); Activation activation; ASSERT_OK_AND_ASSIGN(Value value, program->Evaluate(activation, value_factory.get())); ASSERT_TRUE(value->Is<BoolValue>()); EXPECT_TRUE(value.GetBool().NativeValue()); } TEST(ReferenceResolver, ResolveQualifiedFunctionsCheckedOnly) { RuntimeOptions options; ASSERT_OK_AND_ASSIGN(RuntimeBuilder builder, CreateStandardRuntimeBuilder(options)); ASSERT_OK(EnableReferenceResolver( builder, ReferenceResolverEnabled::kCheckedExpressionOnly)); absl::Status status = RegisterHelper<BinaryFunctionAdapter<int64_t, int64_t, int64_t>>:: RegisterGlobalOverload( "com.example.Exp", [](ValueManager& value_factory, int64_t base, int64_t exp) -> int64_t { int64_t result = 1; for (int64_t i = 0; i < exp; ++i) { result *= base; } return result; }, builder.function_registry()); ASSERT_OK(status); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr, Parse("com.example.Exp(2, 3) == 8")); EXPECT_THAT(ProtobufRuntimeAdapter::CreateProgram(*runtime, parsed_expr), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("No overloads provided"))); } constexpr absl::string_view kIdentifierExpression = R"pb( reference_map: { key: 3 value: { name: "com.example.x" } } reference_map: { key: 4 value: { overload_id: "add_int64" } } reference_map: { key: 7 value: { name: "com.example.y" } } type_map: { key: 3 value: { primitive: INT64 } } type_map: { key: 4 value: { primitive: INT64 } } type_map: { key: 7 value: { primitive: INT64 } } source_info: { location: "<input>" line_offsets: 30 positions: { key: 1 value: 0 } positions: { key: 2 value: 3 } positions: { key: 3 value: 11 } positions: { key: 4 value: 14 } positions: { key: 5 value: 16 } positions: { key: 6 value: 19 } positions: { key: 7 value: 27 } } expr: { id: 4 call_expr: { function: "_+_" args: { id: 3 # compilers typically already apply this rewrite, but older saved # expressions might preserve the original parse. select_expr { operand { id: 8 select_expr { operand: { id: 9 ident_expr { name: "com" } } field: "example" } } field: "x" } } args: { id: 7 ident_expr: { name: "com.example.y" } } } })pb"; TEST(ReferenceResolver, ResolveQualifiedIdentifiers) { RuntimeOptions options; ASSERT_OK_AND_ASSIGN(RuntimeBuilder builder, CreateStandardRuntimeBuilder(options)); ASSERT_OK(EnableReferenceResolver( builder, ReferenceResolverEnabled::kCheckedExpressionOnly)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); CheckedExpr checked_expr; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(kIdentifierExpression, &checked_expr)); ASSERT_OK_AND_ASSIGN(auto program, ProtobufRuntimeAdapter::CreateProgram( *runtime, checked_expr)); ManagedValueFactory value_factory(program->GetTypeProvider(), MemoryManagerRef::ReferenceCounting()); Activation activation; activation.InsertOrAssignValue("com.example.x", value_factory.get().CreateIntValue(3)); activation.InsertOrAssignValue("com.example.y", value_factory.get().CreateIntValue(4)); ASSERT_OK_AND_ASSIGN(Value value, program->Evaluate(activation, value_factory.get())); ASSERT_TRUE(value->Is<IntValue>()); EXPECT_EQ(value.GetInt().NativeValue(), 7); } TEST(ReferenceResolver, ResolveQualifiedIdentifiersSkipParseOnly) { RuntimeOptions options; ASSERT_OK_AND_ASSIGN(RuntimeBuilder builder, CreateStandardRuntimeBuilder(options)); ASSERT_OK(EnableReferenceResolver( builder, ReferenceResolverEnabled::kCheckedExpressionOnly)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); CheckedExpr checked_expr; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(kIdentifierExpression, &checked_expr)); Expr unchecked_expr = checked_expr.expr(); ASSERT_OK_AND_ASSIGN(auto program, ProtobufRuntimeAdapter::CreateProgram( *runtime, checked_expr.expr())); ManagedValueFactory value_factory(program->GetTypeProvider(), MemoryManagerRef::ReferenceCounting()); Activation activation; activation.InsertOrAssignValue("com.example.x", value_factory.get().CreateIntValue(3)); activation.InsertOrAssignValue("com.example.y", value_factory.get().CreateIntValue(4)); ASSERT_OK_AND_ASSIGN(Value value, program->Evaluate(activation, value_factory.get())); ASSERT_TRUE(value->Is<ErrorValue>()); EXPECT_THAT(value.GetError().NativeValue(), StatusIs(absl::StatusCode::kUnknown, HasSubstr("\"com\""))); } constexpr absl::string_view kEnumExpr = R"pb( reference_map: { key: 8 value: { name: "google.api.expr.test.v1.proto2.GlobalEnum.GAZ" value: { int64_value: 2 } } } reference_map: { key: 9 value: { overload_id: "equals" } } type_map: { key: 8 value: { primitive: INT64 } } type_map: { key: 9 value: { primitive: BOOL } } type_map: { key: 10 value: { primitive: INT64 } } source_info: { location: "<input>" line_offsets: 1 line_offsets: 64 line_offsets: 77 positions: { key: 1 value: 13 } positions: { key: 2 value: 19 } positions: { key: 3 value: 23 } positions: { key: 4 value: 28 } positions: { key: 5 value: 33 } positions: { key: 6 value: 36 } positions: { key: 7 value: 43 } positions: { key: 8 value: 54 } positions: { key: 9 value: 59 } positions: { key: 10 value: 62 } } expr: { id: 9 call_expr: { function: "_==_" args: { id: 8 ident_expr: { name: "google.api.expr.test.v1.proto2.GlobalEnum.GAZ" } } args: { id: 10 const_expr: { int64_value: 2 } } } })pb"; TEST(ReferenceResolver, ResolveEnumConstants) { RuntimeOptions options; ASSERT_OK_AND_ASSIGN(RuntimeBuilder builder, CreateStandardRuntimeBuilder(options)); ASSERT_OK(EnableReferenceResolver( builder, ReferenceResolverEnabled::kCheckedExpressionOnly)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); CheckedExpr checked_expr; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(kEnumExpr, &checked_expr)); ASSERT_OK_AND_ASSIGN(auto program, ProtobufRuntimeAdapter::CreateProgram( *runtime, checked_expr)); ManagedValueFactory value_factory(program->GetTypeProvider(), MemoryManagerRef::ReferenceCounting()); Activation activation; ASSERT_OK_AND_ASSIGN(Value value, program->Evaluate(activation, value_factory.get())); ASSERT_TRUE(value->Is<BoolValue>()); EXPECT_TRUE(value.GetBool().NativeValue()); } TEST(ReferenceResolver, ResolveEnumConstantsSkipParseOnly) { RuntimeOptions options; ASSERT_OK_AND_ASSIGN(RuntimeBuilder builder, CreateStandardRuntimeBuilder(options)); ASSERT_OK(EnableReferenceResolver( builder, ReferenceResolverEnabled::kCheckedExpressionOnly)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); CheckedExpr checked_expr; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(kEnumExpr, &checked_expr)); Expr unchecked_expr = checked_expr.expr(); ASSERT_OK_AND_ASSIGN(auto program, ProtobufRuntimeAdapter::CreateProgram( *runtime, unchecked_expr)); ManagedValueFactory value_factory(program->GetTypeProvider(), MemoryManagerRef::ReferenceCounting()); Activation activation; ASSERT_OK_AND_ASSIGN(Value value, program->Evaluate(activation, value_factory.get())); ASSERT_TRUE(value->Is<ErrorValue>()); EXPECT_THAT( value.GetError().NativeValue(), StatusIs(absl::StatusCode::kUnknown, HasSubstr("\"google.api.expr.test.v1.proto2.GlobalEnum.GAZ\""))); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/reference_resolver.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/reference_resolver_test.cc
4552db5798fb0853b131b783d8875794334fae7f
513dcbb4-fb4b-4c9a-9804-aae7b9470e23
cpp
google/cel-cpp
regex_precompilation
runtime/regex_precompilation.cc
runtime/regex_precompilation_test.cc
#include "runtime/regex_precompilation.h" #include "absl/base/macros.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "common/native_type.h" #include "eval/compiler/regex_precompilation_optimization.h" #include "internal/casts.h" #include "internal/status_macros.h" #include "runtime/internal/runtime_friend_access.h" #include "runtime/internal/runtime_impl.h" #include "runtime/runtime.h" #include "runtime/runtime_builder.h" namespace cel::extensions { namespace { using ::cel::internal::down_cast; using ::cel::runtime_internal::RuntimeFriendAccess; using ::cel::runtime_internal::RuntimeImpl; using ::google::api::expr::runtime::CreateRegexPrecompilationExtension; absl::StatusOr<RuntimeImpl*> RuntimeImplFromBuilder(RuntimeBuilder& builder) { Runtime& runtime = RuntimeFriendAccess::GetMutableRuntime(builder); if (RuntimeFriendAccess::RuntimeTypeId(runtime) != NativeTypeId::For<RuntimeImpl>()) { return absl::UnimplementedError( "regex precompilation only supported on the default cel::Runtime " "implementation."); } RuntimeImpl& runtime_impl = down_cast<RuntimeImpl&>(runtime); return &runtime_impl; } } absl::Status EnableRegexPrecompilation(RuntimeBuilder& builder) { CEL_ASSIGN_OR_RETURN(RuntimeImpl * runtime_impl, RuntimeImplFromBuilder(builder)); ABSL_ASSERT(runtime_impl != nullptr); runtime_impl->expr_builder().AddProgramOptimizer( CreateRegexPrecompilationExtension( runtime_impl->expr_builder().options().regex_max_program_size)); return absl::OkStatus(); } }
#include "runtime/regex_precompilation.h" #include <string> #include <utility> #include <vector> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/match.h" #include "base/function_adapter.h" #include "common/value.h" #include "extensions/protobuf/runtime_adapter.h" #include "internal/testing.h" #include "parser/parser.h" #include "runtime/activation.h" #include "runtime/constant_folding.h" #include "runtime/managed_value_factory.h" #include "runtime/register_function_helper.h" #include "runtime/runtime_builder.h" #include "runtime/runtime_options.h" #include "runtime/standard_runtime_builder_factory.h" namespace cel::extensions { namespace { using ::absl_testing::StatusIs; using ::google::api::expr::v1alpha1::ParsedExpr; using ::google::api::expr::parser::Parse; using ::testing::_; using ::testing::HasSubstr; using ValueMatcher = testing::Matcher<Value>; struct TestCase { std::string name; std::string expression; ValueMatcher result_matcher; absl::Status create_status; }; MATCHER_P(IsIntValue, expected, "") { const Value& value = arg; return value->Is<IntValue>() && value.GetInt().NativeValue() == expected; } MATCHER_P(IsBoolValue, expected, "") { const Value& value = arg; return value->Is<BoolValue>() && value.GetBool().NativeValue() == expected; } MATCHER_P(IsErrorValue, expected_substr, "") { const Value& value = arg; return value->Is<ErrorValue>() && absl::StrContains(value.GetError().NativeValue().message(), expected_substr); } class RegexPrecompilationTest : public testing::TestWithParam<TestCase> {}; TEST_P(RegexPrecompilationTest, Basic) { RuntimeOptions options; const TestCase& test_case = GetParam(); ASSERT_OK_AND_ASSIGN(cel::RuntimeBuilder builder, CreateStandardRuntimeBuilder(options)); auto status = RegisterHelper<BinaryFunctionAdapter< absl::StatusOr<Value>, const StringValue&, const StringValue&>>:: RegisterGlobalOverload( "prepend", [](ValueManager& f, const StringValue& value, const StringValue& prefix) { return StringValue::Concat(f, prefix, value); }, builder.function_registry()); ASSERT_OK(status); ASSERT_OK(EnableRegexPrecompilation(builder)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr, Parse(test_case.expression)); auto program_or = ProtobufRuntimeAdapter::CreateProgram(*runtime, parsed_expr); if (!test_case.create_status.ok()) { ASSERT_THAT(program_or.status(), StatusIs(test_case.create_status.code(), HasSubstr(test_case.create_status.message()))); return; } ASSERT_OK_AND_ASSIGN(auto program, std::move(program_or)); ManagedValueFactory value_factory(program->GetTypeProvider(), MemoryManagerRef::ReferenceCounting()); Activation activation; ASSERT_OK_AND_ASSIGN(auto var, value_factory.get().CreateStringValue("string_var")); activation.InsertOrAssignValue("string_var", var); ASSERT_OK_AND_ASSIGN(Value value, program->Evaluate(activation, value_factory.get())); EXPECT_THAT(value, test_case.result_matcher); } TEST_P(RegexPrecompilationTest, WithConstantFolding) { RuntimeOptions options; const TestCase& test_case = GetParam(); ASSERT_OK_AND_ASSIGN(cel::RuntimeBuilder builder, CreateStandardRuntimeBuilder(options)); auto status = RegisterHelper<BinaryFunctionAdapter< absl::StatusOr<Value>, const StringValue&, const StringValue&>>:: RegisterGlobalOverload( "prepend", [](ValueManager& f, const StringValue& value, const StringValue& prefix) { return StringValue::Concat(f, prefix, value); }, builder.function_registry()); ASSERT_OK(status); ASSERT_OK( EnableConstantFolding(builder, MemoryManagerRef::ReferenceCounting())); ASSERT_OK(EnableRegexPrecompilation(builder)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); ASSERT_OK_AND_ASSIGN(ParsedExpr parsed_expr, Parse(test_case.expression)); auto program_or = ProtobufRuntimeAdapter::CreateProgram(*runtime, parsed_expr); if (!test_case.create_status.ok()) { ASSERT_THAT(program_or.status(), StatusIs(test_case.create_status.code(), HasSubstr(test_case.create_status.message()))); return; } ASSERT_OK_AND_ASSIGN(auto program, std::move(program_or)); ManagedValueFactory value_factory(program->GetTypeProvider(), MemoryManagerRef::ReferenceCounting()); Activation activation; ASSERT_OK_AND_ASSIGN(auto var, value_factory.get().CreateStringValue("string_var")); activation.InsertOrAssignValue("string_var", var); ASSERT_OK_AND_ASSIGN(Value value, program->Evaluate(activation, value_factory.get())); EXPECT_THAT(value, test_case.result_matcher); } INSTANTIATE_TEST_SUITE_P( Cases, RegexPrecompilationTest, testing::ValuesIn(std::vector<TestCase>{ {"matches_receiver", R"(string_var.matches(r's\w+_var'))", IsBoolValue(true)}, {"matches_receiver_false", R"(string_var.matches(r'string_var\d+'))", IsBoolValue(false)}, {"matches_global_true", R"(matches(string_var, r's\w+_var'))", IsBoolValue(true)}, {"matches_global_false", R"(matches(string_var, r'string_var\d+'))", IsBoolValue(false)}, {"matches_bad_re2_expression", "matches('123', r'(?<!a)123')", _, absl::InvalidArgumentError("unsupported RE2")}, {"matches_unsupported_call_signature", "matches('123', r'(?<!a)123', 'gi')", _, absl::InvalidArgumentError("No overloads")}, {"constant_computation", "matches(string_var, r'string' + '_' + r'var')", IsBoolValue(true)}, }), [](const testing::TestParamInfo<TestCase>& info) { return info.param.name; }); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/regex_precompilation.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/regex_precompilation_test.cc
4552db5798fb0853b131b783d8875794334fae7f
d3540fdf-f66a-4c00-8171-5490a9676f89
cpp
google/cel-cpp
activation
eval/public/activation.cc
eval/public/activation_test.cc
#include "eval/public/activation.h" #include <algorithm> #include <memory> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "eval/public/cel_function.h" namespace google { namespace api { namespace expr { namespace runtime { absl::optional<CelValue> Activation::FindValue(absl::string_view name, google::protobuf::Arena* arena) const { auto entry = value_map_.find(name); if (entry == value_map_.end()) { return {}; } return entry->second.RetrieveValue(arena); } absl::Status Activation::InsertFunction(std::unique_ptr<CelFunction> function) { auto& overloads = function_map_[function->descriptor().name()]; for (const auto& overload : overloads) { if (overload->descriptor().ShapeMatches(function->descriptor())) { return absl::InvalidArgumentError( "Function with same shape already defined in activation"); } } overloads.emplace_back(std::move(function)); return absl::OkStatus(); } std::vector<const CelFunction*> Activation::FindFunctionOverloads( absl::string_view name) const { const auto map_entry = function_map_.find(name); std::vector<const CelFunction*> overloads; if (map_entry == function_map_.end()) { return overloads; } overloads.resize(map_entry->second.size()); std::transform(map_entry->second.begin(), map_entry->second.end(), overloads.begin(), [](const auto& func) { return func.get(); }); return overloads; } bool Activation::RemoveFunctionEntries( const CelFunctionDescriptor& descriptor) { auto map_entry = function_map_.find(descriptor.name()); if (map_entry == function_map_.end()) { return false; } std::vector<std::unique_ptr<CelFunction>>& overloads = map_entry->second; bool funcs_removed = false; auto func_iter = overloads.begin(); while (func_iter != overloads.end()) { if (descriptor.ShapeMatches(func_iter->get()->descriptor())) { func_iter = overloads.erase(func_iter); funcs_removed = true; } else { ++func_iter; } } if (overloads.empty()) { function_map_.erase(map_entry); } return funcs_removed; } void Activation::InsertValue(absl::string_view name, const CelValue& value) { value_map_.try_emplace(name, ValueEntry(value)); } void Activation::InsertValueProducer( absl::string_view name, std::unique_ptr<CelValueProducer> value_producer) { value_map_.try_emplace(name, ValueEntry(std::move(value_producer))); } bool Activation::RemoveValueEntry(absl::string_view name) { return value_map_.erase(name); } bool Activation::ClearValueEntry(absl::string_view name) { auto entry = value_map_.find(name); if (entry == value_map_.end()) { return false; } return entry->second.ClearValue(); } int Activation::ClearCachedValues() { int n = 0; for (auto& entry : value_map_) { if (entry.second.HasProducer()) { if (entry.second.ClearValue()) { n++; } } } return n; } } } } }
#include "eval/public/activation.h" #include <memory> #include <string> #include <utility> #include "eval/eval/attribute_trail.h" #include "eval/eval/ident_step.h" #include "eval/public/cel_attribute.h" #include "eval/public/cel_function.h" #include "extensions/protobuf/memory_manager.h" #include "internal/status_macros.h" #include "internal/testing.h" #include "parser/parser.h" namespace google { namespace api { namespace expr { namespace runtime { namespace { using ::absl_testing::StatusIs; using ::cel::extensions::ProtoMemoryManager; using ::google::api::expr::v1alpha1::Expr; using ::google::protobuf::Arena; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::IsEmpty; using ::testing::Property; using ::testing::Return; class MockValueProducer : public CelValueProducer { public: MOCK_METHOD(CelValue, Produce, (Arena*), (override)); }; class ConstCelFunction : public CelFunction { public: explicit ConstCelFunction(absl::string_view name) : CelFunction({std::string(name), false, {}}) {} explicit ConstCelFunction(const CelFunctionDescriptor& desc) : CelFunction(desc) {} absl::Status Evaluate(absl::Span<const CelValue> args, CelValue* output, google::protobuf::Arena* arena) const override { *output = CelValue::CreateInt64(42); return absl::OkStatus(); } }; TEST(ActivationTest, CheckValueInsertFindAndRemove) { Activation activation; Arena arena; activation.InsertValue("value42", CelValue::CreateInt64(42)); EXPECT_FALSE(activation.FindValue("value43", &arena)); EXPECT_TRUE(activation.FindValue("value42", &arena)); CelValue value = activation.FindValue("value42", &arena).value(); EXPECT_THAT(value.Int64OrDie(), Eq(42)); EXPECT_FALSE(activation.RemoveValueEntry("value43")); EXPECT_TRUE(activation.RemoveValueEntry("value42")); EXPECT_FALSE(activation.FindValue("value42", &arena)); } TEST(ActivationTest, CheckValueProducerInsertFindAndRemove) { const std::string kValue = "42"; auto producer = std::make_unique<MockValueProducer>(); google::protobuf::Arena arena; ON_CALL(*producer, Produce(&arena)) .WillByDefault(Return(CelValue::CreateString(&kValue))); EXPECT_CALL(*producer, Produce(&arena)).Times(1); Activation activation; activation.InsertValueProducer("value42", std::move(producer)); EXPECT_FALSE(activation.FindValue("value43", &arena)); for (int i = 0; i < 2; i++) { auto opt_value = activation.FindValue("value42", &arena); EXPECT_TRUE(opt_value.has_value()) << " for pass " << i; CelValue value = opt_value.value(); EXPECT_THAT(value.StringOrDie().value(), Eq(kValue)) << " for pass " << i; } EXPECT_TRUE(activation.RemoveValueEntry("value42")); EXPECT_FALSE(activation.FindValue("value42", &arena)); } TEST(ActivationTest, CheckInsertFunction) { Activation activation; ASSERT_OK(activation.InsertFunction( std::make_unique<ConstCelFunction>("ConstFunc"))); auto overloads = activation.FindFunctionOverloads("ConstFunc"); EXPECT_THAT(overloads, ElementsAre(Property( &CelFunction::descriptor, Property(&CelFunctionDescriptor::name, Eq("ConstFunc"))))); EXPECT_THAT(activation.InsertFunction( std::make_unique<ConstCelFunction>("ConstFunc")), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("Function with same shape"))); EXPECT_THAT(activation.FindFunctionOverloads("ConstFunc0"), IsEmpty()); } TEST(ActivationTest, CheckRemoveFunction) { Activation activation; ASSERT_OK(activation.InsertFunction(std::make_unique<ConstCelFunction>( CelFunctionDescriptor{"ConstFunc", false, {CelValue::Type::kInt64}}))); EXPECT_OK(activation.InsertFunction(std::make_unique<ConstCelFunction>( CelFunctionDescriptor{"ConstFunc", false, {CelValue::Type::kUint64}}))); auto overloads = activation.FindFunctionOverloads("ConstFunc"); EXPECT_THAT( overloads, ElementsAre( Property(&CelFunction::descriptor, Property(&CelFunctionDescriptor::name, Eq("ConstFunc"))), Property(&CelFunction::descriptor, Property(&CelFunctionDescriptor::name, Eq("ConstFunc"))))); EXPECT_TRUE(activation.RemoveFunctionEntries( {"ConstFunc", false, {CelValue::Type::kAny}})); EXPECT_THAT(activation.FindFunctionOverloads("ConstFunc"), IsEmpty()); } TEST(ActivationTest, CheckValueProducerClear) { const std::string kValue1 = "42"; const std::string kValue2 = "43"; auto producer1 = std::make_unique<MockValueProducer>(); auto producer2 = std::make_unique<MockValueProducer>(); google::protobuf::Arena arena; ON_CALL(*producer1, Produce(&arena)) .WillByDefault(Return(CelValue::CreateString(&kValue1))); ON_CALL(*producer2, Produce(&arena)) .WillByDefault(Return(CelValue::CreateString(&kValue2))); EXPECT_CALL(*producer1, Produce(&arena)).Times(2); EXPECT_CALL(*producer2, Produce(&arena)).Times(1); Activation activation; activation.InsertValueProducer("value42", std::move(producer1)); activation.InsertValueProducer("value43", std::move(producer2)); auto opt_value = activation.FindValue("value42", &arena); EXPECT_TRUE(opt_value.has_value()); EXPECT_THAT(opt_value->StringOrDie().value(), Eq(kValue1)); EXPECT_TRUE(activation.ClearValueEntry("value42")); EXPECT_FALSE(activation.ClearValueEntry("value43")); auto opt_value2 = activation.FindValue("value43", &arena); EXPECT_TRUE(opt_value2.has_value()); EXPECT_THAT(opt_value2->StringOrDie().value(), Eq(kValue2)); EXPECT_EQ(1, activation.ClearCachedValues()); EXPECT_FALSE(activation.ClearValueEntry("value42")); EXPECT_FALSE(activation.ClearValueEntry("value43")); auto opt_value3 = activation.FindValue("value42", &arena); EXPECT_TRUE(opt_value3.has_value()); EXPECT_THAT(opt_value3->StringOrDie().value(), Eq(kValue1)); EXPECT_EQ(1, activation.ClearCachedValues()); } TEST(ActivationTest, ErrorPathTest) { Activation activation; Expr expr; auto* select_expr = expr.mutable_select_expr(); select_expr->set_field("ip"); Expr* ident_expr = select_expr->mutable_operand(); ident_expr->mutable_ident_expr()->set_name("destination"); const CelAttributePattern destination_ip_pattern( "destination", {CreateCelAttributeQualifierPattern(CelValue::CreateStringView("ip"))}); AttributeTrail trail("destination"); trail = trail.Step(CreateCelAttributeQualifier(CelValue::CreateStringView("ip"))); ASSERT_EQ(destination_ip_pattern.IsMatch(trail.attribute()), CelAttributePattern::MatchType::FULL); EXPECT_TRUE(activation.missing_attribute_patterns().empty()); activation.set_missing_attribute_patterns({destination_ip_pattern}); EXPECT_EQ( activation.missing_attribute_patterns()[0].IsMatch(trail.attribute()), CelAttributePattern::MatchType::FULL); } } } } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/activation.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/activation_test.cc
4552db5798fb0853b131b783d8875794334fae7f
2d83b3c4-ee6c-454d-a6c5-2e474f4faae3
cpp
google/cel-cpp
function_registry
runtime/function_registry.cc
runtime/function_registry_test.cc
#include "runtime/function_registry.h" #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/container/node_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "absl/types/span.h" #include "base/function.h" #include "base/function_descriptor.h" #include "base/kind.h" #include "runtime/activation_interface.h" #include "runtime/function_overload_reference.h" #include "runtime/function_provider.h" namespace cel { namespace { class ActivationFunctionProviderImpl : public cel::runtime_internal::FunctionProvider { public: ActivationFunctionProviderImpl() = default; absl::StatusOr<absl::optional<cel::FunctionOverloadReference>> GetFunction( const cel::FunctionDescriptor& descriptor, const cel::ActivationInterface& activation) const override { std::vector<cel::FunctionOverloadReference> overloads = activation.FindFunctionOverloads(descriptor.name()); absl::optional<cel::FunctionOverloadReference> matching_overload = absl::nullopt; for (const auto& overload : overloads) { if (overload.descriptor.ShapeMatches(descriptor)) { if (matching_overload.has_value()) { return absl::Status(absl::StatusCode::kInvalidArgument, "Couldn't resolve function."); } matching_overload.emplace(overload); } } return matching_overload; } }; std::unique_ptr<cel::runtime_internal::FunctionProvider> CreateActivationFunctionProvider() { return std::make_unique<ActivationFunctionProviderImpl>(); } } absl::Status FunctionRegistry::Register( const cel::FunctionDescriptor& descriptor, std::unique_ptr<cel::Function> implementation) { if (DescriptorRegistered(descriptor)) { return absl::Status( absl::StatusCode::kAlreadyExists, "CelFunction with specified parameters already registered"); } if (!ValidateNonStrictOverload(descriptor)) { return absl::Status(absl::StatusCode::kAlreadyExists, "Only one overload is allowed for non-strict function"); } auto& overloads = functions_[descriptor.name()]; overloads.static_overloads.push_back( StaticFunctionEntry(descriptor, std::move(implementation))); return absl::OkStatus(); } absl::Status FunctionRegistry::RegisterLazyFunction( const cel::FunctionDescriptor& descriptor) { if (DescriptorRegistered(descriptor)) { return absl::Status( absl::StatusCode::kAlreadyExists, "CelFunction with specified parameters already registered"); } if (!ValidateNonStrictOverload(descriptor)) { return absl::Status(absl::StatusCode::kAlreadyExists, "Only one overload is allowed for non-strict function"); } auto& overloads = functions_[descriptor.name()]; overloads.lazy_overloads.push_back( LazyFunctionEntry(descriptor, CreateActivationFunctionProvider())); return absl::OkStatus(); } std::vector<cel::FunctionOverloadReference> FunctionRegistry::FindStaticOverloads(absl::string_view name, bool receiver_style, absl::Span<const cel::Kind> types) const { std::vector<cel::FunctionOverloadReference> matched_funcs; auto overloads = functions_.find(name); if (overloads == functions_.end()) { return matched_funcs; } for (const auto& overload : overloads->second.static_overloads) { if (overload.descriptor->ShapeMatches(receiver_style, types)) { matched_funcs.push_back({*overload.descriptor, *overload.implementation}); } } return matched_funcs; } std::vector<FunctionRegistry::LazyOverload> FunctionRegistry::FindLazyOverloads( absl::string_view name, bool receiver_style, absl::Span<const cel::Kind> types) const { std::vector<FunctionRegistry::LazyOverload> matched_funcs; auto overloads = functions_.find(name); if (overloads == functions_.end()) { return matched_funcs; } for (const auto& entry : overloads->second.lazy_overloads) { if (entry.descriptor->ShapeMatches(receiver_style, types)) { matched_funcs.push_back({*entry.descriptor, *entry.function_provider}); } } return matched_funcs; } absl::node_hash_map<std::string, std::vector<const cel::FunctionDescriptor*>> FunctionRegistry::ListFunctions() const { absl::node_hash_map<std::string, std::vector<const cel::FunctionDescriptor*>> descriptor_map; for (const auto& entry : functions_) { std::vector<const cel::FunctionDescriptor*> descriptors; const RegistryEntry& function_entry = entry.second; descriptors.reserve(function_entry.static_overloads.size() + function_entry.lazy_overloads.size()); for (const auto& entry : function_entry.static_overloads) { descriptors.push_back(entry.descriptor.get()); } for (const auto& entry : function_entry.lazy_overloads) { descriptors.push_back(entry.descriptor.get()); } descriptor_map[entry.first] = std::move(descriptors); } return descriptor_map; } bool FunctionRegistry::DescriptorRegistered( const cel::FunctionDescriptor& descriptor) const { return !(FindStaticOverloads(descriptor.name(), descriptor.receiver_style(), descriptor.types()) .empty()) || !(FindLazyOverloads(descriptor.name(), descriptor.receiver_style(), descriptor.types()) .empty()); } bool FunctionRegistry::ValidateNonStrictOverload( const cel::FunctionDescriptor& descriptor) const { auto overloads = functions_.find(descriptor.name()); if (overloads == functions_.end()) { return true; } const RegistryEntry& entry = overloads->second; if (!descriptor.is_strict()) { return false; } return (entry.static_overloads.empty() || entry.static_overloads[0].descriptor->is_strict()) && (entry.lazy_overloads.empty() || entry.lazy_overloads[0].descriptor->is_strict()); } }
#include "runtime/function_registry.h" #include <cstdint> #include <memory> #include <tuple> #include <vector> #include "absl/status/status.h" #include "base/function.h" #include "base/function_adapter.h" #include "base/function_descriptor.h" #include "base/kind.h" #include "common/value_manager.h" #include "internal/testing.h" #include "runtime/activation.h" #include "runtime/function_overload_reference.h" #include "runtime/function_provider.h" namespace cel { namespace { using ::absl_testing::StatusIs; using ::cel::runtime_internal::FunctionProvider; using ::testing::ElementsAre; using ::testing::HasSubstr; using ::testing::SizeIs; using ::testing::Truly; class ConstIntFunction : public cel::Function { public: static cel::FunctionDescriptor MakeDescriptor() { return {"ConstFunction", false, {}}; } absl::StatusOr<Value> Invoke(const FunctionEvaluationContext& context, absl::Span<const Value> args) const override { return context.value_factory().CreateIntValue(42); } }; TEST(FunctionRegistryTest, InsertAndRetrieveLazyFunction) { cel::FunctionDescriptor lazy_function_desc{"LazyFunction", false, {}}; FunctionRegistry registry; Activation activation; ASSERT_OK(registry.RegisterLazyFunction(lazy_function_desc)); const auto descriptors = registry.FindLazyOverloads("LazyFunction", false, {}); EXPECT_THAT(descriptors, SizeIs(1)); } TEST(FunctionRegistryTest, LazyAndStaticFunctionShareDescriptorSpace) { FunctionRegistry registry; cel::FunctionDescriptor desc = ConstIntFunction::MakeDescriptor(); ASSERT_OK(registry.RegisterLazyFunction(desc)); absl::Status status = registry.Register(ConstIntFunction::MakeDescriptor(), std::make_unique<ConstIntFunction>()); EXPECT_FALSE(status.ok()); } TEST(FunctionRegistryTest, FindStaticOverloadsReturns) { FunctionRegistry registry; cel::FunctionDescriptor desc = ConstIntFunction::MakeDescriptor(); ASSERT_OK(registry.Register(desc, std::make_unique<ConstIntFunction>())); std::vector<cel::FunctionOverloadReference> overloads = registry.FindStaticOverloads(desc.name(), false, {}); EXPECT_THAT(overloads, ElementsAre(Truly( [](const cel::FunctionOverloadReference& overload) -> bool { return overload.descriptor.name() == "ConstFunction"; }))) << "Expected single ConstFunction()"; } TEST(FunctionRegistryTest, ListFunctions) { cel::FunctionDescriptor lazy_function_desc{"LazyFunction", false, {}}; FunctionRegistry registry; ASSERT_OK(registry.RegisterLazyFunction(lazy_function_desc)); EXPECT_OK(registry.Register(ConstIntFunction::MakeDescriptor(), std::make_unique<ConstIntFunction>())); auto registered_functions = registry.ListFunctions(); EXPECT_THAT(registered_functions, SizeIs(2)); EXPECT_THAT(registered_functions["LazyFunction"], SizeIs(1)); EXPECT_THAT(registered_functions["ConstFunction"], SizeIs(1)); } TEST(FunctionRegistryTest, DefaultLazyProviderNoOverloadFound) { FunctionRegistry registry; Activation activation; cel::FunctionDescriptor lazy_function_desc{"LazyFunction", false, {}}; EXPECT_OK(registry.RegisterLazyFunction(lazy_function_desc)); auto providers = registry.FindLazyOverloads("LazyFunction", false, {}); ASSERT_THAT(providers, SizeIs(1)); const FunctionProvider& provider = providers[0].provider; ASSERT_OK_AND_ASSIGN( absl::optional<FunctionOverloadReference> func, provider.GetFunction({"LazyFunc", false, {cel::Kind::kInt64}}, activation)); EXPECT_EQ(func, absl::nullopt); } TEST(FunctionRegistryTest, DefaultLazyProviderReturnsImpl) { FunctionRegistry registry; Activation activation; EXPECT_OK(registry.RegisterLazyFunction( FunctionDescriptor("LazyFunction", false, {Kind::kAny}))); EXPECT_TRUE(activation.InsertFunction( FunctionDescriptor("LazyFunction", false, {Kind::kInt}), UnaryFunctionAdapter<int64_t, int64_t>::WrapFunction( [](ValueManager&, int64_t x) { return 2 * x; }))); EXPECT_TRUE(activation.InsertFunction( FunctionDescriptor("LazyFunction", false, {Kind::kDouble}), UnaryFunctionAdapter<double, double>::WrapFunction( [](ValueManager&, double x) { return 2 * x; }))); auto providers = registry.FindLazyOverloads("LazyFunction", false, {Kind::kInt}); ASSERT_THAT(providers, SizeIs(1)); const FunctionProvider& provider = providers[0].provider; ASSERT_OK_AND_ASSIGN( absl::optional<FunctionOverloadReference> func, provider.GetFunction( FunctionDescriptor("LazyFunction", false, {Kind::kInt}), activation)); ASSERT_TRUE(func.has_value()); EXPECT_EQ(func->descriptor.name(), "LazyFunction"); EXPECT_EQ(func->descriptor.types(), std::vector{cel::Kind::kInt64}); } TEST(FunctionRegistryTest, DefaultLazyProviderAmbiguousOverload) { FunctionRegistry registry; Activation activation; EXPECT_OK(registry.RegisterLazyFunction( FunctionDescriptor("LazyFunction", false, {Kind::kAny}))); EXPECT_TRUE(activation.InsertFunction( FunctionDescriptor("LazyFunction", false, {Kind::kInt}), UnaryFunctionAdapter<int64_t, int64_t>::WrapFunction( [](ValueManager&, int64_t x) { return 2 * x; }))); EXPECT_TRUE(activation.InsertFunction( FunctionDescriptor("LazyFunction", false, {Kind::kDouble}), UnaryFunctionAdapter<double, double>::WrapFunction( [](ValueManager&, double x) { return 2 * x; }))); auto providers = registry.FindLazyOverloads("LazyFunction", false, {Kind::kInt}); ASSERT_THAT(providers, SizeIs(1)); const FunctionProvider& provider = providers[0].provider; EXPECT_THAT( provider.GetFunction( FunctionDescriptor("LazyFunction", false, {Kind::kAny}), activation), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("Couldn't resolve function"))); } TEST(FunctionRegistryTest, CanRegisterNonStrictFunction) { { FunctionRegistry registry; cel::FunctionDescriptor descriptor("NonStrictFunction", false, {Kind::kAny}, false); ASSERT_OK( registry.Register(descriptor, std::make_unique<ConstIntFunction>())); EXPECT_THAT( registry.FindStaticOverloads("NonStrictFunction", false, {Kind::kAny}), SizeIs(1)); } { FunctionRegistry registry; cel::FunctionDescriptor descriptor("NonStrictLazyFunction", false, {Kind::kAny}, false); EXPECT_OK(registry.RegisterLazyFunction(descriptor)); EXPECT_THAT(registry.FindLazyOverloads("NonStrictLazyFunction", false, {Kind::kAny}), SizeIs(1)); } } using NonStrictTestCase = std::tuple<bool, bool>; using NonStrictRegistrationFailTest = testing::TestWithParam<NonStrictTestCase>; TEST_P(NonStrictRegistrationFailTest, IfOtherOverloadExistsRegisteringNonStrictFails) { bool existing_function_is_lazy, new_function_is_lazy; std::tie(existing_function_is_lazy, new_function_is_lazy) = GetParam(); FunctionRegistry registry; cel::FunctionDescriptor descriptor("OverloadedFunction", false, {Kind::kAny}, true); if (existing_function_is_lazy) { ASSERT_OK(registry.RegisterLazyFunction(descriptor)); } else { ASSERT_OK( registry.Register(descriptor, std::make_unique<ConstIntFunction>())); } cel::FunctionDescriptor new_descriptor("OverloadedFunction", false, {Kind::kAny, Kind::kAny}, false); absl::Status status; if (new_function_is_lazy) { status = registry.RegisterLazyFunction(new_descriptor); } else { status = registry.Register(new_descriptor, std::make_unique<ConstIntFunction>()); } EXPECT_THAT(status, StatusIs(absl::StatusCode::kAlreadyExists, HasSubstr("Only one overload"))); } TEST_P(NonStrictRegistrationFailTest, IfOtherNonStrictExistsRegisteringStrictFails) { bool existing_function_is_lazy, new_function_is_lazy; std::tie(existing_function_is_lazy, new_function_is_lazy) = GetParam(); FunctionRegistry registry; cel::FunctionDescriptor descriptor("OverloadedFunction", false, {Kind::kAny}, false); if (existing_function_is_lazy) { ASSERT_OK(registry.RegisterLazyFunction(descriptor)); } else { ASSERT_OK( registry.Register(descriptor, std::make_unique<ConstIntFunction>())); } cel::FunctionDescriptor new_descriptor("OverloadedFunction", false, {Kind::kAny, Kind::kAny}, true); absl::Status status; if (new_function_is_lazy) { status = registry.RegisterLazyFunction(new_descriptor); } else { status = registry.Register(new_descriptor, std::make_unique<ConstIntFunction>()); } EXPECT_THAT(status, StatusIs(absl::StatusCode::kAlreadyExists, HasSubstr("Only one overload"))); } TEST_P(NonStrictRegistrationFailTest, CanRegisterStrictFunctionsWithoutLimit) { bool existing_function_is_lazy, new_function_is_lazy; std::tie(existing_function_is_lazy, new_function_is_lazy) = GetParam(); FunctionRegistry registry; cel::FunctionDescriptor descriptor("OverloadedFunction", false, {Kind::kAny}, true); if (existing_function_is_lazy) { ASSERT_OK(registry.RegisterLazyFunction(descriptor)); } else { ASSERT_OK( registry.Register(descriptor, std::make_unique<ConstIntFunction>())); } cel::FunctionDescriptor new_descriptor("OverloadedFunction", false, {Kind::kAny, Kind::kAny}, true); absl::Status status; if (new_function_is_lazy) { status = registry.RegisterLazyFunction(new_descriptor); } else { status = registry.Register(new_descriptor, std::make_unique<ConstIntFunction>()); } EXPECT_OK(status); } INSTANTIATE_TEST_SUITE_P(NonStrictRegistrationFailTest, NonStrictRegistrationFailTest, testing::Combine(testing::Bool(), testing::Bool())); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/function_registry.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/function_registry_test.cc
4552db5798fb0853b131b783d8875794334fae7f
d65e442f-6790-455c-a666-49c18d3649fd
cpp
google/cel-cpp
constant_folding
eval/compiler/constant_folding.cc
eval/compiler/constant_folding_test.cc
#include "eval/compiler/constant_folding.h" #include <cstddef> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/variant.h" #include "base/ast_internal/ast_impl.h" #include "base/ast_internal/expr.h" #include "base/builtins.h" #include "base/kind.h" #include "base/type_provider.h" #include "common/value.h" #include "common/value_manager.h" #include "eval/compiler/flat_expr_builder_extensions.h" #include "eval/compiler/resolver.h" #include "eval/eval/const_value_step.h" #include "eval/eval/evaluator_core.h" #include "internal/status_macros.h" #include "runtime/activation.h" #include "runtime/internal/convert_constant.h" namespace cel::runtime_internal { namespace { using ::cel::ast_internal::AstImpl; using ::cel::ast_internal::Call; using ::cel::ast_internal::Comprehension; using ::cel::ast_internal::Constant; using ::cel::ast_internal::CreateList; using ::cel::ast_internal::CreateStruct; using ::cel::ast_internal::Expr; using ::cel::ast_internal::Ident; using ::cel::ast_internal::Select; using ::cel::builtin::kAnd; using ::cel::builtin::kOr; using ::cel::builtin::kTernary; using ::cel::runtime_internal::ConvertConstant; using ::google::api::expr::runtime::CreateConstValueDirectStep; using ::google::api::expr::runtime::CreateConstValueStep; using ::google::api::expr::runtime::EvaluationListener; using ::google::api::expr::runtime::ExecutionFrame; using ::google::api::expr::runtime::ExecutionPath; using ::google::api::expr::runtime::ExecutionPathView; using ::google::api::expr::runtime::FlatExpressionEvaluatorState; using ::google::api::expr::runtime::PlannerContext; using ::google::api::expr::runtime::ProgramOptimizer; using ::google::api::expr::runtime::ProgramOptimizerFactory; using ::google::api::expr::runtime::Resolver; class ConstantFoldingExtension : public ProgramOptimizer { public: ConstantFoldingExtension(MemoryManagerRef memory_manager, const TypeProvider& type_provider) : memory_manager_(memory_manager), state_(kDefaultStackLimit, kComprehensionSlotCount, type_provider, memory_manager_) {} absl::Status OnPreVisit(google::api::expr::runtime::PlannerContext& context, const Expr& node) override; absl::Status OnPostVisit(google::api::expr::runtime::PlannerContext& context, const Expr& node) override; private: enum class IsConst { kConditional, kNonConst, }; static constexpr size_t kDefaultStackLimit = 4; static constexpr size_t kComprehensionSlotCount = 0; MemoryManagerRef memory_manager_; Activation empty_; FlatExpressionEvaluatorState state_; std::vector<IsConst> is_const_; }; absl::Status ConstantFoldingExtension::OnPreVisit(PlannerContext& context, const Expr& node) { struct IsConstVisitor { IsConst operator()(const Constant&) { return IsConst::kConditional; } IsConst operator()(const Ident&) { return IsConst::kNonConst; } IsConst operator()(const Comprehension&) { return IsConst::kNonConst; } IsConst operator()(const CreateStruct& create_struct) { return IsConst::kNonConst; } IsConst operator()(const cel::MapExpr& map_expr) { if (map_expr.entries().empty()) { return IsConst::kNonConst; } return IsConst::kConditional; } IsConst operator()(const CreateList& create_list) { if (create_list.elements().empty()) { return IsConst::kNonConst; } return IsConst::kConditional; } IsConst operator()(const Select&) { return IsConst::kConditional; } IsConst operator()(const cel::UnspecifiedExpr&) { return IsConst::kNonConst; } IsConst operator()(const Call& call) { if (call.function() == kAnd || call.function() == kOr || call.function() == kTernary) { return IsConst::kNonConst; } if (call.function() == "cel.@block") { return IsConst::kNonConst; } int arg_len = call.args().size() + (call.has_target() ? 1 : 0); std::vector<cel::Kind> arg_matcher(arg_len, cel::Kind::kAny); if (!resolver .FindLazyOverloads(call.function(), call.has_target(), arg_matcher) .empty()) { return IsConst::kNonConst; } return IsConst::kConditional; } const Resolver& resolver; }; IsConst is_const = absl::visit(IsConstVisitor{context.resolver()}, node.kind()); is_const_.push_back(is_const); return absl::OkStatus(); } absl::Status ConstantFoldingExtension::OnPostVisit(PlannerContext& context, const Expr& node) { if (is_const_.empty()) { return absl::InternalError("ConstantFoldingExtension called out of order."); } IsConst is_const = is_const_.back(); is_const_.pop_back(); if (is_const == IsConst::kNonConst) { if (!is_const_.empty()) { is_const_.back() = IsConst::kNonConst; } return absl::OkStatus(); } ExecutionPathView subplan = context.GetSubplan(node); if (subplan.empty()) { return absl::OkStatus(); } Value value; if (node.has_const_expr()) { CEL_ASSIGN_OR_RETURN( value, ConvertConstant(node.const_expr(), state_.value_factory())); } else { ExecutionFrame frame(subplan, empty_, context.options(), state_); state_.Reset(); state_.value_stack().SetMaxSize(subplan.size()); auto result = frame.Evaluate(); if (!result.ok()) { return absl::OkStatus(); } value = *result; if (value->Is<UnknownValue>()) { return absl::OkStatus(); } } if (context.options().max_recursion_depth != 0) { return context.ReplaceSubplan( node, CreateConstValueDirectStep(std::move(value), node.id()), 1); } ExecutionPath new_plan; CEL_ASSIGN_OR_RETURN( new_plan.emplace_back(), CreateConstValueStep(std::move(value), node.id(), false)); return context.ReplaceSubplan(node, std::move(new_plan)); } } ProgramOptimizerFactory CreateConstantFoldingOptimizer( MemoryManagerRef memory_manager) { return [memory_manager](PlannerContext& ctx, const AstImpl&) -> absl::StatusOr<std::unique_ptr<ProgramOptimizer>> { return std::make_unique<ConstantFoldingExtension>( memory_manager, ctx.value_factory().type_provider()); }; } }
#include "eval/compiler/constant_folding.h" #include <memory> #include <utility> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "base/ast.h" #include "base/ast_internal/ast_impl.h" #include "base/ast_internal/expr.h" #include "common/memory.h" #include "common/type_factory.h" #include "common/type_manager.h" #include "common/value.h" #include "common/value_manager.h" #include "common/values/legacy_value_manager.h" #include "eval/compiler/flat_expr_builder_extensions.h" #include "eval/compiler/resolver.h" #include "eval/eval/const_value_step.h" #include "eval/eval/create_list_step.h" #include "eval/eval/create_map_step.h" #include "eval/eval/evaluator_core.h" #include "extensions/protobuf/ast_converters.h" #include "extensions/protobuf/memory_manager.h" #include "internal/status_macros.h" #include "internal/testing.h" #include "parser/parser.h" #include "runtime/function_registry.h" #include "runtime/internal/issue_collector.h" #include "runtime/runtime_issue.h" #include "runtime/runtime_options.h" #include "runtime/type_registry.h" #include "google/protobuf/arena.h" namespace cel::runtime_internal { namespace { using ::absl_testing::StatusIs; using ::cel::RuntimeIssue; using ::cel::ast_internal::AstImpl; using ::cel::ast_internal::Expr; using ::cel::extensions::ProtoMemoryManagerRef; using ::cel::runtime_internal::IssueCollector; using ::google::api::expr::v1alpha1::ParsedExpr; using ::google::api::expr::parser::Parse; using ::google::api::expr::runtime::CreateConstValueStep; using ::google::api::expr::runtime::CreateCreateListStep; using ::google::api::expr::runtime::CreateCreateStructStepForMap; using ::google::api::expr::runtime::ExecutionPath; using ::google::api::expr::runtime::PlannerContext; using ::google::api::expr::runtime::ProgramBuilder; using ::google::api::expr::runtime::ProgramOptimizer; using ::google::api::expr::runtime::ProgramOptimizerFactory; using ::google::api::expr::runtime::Resolver; using ::testing::SizeIs; class UpdatedConstantFoldingTest : public testing::Test { public: UpdatedConstantFoldingTest() : value_factory_(ProtoMemoryManagerRef(&arena_), type_registry_.GetComposedTypeProvider()), issue_collector_(RuntimeIssue::Severity::kError), resolver_("", function_registry_, type_registry_, value_factory_, type_registry_.resolveable_enums()) {} protected: google::protobuf::Arena arena_; cel::FunctionRegistry function_registry_; cel::TypeRegistry type_registry_; cel::common_internal::LegacyValueManager value_factory_; cel::RuntimeOptions options_; IssueCollector issue_collector_; Resolver resolver_; }; absl::StatusOr<std::unique_ptr<cel::Ast>> ParseFromCel( absl::string_view expression) { CEL_ASSIGN_OR_RETURN(ParsedExpr expr, Parse(expression)); return cel::extensions::CreateAstFromParsedExpr(expr); } TEST_F(UpdatedConstantFoldingTest, SkipsTernary) { ASSERT_OK_AND_ASSIGN(std::unique_ptr<cel::Ast> ast, ParseFromCel("true ? true : false")); AstImpl& ast_impl = AstImpl::CastFromPublicAst(*ast); const Expr& call = ast_impl.root_expr(); const Expr& condition = call.call_expr().args()[0]; const Expr& true_branch = call.call_expr().args()[1]; const Expr& false_branch = call.call_expr().args()[2]; ProgramBuilder program_builder; program_builder.EnterSubexpression(&call); program_builder.EnterSubexpression(&condition); ASSERT_OK_AND_ASSIGN( auto step, CreateConstValueStep(value_factory_.CreateBoolValue(true), -1)); program_builder.AddStep(std::move(step)); program_builder.ExitSubexpression(&condition); program_builder.EnterSubexpression(&true_branch); ASSERT_OK_AND_ASSIGN( step, CreateConstValueStep(value_factory_.CreateBoolValue(true), -1)); program_builder.AddStep(std::move(step)); program_builder.ExitSubexpression(&true_branch); program_builder.EnterSubexpression(&false_branch); ASSERT_OK_AND_ASSIGN( step, CreateConstValueStep(value_factory_.CreateBoolValue(true), -1)); program_builder.AddStep(std::move(step)); program_builder.ExitSubexpression(&false_branch); ASSERT_OK_AND_ASSIGN(step, CreateConstValueStep(value_factory_.GetNullValue(), -1)); program_builder.AddStep(std::move(step)); program_builder.ExitSubexpression(&call); PlannerContext context(resolver_, options_, value_factory_, issue_collector_, program_builder); google::protobuf::Arena arena; ProgramOptimizerFactory constant_folder_factory = CreateConstantFoldingOptimizer(ProtoMemoryManagerRef(&arena_)); ASSERT_OK_AND_ASSIGN(std::unique_ptr<ProgramOptimizer> constant_folder, constant_folder_factory(context, ast_impl)); ASSERT_OK(constant_folder->OnPreVisit(context, call)); ASSERT_OK(constant_folder->OnPreVisit(context, condition)); ASSERT_OK(constant_folder->OnPostVisit(context, condition)); ASSERT_OK(constant_folder->OnPreVisit(context, true_branch)); ASSERT_OK(constant_folder->OnPostVisit(context, true_branch)); ASSERT_OK(constant_folder->OnPreVisit(context, false_branch)); ASSERT_OK(constant_folder->OnPostVisit(context, false_branch)); ASSERT_OK(constant_folder->OnPostVisit(context, call)); auto path = std::move(program_builder).FlattenMain(); EXPECT_THAT(path, SizeIs(4)); } TEST_F(UpdatedConstantFoldingTest, SkipsOr) { ASSERT_OK_AND_ASSIGN(std::unique_ptr<cel::Ast> ast, ParseFromCel("false || true")); AstImpl& ast_impl = AstImpl::CastFromPublicAst(*ast); const Expr& call = ast_impl.root_expr(); const Expr& left_condition = call.call_expr().args()[0]; const Expr& right_condition = call.call_expr().args()[1]; ProgramBuilder program_builder; program_builder.EnterSubexpression(&call); program_builder.EnterSubexpression(&left_condition); ASSERT_OK_AND_ASSIGN( auto step, CreateConstValueStep(value_factory_.CreateBoolValue(false), -1)); program_builder.AddStep(std::move(step)); program_builder.ExitSubexpression(&left_condition); program_builder.EnterSubexpression(&right_condition); ASSERT_OK_AND_ASSIGN( step, CreateConstValueStep(value_factory_.CreateBoolValue(true), -1)); program_builder.AddStep(std::move(step)); program_builder.ExitSubexpression(&right_condition); ASSERT_OK_AND_ASSIGN(step, CreateConstValueStep(value_factory_.GetNullValue(), -1)); program_builder.AddStep(std::move(step)); program_builder.ExitSubexpression(&call); PlannerContext context(resolver_, options_, value_factory_, issue_collector_, program_builder); google::protobuf::Arena arena; ProgramOptimizerFactory constant_folder_factory = CreateConstantFoldingOptimizer(ProtoMemoryManagerRef(&arena_)); ASSERT_OK_AND_ASSIGN(std::unique_ptr<ProgramOptimizer> constant_folder, constant_folder_factory(context, ast_impl)); ASSERT_OK(constant_folder->OnPreVisit(context, call)); ASSERT_OK(constant_folder->OnPreVisit(context, left_condition)); ASSERT_OK(constant_folder->OnPostVisit(context, left_condition)); ASSERT_OK(constant_folder->OnPreVisit(context, right_condition)); ASSERT_OK(constant_folder->OnPostVisit(context, right_condition)); ASSERT_OK(constant_folder->OnPostVisit(context, call)); auto path = std::move(program_builder).FlattenMain(); EXPECT_THAT(path, SizeIs(3)); } TEST_F(UpdatedConstantFoldingTest, SkipsAnd) { ASSERT_OK_AND_ASSIGN(std::unique_ptr<cel::Ast> ast, ParseFromCel("true && false")); AstImpl& ast_impl = AstImpl::CastFromPublicAst(*ast); const Expr& call = ast_impl.root_expr(); const Expr& left_condition = call.call_expr().args()[0]; const Expr& right_condition = call.call_expr().args()[1]; ProgramBuilder program_builder; program_builder.EnterSubexpression(&call); program_builder.EnterSubexpression(&left_condition); ASSERT_OK_AND_ASSIGN( auto step, CreateConstValueStep(value_factory_.CreateBoolValue(true), -1)); program_builder.AddStep(std::move(step)); program_builder.ExitSubexpression(&left_condition); program_builder.EnterSubexpression(&right_condition); ASSERT_OK_AND_ASSIGN( step, CreateConstValueStep(value_factory_.CreateBoolValue(false), -1)); program_builder.AddStep(std::move(step)); program_builder.ExitSubexpression(&right_condition); ASSERT_OK_AND_ASSIGN(step, CreateConstValueStep(value_factory_.GetNullValue(), -1)); program_builder.AddStep(std::move(step)); program_builder.ExitSubexpression(&call); PlannerContext context(resolver_, options_, value_factory_, issue_collector_, program_builder); google::protobuf::Arena arena; ProgramOptimizerFactory constant_folder_factory = CreateConstantFoldingOptimizer(ProtoMemoryManagerRef(&arena_)); ASSERT_OK_AND_ASSIGN(std::unique_ptr<ProgramOptimizer> constant_folder, constant_folder_factory(context, ast_impl)); ASSERT_OK(constant_folder->OnPreVisit(context, call)); ASSERT_OK(constant_folder->OnPreVisit(context, left_condition)); ASSERT_OK(constant_folder->OnPostVisit(context, left_condition)); ASSERT_OK(constant_folder->OnPreVisit(context, right_condition)); ASSERT_OK(constant_folder->OnPostVisit(context, right_condition)); ASSERT_OK(constant_folder->OnPostVisit(context, call)); ExecutionPath path = std::move(program_builder).FlattenMain(); EXPECT_THAT(path, SizeIs(3)); } TEST_F(UpdatedConstantFoldingTest, CreatesList) { ASSERT_OK_AND_ASSIGN(std::unique_ptr<cel::Ast> ast, ParseFromCel("[1, 2]")); AstImpl& ast_impl = AstImpl::CastFromPublicAst(*ast); const Expr& create_list = ast_impl.root_expr(); const Expr& elem_one = create_list.list_expr().elements()[0].expr(); const Expr& elem_two = create_list.list_expr().elements()[1].expr(); ProgramBuilder program_builder; program_builder.EnterSubexpression(&create_list); program_builder.EnterSubexpression(&elem_one); ASSERT_OK_AND_ASSIGN( auto step, CreateConstValueStep(value_factory_.CreateIntValue(1L), 1)); program_builder.AddStep(std::move(step)); program_builder.ExitSubexpression(&elem_one); program_builder.EnterSubexpression(&elem_two); ASSERT_OK_AND_ASSIGN( step, CreateConstValueStep(value_factory_.CreateIntValue(2L), 2)); program_builder.AddStep(std::move(step)); program_builder.ExitSubexpression(&elem_two); ASSERT_OK_AND_ASSIGN(step, CreateCreateListStep(create_list.list_expr(), 3)); program_builder.AddStep(std::move(step)); program_builder.ExitSubexpression(&create_list); PlannerContext context(resolver_, options_, value_factory_, issue_collector_, program_builder); google::protobuf::Arena arena; ProgramOptimizerFactory constant_folder_factory = CreateConstantFoldingOptimizer(ProtoMemoryManagerRef(&arena_)); ASSERT_OK_AND_ASSIGN(std::unique_ptr<ProgramOptimizer> constant_folder, constant_folder_factory(context, ast_impl)); ASSERT_OK(constant_folder->OnPreVisit(context, create_list)); ASSERT_OK(constant_folder->OnPreVisit(context, elem_one)); ASSERT_OK(constant_folder->OnPostVisit(context, elem_one)); ASSERT_OK(constant_folder->OnPreVisit(context, elem_two)); ASSERT_OK(constant_folder->OnPostVisit(context, elem_two)); ASSERT_OK(constant_folder->OnPostVisit(context, create_list)); ExecutionPath path = std::move(program_builder).FlattenMain(); EXPECT_THAT(path, SizeIs(1)); } TEST_F(UpdatedConstantFoldingTest, CreatesMap) { ASSERT_OK_AND_ASSIGN(std::unique_ptr<cel::Ast> ast, ParseFromCel("{1: 2}")); AstImpl& ast_impl = AstImpl::CastFromPublicAst(*ast); const Expr& create_map = ast_impl.root_expr(); const Expr& key = create_map.map_expr().entries()[0].key(); const Expr& value = create_map.map_expr().entries()[0].value(); ProgramBuilder program_builder; program_builder.EnterSubexpression(&create_map); program_builder.EnterSubexpression(&key); ASSERT_OK_AND_ASSIGN( auto step, CreateConstValueStep(value_factory_.CreateIntValue(1L), 1)); program_builder.AddStep(std::move(step)); program_builder.ExitSubexpression(&key); program_builder.EnterSubexpression(&value); ASSERT_OK_AND_ASSIGN( step, CreateConstValueStep(value_factory_.CreateIntValue(2L), 2)); program_builder.AddStep(std::move(step)); program_builder.ExitSubexpression(&value); ASSERT_OK_AND_ASSIGN( step, CreateCreateStructStepForMap(create_map.map_expr().entries().size(), {}, 3)); program_builder.AddStep(std::move(step)); program_builder.ExitSubexpression(&create_map); PlannerContext context(resolver_, options_, value_factory_, issue_collector_, program_builder); google::protobuf::Arena arena; ProgramOptimizerFactory constant_folder_factory = CreateConstantFoldingOptimizer(ProtoMemoryManagerRef(&arena_)); ASSERT_OK_AND_ASSIGN(std::unique_ptr<ProgramOptimizer> constant_folder, constant_folder_factory(context, ast_impl)); ASSERT_OK(constant_folder->OnPreVisit(context, create_map)); ASSERT_OK(constant_folder->OnPreVisit(context, key)); ASSERT_OK(constant_folder->OnPostVisit(context, key)); ASSERT_OK(constant_folder->OnPreVisit(context, value)); ASSERT_OK(constant_folder->OnPostVisit(context, value)); ASSERT_OK(constant_folder->OnPostVisit(context, create_map)); ExecutionPath path = std::move(program_builder).FlattenMain(); EXPECT_THAT(path, SizeIs(1)); } TEST_F(UpdatedConstantFoldingTest, CreatesInvalidMap) { ASSERT_OK_AND_ASSIGN(std::unique_ptr<cel::Ast> ast, ParseFromCel("{1.0: 2}")); AstImpl& ast_impl = AstImpl::CastFromPublicAst(*ast); const Expr& create_map = ast_impl.root_expr(); const Expr& key = create_map.map_expr().entries()[0].key(); const Expr& value = create_map.map_expr().entries()[0].value(); ProgramBuilder program_builder; program_builder.EnterSubexpression(&create_map); program_builder.EnterSubexpression(&key); ASSERT_OK_AND_ASSIGN( auto step, CreateConstValueStep(value_factory_.CreateDoubleValue(1.0), 1)); program_builder.AddStep(std::move(step)); program_builder.ExitSubexpression(&key); program_builder.EnterSubexpression(&value); ASSERT_OK_AND_ASSIGN( step, CreateConstValueStep(value_factory_.CreateIntValue(2L), 2)); program_builder.AddStep(std::move(step)); program_builder.ExitSubexpression(&value); ASSERT_OK_AND_ASSIGN( step, CreateCreateStructStepForMap(create_map.map_expr().entries().size(), {}, 3)); program_builder.AddStep(std::move(step)); program_builder.ExitSubexpression(&create_map); PlannerContext context(resolver_, options_, value_factory_, issue_collector_, program_builder); google::protobuf::Arena arena; ProgramOptimizerFactory constant_folder_factory = CreateConstantFoldingOptimizer(ProtoMemoryManagerRef(&arena_)); ASSERT_OK_AND_ASSIGN(std::unique_ptr<ProgramOptimizer> constant_folder, constant_folder_factory(context, ast_impl)); ASSERT_OK(constant_folder->OnPreVisit(context, create_map)); ASSERT_OK(constant_folder->OnPreVisit(context, key)); ASSERT_OK(constant_folder->OnPostVisit(context, key)); ASSERT_OK(constant_folder->OnPreVisit(context, value)); ASSERT_OK(constant_folder->OnPostVisit(context, value)); ASSERT_OK(constant_folder->OnPostVisit(context, create_map)); ExecutionPath path = std::move(program_builder).FlattenMain(); EXPECT_THAT(path, SizeIs(3)); } TEST_F(UpdatedConstantFoldingTest, ErrorsOnUnexpectedOrder) { ASSERT_OK_AND_ASSIGN(std::unique_ptr<cel::Ast> ast, ParseFromCel("true && false")); AstImpl& ast_impl = AstImpl::CastFromPublicAst(*ast); const Expr& call = ast_impl.root_expr(); const Expr& left_condition = call.call_expr().args()[0]; const Expr& right_condition = call.call_expr().args()[1]; ProgramBuilder program_builder; program_builder.EnterSubexpression(&call); program_builder.EnterSubexpression(&left_condition); ASSERT_OK_AND_ASSIGN( auto step, CreateConstValueStep(value_factory_.CreateBoolValue(true), -1)); program_builder.AddStep(std::move(step)); program_builder.ExitSubexpression(&left_condition); program_builder.EnterSubexpression(&right_condition); ASSERT_OK_AND_ASSIGN( step, CreateConstValueStep(value_factory_.CreateBoolValue(false), -1)); program_builder.AddStep(std::move(step)); program_builder.ExitSubexpression(&right_condition); ASSERT_OK_AND_ASSIGN(step, CreateConstValueStep(value_factory_.GetNullValue(), -1)); program_builder.AddStep(std::move(step)); program_builder.ExitSubexpression(&call); PlannerContext context(resolver_, options_, value_factory_, issue_collector_, program_builder); google::protobuf::Arena arena; ProgramOptimizerFactory constant_folder_factory = CreateConstantFoldingOptimizer(ProtoMemoryManagerRef(&arena_)); ASSERT_OK_AND_ASSIGN(std::unique_ptr<ProgramOptimizer> constant_folder, constant_folder_factory(context, ast_impl)); EXPECT_THAT(constant_folder->OnPostVisit(context, left_condition), StatusIs(absl::StatusCode::kInternal)); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/compiler/constant_folding.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/compiler/constant_folding_test.cc
4552db5798fb0853b131b783d8875794334fae7f
3e1b80d3-4273-4518-9418-e44c3c9984a2
cpp
google/cel-cpp
optional_types
runtime/optional_types.cc
runtime/optional_types_test.cc
#include "runtime/optional_types.h" #include <cstddef> #include <cstdint> #include <limits> #include <memory> #include <string> #include <tuple> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "base/function_adapter.h" #include "common/casting.h" #include "common/type.h" #include "common/type_reflector.h" #include "common/value.h" #include "common/value_manager.h" #include "internal/casts.h" #include "internal/number.h" #include "internal/status_macros.h" #include "runtime/function_registry.h" #include "runtime/internal/errors.h" #include "runtime/internal/runtime_friend_access.h" #include "runtime/internal/runtime_impl.h" #include "runtime/runtime_builder.h" #include "runtime/runtime_options.h" namespace cel::extensions { namespace { Value OptionalOf(ValueManager& value_manager, const Value& value) { return OptionalValue::Of(value_manager.GetMemoryManager(), value); } Value OptionalNone(ValueManager&) { return OptionalValue::None(); } Value OptionalOfNonZeroValue(ValueManager& value_manager, const Value& value) { if (value.IsZeroValue()) { return OptionalNone(value_manager); } return OptionalOf(value_manager, value); } absl::StatusOr<Value> OptionalGetValue(ValueManager& value_manager, const OpaqueValue& opaque_value) { if (auto optional_value = As<OptionalValue>(opaque_value); optional_value) { return optional_value->Value(); } return ErrorValue{runtime_internal::CreateNoMatchingOverloadError("value")}; } absl::StatusOr<Value> OptionalHasValue(ValueManager& value_manager, const OpaqueValue& opaque_value) { if (auto optional_value = As<OptionalValue>(opaque_value); optional_value) { return BoolValue{optional_value->HasValue()}; } return ErrorValue{ runtime_internal::CreateNoMatchingOverloadError("hasValue")}; } absl::StatusOr<Value> SelectOptionalFieldStruct(ValueManager& value_manager, const StructValue& struct_value, const StringValue& key) { std::string field_name; auto field_name_view = key.NativeString(field_name); CEL_ASSIGN_OR_RETURN(auto has_field, struct_value.HasFieldByName(field_name_view)); if (!has_field) { return OptionalValue::None(); } CEL_ASSIGN_OR_RETURN( auto field, struct_value.GetFieldByName(value_manager, field_name_view)); return OptionalValue::Of(value_manager.GetMemoryManager(), std::move(field)); } absl::StatusOr<Value> SelectOptionalFieldMap(ValueManager& value_manager, const MapValue& map, const StringValue& key) { Value value; bool ok; CEL_ASSIGN_OR_RETURN(std::tie(value, ok), map.Find(value_manager, key)); if (ok) { return OptionalValue::Of(value_manager.GetMemoryManager(), std::move(value)); } return OptionalValue::None(); } absl::StatusOr<Value> SelectOptionalField(ValueManager& value_manager, const OpaqueValue& opaque_value, const StringValue& key) { if (auto optional_value = As<OptionalValue>(opaque_value); optional_value) { if (!optional_value->HasValue()) { return OptionalValue::None(); } auto container = optional_value->Value(); if (auto map_value = As<MapValue>(container); map_value) { return SelectOptionalFieldMap(value_manager, *map_value, key); } if (auto struct_value = As<StructValue>(container); struct_value) { return SelectOptionalFieldStruct(value_manager, *struct_value, key); } } return ErrorValue{runtime_internal::CreateNoMatchingOverloadError("_[?_]")}; } absl::StatusOr<Value> MapOptIndexOptionalValue(ValueManager& value_manager, const MapValue& map, const Value& key) { Value value; bool ok; if (auto double_key = cel::As<DoubleValue>(key); double_key) { auto number = internal::Number::FromDouble(double_key->NativeValue()); if (number.LosslessConvertibleToInt()) { CEL_ASSIGN_OR_RETURN(std::tie(value, ok), map.Find(value_manager, IntValue{number.AsInt()})); if (ok) { return OptionalValue::Of(value_manager.GetMemoryManager(), std::move(value)); } } if (number.LosslessConvertibleToUint()) { CEL_ASSIGN_OR_RETURN(std::tie(value, ok), map.Find(value_manager, UintValue{number.AsUint()})); if (ok) { return OptionalValue::Of(value_manager.GetMemoryManager(), std::move(value)); } } } else { CEL_ASSIGN_OR_RETURN(std::tie(value, ok), map.Find(value_manager, key)); if (ok) { return OptionalValue::Of(value_manager.GetMemoryManager(), std::move(value)); } if (auto int_key = cel::As<IntValue>(key); int_key && int_key->NativeValue() >= 0) { CEL_ASSIGN_OR_RETURN( std::tie(value, ok), map.Find(value_manager, UintValue{static_cast<uint64_t>(int_key->NativeValue())})); if (ok) { return OptionalValue::Of(value_manager.GetMemoryManager(), std::move(value)); } } else if (auto uint_key = cel::As<UintValue>(key); uint_key && uint_key->NativeValue() <= static_cast<uint64_t>(std::numeric_limits<int64_t>::max())) { CEL_ASSIGN_OR_RETURN( std::tie(value, ok), map.Find(value_manager, IntValue{static_cast<int64_t>(uint_key->NativeValue())})); if (ok) { return OptionalValue::Of(value_manager.GetMemoryManager(), std::move(value)); } } } return OptionalValue::None(); } absl::StatusOr<Value> ListOptIndexOptionalInt(ValueManager& value_manager, const ListValue& list, int64_t key) { CEL_ASSIGN_OR_RETURN(auto list_size, list.Size()); if (key < 0 || static_cast<size_t>(key) >= list_size) { return OptionalValue::None(); } CEL_ASSIGN_OR_RETURN(auto element, list.Get(value_manager, static_cast<size_t>(key))); return OptionalValue::Of(value_manager.GetMemoryManager(), std::move(element)); } absl::StatusOr<Value> OptionalOptIndexOptionalValue( ValueManager& value_manager, const OpaqueValue& opaque_value, const Value& key) { if (auto optional_value = As<OptionalValue>(opaque_value); optional_value) { if (!optional_value->HasValue()) { return OptionalValue::None(); } auto container = optional_value->Value(); if (auto map_value = cel::As<MapValue>(container); map_value) { return MapOptIndexOptionalValue(value_manager, *map_value, key); } if (auto list_value = cel::As<ListValue>(container); list_value) { if (auto int_value = cel::As<IntValue>(key); int_value) { return ListOptIndexOptionalInt(value_manager, *list_value, int_value->NativeValue()); } } } return ErrorValue{runtime_internal::CreateNoMatchingOverloadError("_[?_]")}; } absl::Status RegisterOptionalTypeFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { if (!options.enable_qualified_type_identifiers) { return absl::FailedPreconditionError( "optional_type requires " "RuntimeOptions.enable_qualified_type_identifiers"); } if (!options.enable_heterogeneous_equality) { return absl::FailedPreconditionError( "optional_type requires RuntimeOptions.enable_heterogeneous_equality"); } CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, Value>::CreateDescriptor("optional.of", false), UnaryFunctionAdapter<Value, Value>::WrapFunction(&OptionalOf))); CEL_RETURN_IF_ERROR( registry.Register(UnaryFunctionAdapter<Value, Value>::CreateDescriptor( "optional.ofNonZeroValue", false), UnaryFunctionAdapter<Value, Value>::WrapFunction( &OptionalOfNonZeroValue))); CEL_RETURN_IF_ERROR(registry.Register( VariadicFunctionAdapter<Value>::CreateDescriptor("optional.none", false), VariadicFunctionAdapter<Value>::WrapFunction(&OptionalNone))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<absl::StatusOr<Value>, OpaqueValue>::CreateDescriptor("value", true), UnaryFunctionAdapter<absl::StatusOr<Value>, OpaqueValue>::WrapFunction( &OptionalGetValue))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<absl::StatusOr<Value>, OpaqueValue>::CreateDescriptor("hasValue", true), UnaryFunctionAdapter<absl::StatusOr<Value>, OpaqueValue>::WrapFunction( &OptionalHasValue))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<absl::StatusOr<Value>, StructValue, StringValue>::CreateDescriptor("_?._", false), BinaryFunctionAdapter<absl::StatusOr<Value>, StructValue, StringValue>:: WrapFunction(&SelectOptionalFieldStruct))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<absl::StatusOr<Value>, MapValue, StringValue>::CreateDescriptor("_?._", false), BinaryFunctionAdapter<absl::StatusOr<Value>, MapValue, StringValue>:: WrapFunction(&SelectOptionalFieldMap))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<absl::StatusOr<Value>, OpaqueValue, StringValue>::CreateDescriptor("_?._", false), BinaryFunctionAdapter<absl::StatusOr<Value>, OpaqueValue, StringValue>::WrapFunction(&SelectOptionalField))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<absl::StatusOr<Value>, MapValue, Value>::CreateDescriptor("_[?_]", false), BinaryFunctionAdapter<absl::StatusOr<Value>, MapValue, Value>::WrapFunction(&MapOptIndexOptionalValue))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<absl::StatusOr<Value>, ListValue, int64_t>::CreateDescriptor("_[?_]", false), BinaryFunctionAdapter<absl::StatusOr<Value>, ListValue, int64_t>::WrapFunction(&ListOptIndexOptionalInt))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<absl::StatusOr<Value>, OpaqueValue, Value>::CreateDescriptor("_[?_]", false), BinaryFunctionAdapter<absl::StatusOr<Value>, OpaqueValue, Value>:: WrapFunction(&OptionalOptIndexOptionalValue))); return absl::OkStatus(); } class OptionalTypeProvider final : public TypeReflector { protected: absl::StatusOr<absl::optional<Type>> FindTypeImpl( TypeFactory&, absl::string_view name) const override { if (name != "optional_type") { return absl::nullopt; } return OptionalType{}; } }; } absl::Status EnableOptionalTypes(RuntimeBuilder& builder) { auto& runtime = cel::internal::down_cast<runtime_internal::RuntimeImpl&>( runtime_internal::RuntimeFriendAccess::GetMutableRuntime(builder)); CEL_RETURN_IF_ERROR(RegisterOptionalTypeFunctions( builder.function_registry(), runtime.expr_builder().options())); builder.type_registry().AddTypeProvider( std::make_unique<OptionalTypeProvider>()); runtime.expr_builder().enable_optional_types(); return absl::OkStatus(); } }
#include "runtime/optional_types.h" #include <cstdint> #include <memory> #include <ostream> #include <string> #include <utility> #include <vector> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "base/function.h" #include "base/function_descriptor.h" #include "common/kind.h" #include "common/memory.h" #include "common/value.h" #include "common/value_testing.h" #include "common/values/legacy_value_manager.h" #include "extensions/protobuf/memory_manager.h" #include "extensions/protobuf/runtime_adapter.h" #include "internal/testing.h" #include "parser/options.h" #include "parser/parser.h" #include "runtime/activation.h" #include "runtime/internal/runtime_impl.h" #include "runtime/reference_resolver.h" #include "runtime/runtime.h" #include "runtime/runtime_builder.h" #include "runtime/runtime_options.h" #include "runtime/standard_runtime_builder_factory.h" #include "google/protobuf/arena.h" namespace cel::extensions { namespace { using ::absl_testing::IsOk; using ::absl_testing::StatusIs; using ::cel::extensions::ProtobufRuntimeAdapter; using ::cel::extensions::ProtoMemoryManagerRef; using ::cel::test::BoolValueIs; using ::cel::test::IntValueIs; using ::cel::test::OptionalValueIs; using ::cel::test::OptionalValueIsEmpty; using ::google::api::expr::v1alpha1::ParsedExpr; using ::google::api::expr::parser::Parse; using ::google::api::expr::parser::ParserOptions; using ::testing::ElementsAre; using ::testing::HasSubstr; MATCHER_P(MatchesOptionalReceiver1, name, "") { const FunctionDescriptor& descriptor = arg.descriptor; std::vector<Kind> types{Kind::kOpaque}; return descriptor.name() == name && descriptor.receiver_style() == true && descriptor.types() == types; } MATCHER_P2(MatchesOptionalReceiver2, name, kind, "") { const FunctionDescriptor& descriptor = arg.descriptor; std::vector<Kind> types{Kind::kOpaque, kind}; return descriptor.name() == name && descriptor.receiver_style() == true && descriptor.types() == types; } MATCHER_P2(MatchesOptionalSelect, kind1, kind2, "") { const FunctionDescriptor& descriptor = arg.descriptor; std::vector<Kind> types{kind1, kind2}; return descriptor.name() == "_?._" && descriptor.receiver_style() == false && descriptor.types() == types; } MATCHER_P2(MatchesOptionalIndex, kind1, kind2, "") { const FunctionDescriptor& descriptor = arg.descriptor; std::vector<Kind> types{kind1, kind2}; return descriptor.name() == "_[?_]" && descriptor.receiver_style() == false && descriptor.types() == types; } TEST(EnableOptionalTypes, HeterogeneousEqualityRequired) { ASSERT_OK_AND_ASSIGN(auto builder, CreateStandardRuntimeBuilder(RuntimeOptions{ .enable_qualified_type_identifiers = true, .enable_heterogeneous_equality = false})); EXPECT_THAT(EnableOptionalTypes(builder), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST(EnableOptionalTypes, QualifiedTypeIdentifiersRequired) { ASSERT_OK_AND_ASSIGN(auto builder, CreateStandardRuntimeBuilder(RuntimeOptions{ .enable_qualified_type_identifiers = false, .enable_heterogeneous_equality = true})); EXPECT_THAT(EnableOptionalTypes(builder), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST(EnableOptionalTypes, PreconditionsSatisfied) { ASSERT_OK_AND_ASSIGN(auto builder, CreateStandardRuntimeBuilder(RuntimeOptions{ .enable_qualified_type_identifiers = true, .enable_heterogeneous_equality = true})); EXPECT_THAT(EnableOptionalTypes(builder), IsOk()); } TEST(EnableOptionalTypes, Functions) { ASSERT_OK_AND_ASSIGN(auto builder, CreateStandardRuntimeBuilder(RuntimeOptions{ .enable_qualified_type_identifiers = true, .enable_heterogeneous_equality = true})); ASSERT_THAT(EnableOptionalTypes(builder), IsOk()); EXPECT_THAT(builder.function_registry().FindStaticOverloads("hasValue", true, {Kind::kOpaque}), ElementsAre(MatchesOptionalReceiver1("hasValue"))); EXPECT_THAT(builder.function_registry().FindStaticOverloads("value", true, {Kind::kOpaque}), ElementsAre(MatchesOptionalReceiver1("value"))); EXPECT_THAT(builder.function_registry().FindStaticOverloads( "_?._", false, {Kind::kStruct, Kind::kString}), ElementsAre(MatchesOptionalSelect(Kind::kStruct, Kind::kString))); EXPECT_THAT(builder.function_registry().FindStaticOverloads( "_?._", false, {Kind::kMap, Kind::kString}), ElementsAre(MatchesOptionalSelect(Kind::kMap, Kind::kString))); EXPECT_THAT(builder.function_registry().FindStaticOverloads( "_?._", false, {Kind::kOpaque, Kind::kString}), ElementsAre(MatchesOptionalSelect(Kind::kOpaque, Kind::kString))); EXPECT_THAT(builder.function_registry().FindStaticOverloads( "_[?_]", false, {Kind::kMap, Kind::kAny}), ElementsAre(MatchesOptionalIndex(Kind::kMap, Kind::kAny))); EXPECT_THAT(builder.function_registry().FindStaticOverloads( "_[?_]", false, {Kind::kList, Kind::kInt}), ElementsAre(MatchesOptionalIndex(Kind::kList, Kind::kInt))); EXPECT_THAT(builder.function_registry().FindStaticOverloads( "_[?_]", false, {Kind::kOpaque, Kind::kAny}), ElementsAre(MatchesOptionalIndex(Kind::kOpaque, Kind::kAny))); } struct EvaluateResultTestCase { std::string name; std::string expression; test::ValueMatcher value_matcher; }; class OptionalTypesTest : public common_internal::ThreadCompatibleValueTest<EvaluateResultTestCase, bool> { public: const EvaluateResultTestCase& GetTestCase() { return std::get<1>(GetParam()); } bool EnableShortCircuiting() { return std::get<2>(GetParam()); } }; std::ostream& operator<<(std::ostream& os, const EvaluateResultTestCase& test_case) { return os << test_case.name; } TEST_P(OptionalTypesTest, RecursivePlan) { RuntimeOptions opts; opts.use_legacy_container_builders = false; opts.enable_qualified_type_identifiers = true; opts.max_recursion_depth = -1; opts.short_circuiting = EnableShortCircuiting(); const EvaluateResultTestCase& test_case = GetTestCase(); ASSERT_OK_AND_ASSIGN(auto builder, CreateStandardRuntimeBuilder(opts)); ASSERT_OK(EnableOptionalTypes(builder)); ASSERT_OK( EnableReferenceResolver(builder, ReferenceResolverEnabled::kAlways)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); ASSERT_OK_AND_ASSIGN(ParsedExpr expr, Parse(test_case.expression, "<input>", ParserOptions{.enable_optional_syntax = true})); ASSERT_OK_AND_ASSIGN(std::unique_ptr<Program> program, ProtobufRuntimeAdapter::CreateProgram(*runtime, expr)); EXPECT_TRUE(runtime_internal::TestOnly_IsRecursiveImpl(program.get())); cel::common_internal::LegacyValueManager value_factory( memory_manager(), runtime->GetTypeProvider()); Activation activation; ASSERT_OK_AND_ASSIGN(Value result, program->Evaluate(activation, value_factory)); EXPECT_THAT(result, test_case.value_matcher) << test_case.expression; } TEST_P(OptionalTypesTest, Defaults) { RuntimeOptions opts; opts.use_legacy_container_builders = false; opts.enable_qualified_type_identifiers = true; opts.short_circuiting = EnableShortCircuiting(); const EvaluateResultTestCase& test_case = GetTestCase(); ASSERT_OK_AND_ASSIGN(auto builder, CreateStandardRuntimeBuilder(opts)); ASSERT_OK(EnableOptionalTypes(builder)); ASSERT_OK( EnableReferenceResolver(builder, ReferenceResolverEnabled::kAlways)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); ASSERT_OK_AND_ASSIGN(ParsedExpr expr, Parse(test_case.expression, "<input>", ParserOptions{.enable_optional_syntax = true})); ASSERT_OK_AND_ASSIGN(std::unique_ptr<Program> program, ProtobufRuntimeAdapter::CreateProgram(*runtime, expr)); common_internal::LegacyValueManager value_factory(this->memory_manager(), runtime->GetTypeProvider()); Activation activation; ASSERT_OK_AND_ASSIGN(Value result, program->Evaluate(activation, value_factory)); EXPECT_THAT(result, test_case.value_matcher) << test_case.expression; } INSTANTIATE_TEST_SUITE_P( Basic, OptionalTypesTest, testing::Combine( testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), testing::ValuesIn(std::vector<EvaluateResultTestCase>{ {"optional_none_hasValue", "optional.none().hasValue()", BoolValueIs(false)}, {"optional_of_hasValue", "optional.of(0).hasValue()", BoolValueIs(true)}, {"optional_ofNonZeroValue_hasValue", "optional.ofNonZeroValue(0).hasValue()", BoolValueIs(false)}, {"optional_or_absent", "optional.ofNonZeroValue(0).or(optional.ofNonZeroValue(0))", OptionalValueIsEmpty()}, {"optional_or_present", "optional.of(1).or(optional.none())", OptionalValueIs(IntValueIs(1))}, {"optional_orValue_absent", "optional.ofNonZeroValue(0).orValue(1)", IntValueIs(1)}, {"optional_orValue_present", "optional.of(1).orValue(2)", IntValueIs(1)}, {"list_of_optional", "[optional.of(1)][0].orValue(1)", IntValueIs(1)}}), testing::Bool()), OptionalTypesTest::ToString); class UnreachableFunction final : public cel::Function { public: explicit UnreachableFunction(int64_t* count) : count_(count) {} absl::StatusOr<Value> Invoke(const InvokeContext& context, absl::Span<const Value> args) const override { ++(*count_); return ErrorValue{absl::CancelledError()}; } private: int64_t* const count_; }; TEST(OptionalTypesTest, ErrorShortCircuiting) { RuntimeOptions opts{.enable_qualified_type_identifiers = true}; google::protobuf::Arena arena; auto memory_manager = ProtoMemoryManagerRef(&arena); ASSERT_OK_AND_ASSIGN(auto builder, CreateStandardRuntimeBuilder(opts)); int64_t unreachable_count = 0; ASSERT_OK(EnableOptionalTypes(builder)); ASSERT_OK( EnableReferenceResolver(builder, ReferenceResolverEnabled::kAlways)); ASSERT_OK(builder.function_registry().Register( cel::FunctionDescriptor("unreachable", false, {}), std::make_unique<UnreachableFunction>(&unreachable_count))); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); ASSERT_OK_AND_ASSIGN( ParsedExpr expr, Parse("optional.of(1 / 0).orValue(unreachable())", "<input>", ParserOptions{.enable_optional_syntax = true})); ASSERT_OK_AND_ASSIGN(std::unique_ptr<Program> program, ProtobufRuntimeAdapter::CreateProgram(*runtime, expr)); common_internal::LegacyValueManager value_factory(memory_manager, runtime->GetTypeProvider()); Activation activation; ASSERT_OK_AND_ASSIGN(Value result, program->Evaluate(activation, value_factory)); EXPECT_EQ(unreachable_count, 0); ASSERT_TRUE(result->Is<ErrorValue>()) << result->DebugString(); EXPECT_THAT(result.GetError().NativeValue(), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("divide by zero"))); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/optional_types.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/optional_types_test.cc
4552db5798fb0853b131b783d8875794334fae7f
3547d5cb-7ad4-457b-ab9e-e07a7ac34934
cpp
google/cel-cpp
standard_runtime_builder_factory
runtime/standard_runtime_builder_factory.cc
runtime/standard_runtime_builder_factory_test.cc
#include "runtime/standard_runtime_builder_factory.h" #include "absl/status/statusor.h" #include "internal/status_macros.h" #include "runtime/runtime_builder.h" #include "runtime/runtime_builder_factory.h" #include "runtime/runtime_options.h" #include "runtime/standard_functions.h" namespace cel { absl::StatusOr<RuntimeBuilder> CreateStandardRuntimeBuilder( const RuntimeOptions& options) { RuntimeBuilder result = CreateRuntimeBuilder(options); CEL_RETURN_IF_ERROR( RegisterStandardFunctions(result.function_registry(), options)); return result; } }
#include "runtime/standard_runtime_builder_factory.h" #include <functional> #include <memory> #include <ostream> #include <string> #include <utility> #include <vector> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/base/no_destructor.h" #include "absl/log/absl_check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "common/memory.h" #include "common/source.h" #include "common/value.h" #include "common/value_manager.h" #include "common/value_testing.h" #include "common/values/legacy_value_manager.h" #include "extensions/bindings_ext.h" #include "extensions/protobuf/memory_manager.h" #include "extensions/protobuf/runtime_adapter.h" #include "internal/testing.h" #include "parser/macro_registry.h" #include "parser/parser.h" #include "parser/standard_macros.h" #include "runtime/activation.h" #include "runtime/internal/runtime_impl.h" #include "runtime/managed_value_factory.h" #include "runtime/runtime.h" #include "runtime/runtime_issue.h" #include "runtime/runtime_options.h" #include "google/protobuf/arena.h" namespace cel { namespace { using ::cel::extensions::ProtobufRuntimeAdapter; using ::cel::extensions::ProtoMemoryManagerRef; using ::cel::test::BoolValueIs; using ::google::api::expr::v1alpha1::ParsedExpr; using ::google::api::expr::parser::Parse; using ::testing::ElementsAre; using ::testing::Truly; struct EvaluateResultTestCase { std::string name; std::string expression; bool expected_result; std::function<absl::Status(ValueManager&, Activation&)> activation_builder; }; std::ostream& operator<<(std::ostream& os, const EvaluateResultTestCase& test_case) { return os << test_case.name; } const cel::MacroRegistry& GetMacros() { static absl::NoDestructor<cel::MacroRegistry> macros([]() { MacroRegistry registry; ABSL_CHECK_OK(cel::RegisterStandardMacros(registry, {})); for (const auto& macro : extensions::bindings_macros()) { ABSL_CHECK_OK(registry.RegisterMacro(macro)); } return registry; }()); return *macros; } absl::StatusOr<ParsedExpr> ParseWithTestMacros(absl::string_view expression) { auto src = cel::NewSource(expression, "<input>"); ABSL_CHECK_OK(src.status()); return Parse(**src, GetMacros()); } class StandardRuntimeTest : public common_internal::ThreadCompatibleValueTest< EvaluateResultTestCase> { public: const EvaluateResultTestCase& GetTestCase() { return std::get<1>(GetParam()); } }; TEST_P(StandardRuntimeTest, Defaults) { RuntimeOptions opts; const EvaluateResultTestCase& test_case = GetTestCase(); ASSERT_OK_AND_ASSIGN(auto builder, CreateStandardRuntimeBuilder(opts)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); ASSERT_OK_AND_ASSIGN(ParsedExpr expr, ParseWithTestMacros(test_case.expression)); ASSERT_OK_AND_ASSIGN(std::unique_ptr<Program> program, ProtobufRuntimeAdapter::CreateProgram(*runtime, expr)); EXPECT_FALSE(runtime_internal::TestOnly_IsRecursiveImpl(program.get())); common_internal::LegacyValueManager value_factory(memory_manager(), runtime->GetTypeProvider()); Activation activation; if (test_case.activation_builder != nullptr) { ASSERT_OK(test_case.activation_builder(value_factory, activation)); } ASSERT_OK_AND_ASSIGN(Value result, program->Evaluate(activation, value_factory)); EXPECT_THAT(result, BoolValueIs(test_case.expected_result)) << test_case.expression; } TEST_P(StandardRuntimeTest, Recursive) { RuntimeOptions opts; opts.max_recursion_depth = -1; const EvaluateResultTestCase& test_case = GetTestCase(); ASSERT_OK_AND_ASSIGN(auto builder, CreateStandardRuntimeBuilder(opts)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); ASSERT_OK_AND_ASSIGN(ParsedExpr expr, ParseWithTestMacros(test_case.expression)); ASSERT_OK_AND_ASSIGN(std::unique_ptr<Program> program, ProtobufRuntimeAdapter::CreateProgram(*runtime, expr)); EXPECT_TRUE(runtime_internal::TestOnly_IsRecursiveImpl(program.get())); common_internal::LegacyValueManager value_factory(memory_manager(), runtime->GetTypeProvider()); Activation activation; if (test_case.activation_builder != nullptr) { ASSERT_OK(test_case.activation_builder(value_factory, activation)); } ASSERT_OK_AND_ASSIGN(Value result, program->Evaluate(activation, value_factory)); EXPECT_THAT(result, BoolValueIs(test_case.expected_result)) << test_case.expression; } INSTANTIATE_TEST_SUITE_P( Basic, StandardRuntimeTest, testing::Combine( testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), testing::ValuesIn(std::vector<EvaluateResultTestCase>{ {"int_identifier", "int_var == 42", true, [](ValueManager& value_factory, Activation& activation) { activation.InsertOrAssignValue("int_var", value_factory.CreateIntValue(42)); return absl::OkStatus(); }}, {"logic_and_true", "true && 1 < 2", true}, {"logic_and_false", "true && 1 > 2", false}, {"logic_or_true", "false || 1 < 2", true}, {"logic_or_false", "false && 1 > 2", false}, {"ternary_true_cond", "(1 < 2 ? 'yes' : 'no') == 'yes'", true}, {"ternary_false_cond", "(1 > 2 ? 'yes' : 'no') == 'no'", true}, {"list_index", "['a', 'b', 'c', 'd'][1] == 'b'", true}, {"map_index_bool", "{true: 1, false: 2}[false] == 2", true}, {"map_index_string", "{'abc': 123}['abc'] == 123", true}, {"map_index_int", "{1: 2, 2: 4}[2] == 4", true}, {"map_index_uint", "{1u: 1, 2u: 2}[1u] == 1", true}, {"map_index_coerced_double", "{1: 2, 2: 4}[2.0] == 4", true}, })), StandardRuntimeTest::ToString); INSTANTIATE_TEST_SUITE_P( Equality, StandardRuntimeTest, testing::Combine( testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), testing::ValuesIn(std::vector<EvaluateResultTestCase>{ {"eq_bool_bool_true", "false == false", true}, {"eq_bool_bool_false", "false == true", false}, {"eq_int_int_true", "-1 == -1", true}, {"eq_int_int_false", "-1 == 1", false}, {"eq_uint_uint_true", "2u == 2u", true}, {"eq_uint_uint_false", "2u == 3u", false}, {"eq_double_double_true", "2.4 == 2.4", true}, {"eq_double_double_false", "2.4 == 3.3", false}, {"eq_string_string_true", "'abc' == 'abc'", true}, {"eq_string_string_false", "'abc' == 'def'", false}, {"eq_bytes_bytes_true", "b'abc' == b'abc'", true}, {"eq_bytes_bytes_false", "b'abc' == b'def'", false}, {"eq_duration_duration_true", "duration('15m') == duration('15m')", true}, {"eq_duration_duration_false", "duration('15m') == duration('1h')", false}, {"eq_timestamp_timestamp_true", "timestamp('1970-01-01T00:02:00Z') == " "timestamp('1970-01-01T00:02:00Z')", true}, {"eq_timestamp_timestamp_false", "timestamp('1970-01-01T00:02:00Z') == " "timestamp('2020-01-01T00:02:00Z')", false}, {"eq_null_null_true", "null == null", true}, {"eq_list_list_true", "[1, 2, 3] == [1, 2, 3]", true}, {"eq_list_list_false", "[1, 2, 3] == [1, 2, 3, 4]", false}, {"eq_map_map_true", "{1: 2, 2: 4} == {1: 2, 2: 4}", true}, {"eq_map_map_false", "{1: 2, 2: 4} == {1: 2, 2: 5}", false}, {"neq_bool_bool_true", "false != false", false}, {"neq_bool_bool_false", "false != true", true}, {"neq_int_int_true", "-1 != -1", false}, {"neq_int_int_false", "-1 != 1", true}, {"neq_uint_uint_true", "2u != 2u", false}, {"neq_uint_uint_false", "2u != 3u", true}, {"neq_double_double_true", "2.4 != 2.4", false}, {"neq_double_double_false", "2.4 != 3.3", true}, {"neq_string_string_true", "'abc' != 'abc'", false}, {"neq_string_string_false", "'abc' != 'def'", true}, {"neq_bytes_bytes_true", "b'abc' != b'abc'", false}, {"neq_bytes_bytes_false", "b'abc' != b'def'", true}, {"neq_duration_duration_true", "duration('15m') != duration('15m')", false}, {"neq_duration_duration_false", "duration('15m') != duration('1h')", true}, {"neq_timestamp_timestamp_true", "timestamp('1970-01-01T00:02:00Z') != " "timestamp('1970-01-01T00:02:00Z')", false}, {"neq_timestamp_timestamp_false", "timestamp('1970-01-01T00:02:00Z') != " "timestamp('2020-01-01T00:02:00Z')", true}, {"neq_null_null_true", "null != null", false}, {"neq_list_list_true", "[1, 2, 3] != [1, 2, 3]", false}, {"neq_list_list_false", "[1, 2, 3] != [1, 2, 3, 4]", true}, {"neq_map_map_true", "{1: 2, 2: 4} != {1: 2, 2: 4}", false}, {"neq_map_map_false", "{1: 2, 2: 4} != {1: 2, 2: 5}", true}})), StandardRuntimeTest::ToString); INSTANTIATE_TEST_SUITE_P( ArithmeticFunctions, StandardRuntimeTest, testing::Combine( testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), testing::ValuesIn(std::vector<EvaluateResultTestCase>{ {"lt_int_int_true", "-1 < 2", true}, {"lt_int_int_false", "2 < -1", false}, {"lt_double_double_true", "-1.1 < 2.2", true}, {"lt_double_double_false", "2.2 < -1.1", false}, {"lt_uint_uint_true", "1u < 2u", true}, {"lt_uint_uint_false", "2u < 1u", false}, {"lt_string_string_true", "'abc' < 'def'", true}, {"lt_string_string_false", "'def' < 'abc'", false}, {"lt_duration_duration_true", "duration('1s') < duration('2s')", true}, {"lt_duration_duration_false", "duration('2s') < duration('1s')", false}, {"lt_timestamp_timestamp_true", "timestamp(1) < timestamp(2)", true}, {"lt_timestamp_timestamp_false", "timestamp(2) < timestamp(1)", false}, {"gt_int_int_false", "-1 > 2", false}, {"gt_int_int_true", "2 > -1", true}, {"gt_double_double_false", "-1.1 > 2.2", false}, {"gt_double_double_true", "2.2 > -1.1", true}, {"gt_uint_uint_false", "1u > 2u", false}, {"gt_uint_uint_true", "2u > 1u", true}, {"gt_string_string_false", "'abc' > 'def'", false}, {"gt_string_string_true", "'def' > 'abc'", true}, {"gt_duration_duration_false", "duration('1s') > duration('2s')", false}, {"gt_duration_duration_true", "duration('2s') > duration('1s')", true}, {"gt_timestamp_timestamp_false", "timestamp(1) > timestamp(2)", false}, {"gt_timestamp_timestamp_true", "timestamp(2) > timestamp(1)", true}, {"le_int_int_true", "-1 <= -1", true}, {"le_int_int_false", "2 <= -1", false}, {"le_double_double_true", "-1.1 <= -1.1", true}, {"le_double_double_false", "2.2 <= -1.1", false}, {"le_uint_uint_true", "1u <= 1u", true}, {"le_uint_uint_false", "2u <= 1u", false}, {"le_string_string_true", "'abc' <= 'abc'", true}, {"le_string_string_false", "'def' <= 'abc'", false}, {"le_duration_duration_true", "duration('1s') <= duration('1s')", true}, {"le_duration_duration_false", "duration('2s') <= duration('1s')", false}, {"le_timestamp_timestamp_true", "timestamp(1) <= timestamp(1)", true}, {"le_timestamp_timestamp_false", "timestamp(2) <= timestamp(1)", false}, {"ge_int_int_false", "-1 >= 2", false}, {"ge_int_int_true", "2 >= 2", true}, {"ge_double_double_false", "-1.1 >= 2.2", false}, {"ge_double_double_true", "2.2 >= 2.2", true}, {"ge_uint_uint_false", "1u >= 2u", false}, {"ge_uint_uint_true", "2u >= 2u", true}, {"ge_string_string_false", "'abc' >= 'def'", false}, {"ge_string_string_true", "'abc' >= 'abc'", true}, {"ge_duration_duration_false", "duration('1s') >= duration('2s')", false}, {"ge_duration_duration_true", "duration('1s') >= duration('1s')", true}, {"ge_timestamp_timestamp_false", "timestamp(1) >= timestamp(2)", false}, {"ge_timestamp_timestamp_true", "timestamp(1) >= timestamp(1)", true}, {"sum_int_int", "1 + 2 == 3", true}, {"sum_uint_uint", "3u + 4u == 7", true}, {"sum_double_double", "1.0 + 2.5 == 3.5", true}, {"sum_duration_duration", "duration('2m') + duration('30s') == duration('150s')", true}, {"sum_time_duration", "timestamp(0) + duration('2m') == " "timestamp('1970-01-01T00:02:00Z')", true}, {"difference_int_int", "1 - 2 == -1", true}, {"difference_uint_uint", "4u - 3u == 1u", true}, {"difference_double_double", "1.0 - 2.5 == -1.5", true}, {"difference_duration_duration", "duration('5m') - duration('45s') == duration('4m15s')", true}, {"difference_time_time", "timestamp(10) - timestamp(0) == duration('10s')", true}, {"difference_time_duration", "timestamp(0) - duration('2m') == " "timestamp('1969-12-31T23:58:00Z')", true}, {"multiplication_int_int", "2 * 3 == 6", true}, {"multiplication_uint_uint", "2u * 3u == 6u", true}, {"multiplication_double_double", "2.5 * 3.0 == 7.5", true}, {"division_int_int", "6 / 3 == 2", true}, {"division_uint_uint", "8u / 4u == 2u", true}, {"division_double_double", "1.0 / 0.0 == double('inf')", true}, {"modulo_int_int", "6 % 4 == 2", true}, {"modulo_uint_uint", "8u % 5u == 3u", true}, })), StandardRuntimeTest::ToString); INSTANTIATE_TEST_SUITE_P( Macros, StandardRuntimeTest, testing::Combine(testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), testing::ValuesIn(std::vector<EvaluateResultTestCase>{ {"map", "[1, 2, 3, 4].map(x, x * x)[3] == 16", true}, {"filter", "[1, 2, 3, 4].filter(x, x < 4).size() == 3", true}, {"exists", "[1, 2, 3, 4].exists(x, x < 4)", true}, {"all", "[1, 2, 3, 4].all(x, x < 5)", true}})), StandardRuntimeTest::ToString); INSTANTIATE_TEST_SUITE_P( StringFunctions, StandardRuntimeTest, testing::Combine( testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), testing::ValuesIn(std::vector<EvaluateResultTestCase>{ {"string_contains", "'tacocat'.contains('acoca')", true}, {"string_contains_global", "contains('tacocat', 'dog')", false}, {"string_ends_with", "'abcdefg'.endsWith('efg')", true}, {"string_ends_with_global", "endsWith('abcdefg', 'fgh')", false}, {"string_starts_with", "'abcdefg'.startsWith('abc')", true}, {"string_starts_with_global", "startsWith('abcd', 'bcd')", false}, {"string_size", "'Hello World! 😀'.size() == 14", true}, {"string_size_global", "size('Hello world!') == 12", true}, {"bytes_size", "b'0123'.size() == 4", true}, {"bytes_size_global", "size(b'😀') == 4", true}})), StandardRuntimeTest::ToString); INSTANTIATE_TEST_SUITE_P( RegExFunctions, StandardRuntimeTest, testing::Combine( testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), testing::ValuesIn(std::vector<EvaluateResultTestCase>{ {"matches_string_re", "'127.0.0.1'.matches(r'127\\.\\d+\\.\\d+\\.\\d+')", true}, {"matches_string_re_global", "matches('192.168.0.1', r'127\\.\\d+\\.\\d+\\.\\d+')", false}})), StandardRuntimeTest::ToString); INSTANTIATE_TEST_SUITE_P( TimeFunctions, StandardRuntimeTest, testing::Combine( testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), testing::ValuesIn(std::vector<EvaluateResultTestCase>{ {"timestamp_get_full_year", "timestamp('2001-02-03T04:05:06.007Z').getFullYear() == 2001", true}, {"timestamp_get_date", "timestamp('2001-02-03T04:05:06.007Z').getDate() == 3", true}, {"timestamp_get_hours", "timestamp('2001-02-03T04:05:06.007Z').getHours() == 4", true}, {"timestamp_get_minutes", "timestamp('2001-02-03T04:05:06.007Z').getMinutes() == 5", true}, {"timestamp_get_seconds", "timestamp('2001-02-03T04:05:06.007Z').getSeconds() == 6", true}, {"timestamp_get_milliseconds", "timestamp('2001-02-03T04:05:06.007Z').getMilliseconds() == 7", true}, {"timestamp_get_month", "timestamp('2001-02-03T04:05:06.007Z').getMonth() == 1", true}, {"timestamp_get_day_of_year", "timestamp('2001-02-03T04:05:06.007Z').getDayOfYear() == 33", true}, {"timestamp_get_day_of_month", "timestamp('2001-02-03T04:05:06.007Z').getDayOfMonth() == 2", true}, {"timestamp_get_day_of_week", "timestamp('2001-02-03T04:05:06.007Z').getDayOfWeek() == 6", true}, {"duration_get_hours", "duration('10h20m30s40ms').getHours() == 10", true}, {"duration_get_minutes", "duration('10h20m30s40ms').getMinutes() == 20 + 600", true}, {"duration_get_seconds", "duration('10h20m30s40ms').getSeconds() == 30 + 20 * 60 + 10 * 60 " "* " "60", true}, {"duration_get_milliseconds", "duration('10h20m30s40ms').getMilliseconds() == 40", true}, })), StandardRuntimeTest::ToString); INSTANTIATE_TEST_SUITE_P( TypeConversionFunctions, StandardRuntimeTest, testing::Combine( testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), testing::ValuesIn(std::vector<EvaluateResultTestCase>{ {"string_timestamp", "string(timestamp(1)) == '1970-01-01T00:00:01Z'", true}, {"string_duration", "string(duration('10m30s')) == '630s'", true}, {"string_int", "string(-1) == '-1'", true}, {"string_uint", "string(1u) == '1'", true}, {"string_double", "string(double('inf')) == 'inf'", true}, {"string_bytes", R"(string(b'\xF0\x9F\x98\x80') == '😀')", true}, {"string_string", "string('hello!') == 'hello!'", true}, {"bytes_bytes", "bytes(b'123') == b'123'", true}, {"bytes_string", "bytes('😀') == b'\xF0\x9F\x98\x80'", true}, {"timestamp", "timestamp(1) == timestamp('1970-01-01T00:00:01Z')", true}, {"duration", "duration('10h') == duration('600m')", true}, {"double_string", "double('1.0') == 1.0", true}, {"double_string_nan", "double('nan') != double('nan')", true}, {"double_int", "double(1) == 1.0", true}, {"double_uint", "double(1u) == 1.0", true}, {"double_double", "double(1.0) == 1.0", true}, {"uint_string", "uint('1') == 1u", true}, {"uint_int", "uint(1) == 1u", true}, {"uint_uint", "uint(1u) == 1u", true}, {"uint_double", "uint(1.1) == 1u", true}, {"int_string", "int('-1') == -1", true}, {"int_int", "int(-1) == -1", true}, {"int_uint", "int(1u) == 1", true}, {"int_double", "int(-1.1) == -1", true}, {"int_timestamp", "int(timestamp('1969-12-31T23:30:00Z')) == -1800", true}, })), StandardRuntimeTest::ToString); INSTANTIATE_TEST_SUITE_P( ContainerFunctions, StandardRuntimeTest, testing::Combine( testing::Values(MemoryManagement::kPooling, MemoryManagement::kReferenceCounting), testing::ValuesIn(std::vector<EvaluateResultTestCase>{ {"map_size", "{'abc': 1, 'def': 2}.size() == 2", true}, {"map_in", "'abc' in {'abc': 1, 'def': 2}", true}, {"map_in_numeric", "1.0 in {1u: 1, 2u: 2}", true}, {"list_size", "[1, 2, 3, 4].size() == 4", true}, {"list_size_global", "size([1, 2, 3]) == 3", true}, {"list_concat", "[1, 2] + [3, 4] == [1, 2, 3, 4]", true}, {"list_in", "'a' in ['a', 'b', 'c', 'd']", true}, {"list_in_numeric", "3u in [1.1, 2.3, 3.0, 4.4]", true}})), StandardRuntimeTest::ToString); TEST(StandardRuntimeTest, RuntimeIssueSupport) { RuntimeOptions options; options.fail_on_warnings = false; google::protobuf::Arena arena; auto memory_manager = ProtoMemoryManagerRef(&arena); ASSERT_OK_AND_ASSIGN(auto builder, CreateStandardRuntimeBuilder(options)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); { ASSERT_OK_AND_ASSIGN(ParsedExpr expr, ParseWithTestMacros("unregistered_function(1)")); std::vector<RuntimeIssue> issues; ASSERT_OK_AND_ASSIGN( std::unique_ptr<Program> program, ProtobufRuntimeAdapter::CreateProgram(*runtime, expr, {&issues})); EXPECT_THAT(issues, ElementsAre(Truly([](const RuntimeIssue& issue) { return issue.severity() == RuntimeIssue::Severity::kWarning && issue.error_code() == RuntimeIssue::ErrorCode::kNoMatchingOverload; }))); } { ASSERT_OK_AND_ASSIGN( ParsedExpr expr, ParseWithTestMacros( "unregistered_function(1) || unregistered_function(2)")); std::vector<RuntimeIssue> issues; ASSERT_OK_AND_ASSIGN( std::unique_ptr<Program> program, ProtobufRuntimeAdapter::CreateProgram(*runtime, expr, {&issues})); EXPECT_THAT( issues, ElementsAre( Truly([](const RuntimeIssue& issue) { return issue.severity() == RuntimeIssue::Severity::kWarning && issue.error_code() == RuntimeIssue::ErrorCode::kNoMatchingOverload; }), Truly([](const RuntimeIssue& issue) { return issue.severity() == RuntimeIssue::Severity::kWarning && issue.error_code() == RuntimeIssue::ErrorCode::kNoMatchingOverload; }))); } { ASSERT_OK_AND_ASSIGN( ParsedExpr expr, ParseWithTestMacros( "unregistered_function(1) || unregistered_function(2) || true")); std::vector<RuntimeIssue> issues; ASSERT_OK_AND_ASSIGN( std::unique_ptr<Program> program, ProtobufRuntimeAdapter::CreateProgram(*runtime, expr, {&issues})); EXPECT_THAT( issues, ElementsAre( Truly([](const RuntimeIssue& issue) { return issue.severity() == RuntimeIssue::Severity::kWarning && issue.error_code() == RuntimeIssue::ErrorCode::kNoMatchingOverload; }), Truly([](const RuntimeIssue& issue) { return issue.severity() == RuntimeIssue::Severity::kWarning && issue.error_code() == RuntimeIssue::ErrorCode::kNoMatchingOverload; }))); ManagedValueFactory value_factory(program->GetTypeProvider(), memory_manager); Activation activation; ASSERT_OK_AND_ASSIGN(auto result, program->Evaluate(activation, value_factory.get())); EXPECT_TRUE(result->Is<BoolValue>() && result.GetBool().NativeValue()); } } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/standard_runtime_builder_factory.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/standard_runtime_builder_factory_test.cc
4552db5798fb0853b131b783d8875794334fae7f
afcc0e7d-5d93-494e-8de0-9fb0bc1f48ef
cpp
google/cel-cpp
comprehension_vulnerability_check
eval/compiler/comprehension_vulnerability_check.cc
runtime/comprehension_vulnerability_check_test.cc
#include "eval/compiler/comprehension_vulnerability_check.h" #include <algorithm> #include <memory> #include <vector> #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "absl/types/variant.h" #include "base/ast_internal/ast_impl.h" #include "base/ast_internal/expr.h" #include "base/builtins.h" #include "eval/compiler/flat_expr_builder_extensions.h" namespace google::api::expr::runtime { namespace { using ::cel::ast_internal::Comprehension; int ComprehensionAccumulationReferences(const cel::ast_internal::Expr& expr, absl::string_view var_name) { struct Handler { const cel::ast_internal::Expr& expr; absl::string_view var_name; int operator()(const cel::ast_internal::Call& call) { int references = 0; absl::string_view function = call.function(); if (function == cel::builtin::kTernary && call.args().size() == 3) { return std::max( ComprehensionAccumulationReferences(call.args()[1], var_name), ComprehensionAccumulationReferences(call.args()[2], var_name)); } if (function == cel::builtin::kAdd) { for (int i = 0; i < call.args().size(); i++) { references += ComprehensionAccumulationReferences(call.args()[i], var_name); } return references; } if ((function == cel::builtin::kIndex && call.args().size() == 2) || (function == cel::builtin::kDyn && call.args().size() == 1)) { return ComprehensionAccumulationReferences(call.args()[0], var_name); } return 0; } int operator()(const cel::ast_internal::Comprehension& comprehension) { absl::string_view accu_var = comprehension.accu_var(); absl::string_view iter_var = comprehension.iter_var(); int result_references = 0; int loop_step_references = 0; int sum_of_accumulator_references = 0; if (accu_var != var_name && iter_var != var_name) { loop_step_references = ComprehensionAccumulationReferences( comprehension.loop_step(), var_name); } if (accu_var != var_name) { result_references = ComprehensionAccumulationReferences( comprehension.result(), var_name); } sum_of_accumulator_references = ComprehensionAccumulationReferences( comprehension.accu_init(), var_name); sum_of_accumulator_references += ComprehensionAccumulationReferences( comprehension.iter_range(), var_name); return std::max({loop_step_references, result_references, sum_of_accumulator_references}); } int operator()(const cel::ast_internal::CreateList& list) { int references = 0; for (int i = 0; i < list.elements().size(); i++) { references += ComprehensionAccumulationReferences( list.elements()[i].expr(), var_name); } return references; } int operator()(const cel::ast_internal::CreateStruct& map) { int references = 0; for (int i = 0; i < map.fields().size(); i++) { const auto& entry = map.fields()[i]; if (entry.has_value()) { references += ComprehensionAccumulationReferences(entry.value(), var_name); } } return references; } int operator()(const cel::MapExpr& map) { int references = 0; for (int i = 0; i < map.entries().size(); i++) { const auto& entry = map.entries()[i]; if (entry.has_value()) { references += ComprehensionAccumulationReferences(entry.value(), var_name); } } return references; } int operator()(const cel::ast_internal::Select& select) { if (select.test_only()) { return 0; } return ComprehensionAccumulationReferences(select.operand(), var_name); } int operator()(const cel::ast_internal::Ident& ident) { return ident.name() == var_name ? 1 : 0; } int operator()(const cel::ast_internal::Constant& constant) { return 0; } int operator()(const cel::UnspecifiedExpr&) { return 0; } } handler{expr, var_name}; return absl::visit(handler, expr.kind()); } bool ComprehensionHasMemoryExhaustionVulnerability( const Comprehension& comprehension) { absl::string_view accu_var = comprehension.accu_var(); const auto& loop_step = comprehension.loop_step(); return ComprehensionAccumulationReferences(loop_step, accu_var) >= 2; } class ComprehensionVulnerabilityCheck : public ProgramOptimizer { public: absl::Status OnPreVisit(PlannerContext& context, const cel::ast_internal::Expr& node) override { if (node.has_comprehension_expr() && ComprehensionHasMemoryExhaustionVulnerability( node.comprehension_expr())) { return absl::InvalidArgumentError( "Comprehension contains memory exhaustion vulnerability"); } return absl::OkStatus(); } absl::Status OnPostVisit(PlannerContext& context, const cel::ast_internal::Expr& node) override { return absl::OkStatus(); } }; } ProgramOptimizerFactory CreateComprehensionVulnerabilityCheck() { return [](PlannerContext&, const cel::ast_internal::AstImpl&) { return std::make_unique<ComprehensionVulnerabilityCheck>(); }; } }
#include "runtime/comprehension_vulnerability_check.h" #include <utility> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "extensions/protobuf/runtime_adapter.h" #include "internal/testing.h" #include "parser/parser.h" #include "runtime/runtime_builder.h" #include "runtime/runtime_options.h" #include "runtime/standard_runtime_builder_factory.h" #include "google/protobuf/text_format.h" namespace cel { namespace { using ::absl_testing::IsOk; using ::absl_testing::StatusIs; using ::cel::extensions::ProtobufRuntimeAdapter; using ::google::api::expr::v1alpha1::ParsedExpr; using ::google::api::expr::parser::Parse; using ::google::protobuf::TextFormat; using ::testing::HasSubstr; constexpr absl::string_view kVulnerableExpr = R"pb( expr { id: 1 comprehension_expr { iter_var: "unused" accu_var: "accu" result { id: 2 ident_expr { name: "accu" } } accu_init { id: 11 list_expr { elements { id: 12 const_expr { int64_value: 0 } } } } loop_condition { id: 13 const_expr { bool_value: true } } loop_step { id: 3 call_expr { function: "_+_" args { id: 4 ident_expr { name: "accu" } } args { id: 5 ident_expr { name: "accu" } } } } iter_range { id: 6 list_expr { elements { id: 7 const_expr { int64_value: 0 } } elements { id: 8 const_expr { int64_value: 0 } } elements { id: 9 const_expr { int64_value: 0 } } elements { id: 10 const_expr { int64_value: 0 } } } } } } )pb"; TEST(ComprehensionVulnerabilityCheck, EnabledVulnerable) { RuntimeOptions runtime_options; ASSERT_OK_AND_ASSIGN(RuntimeBuilder builder, CreateStandardRuntimeBuilder(runtime_options)); ASSERT_OK(EnableComprehensionVulnerabiltyCheck(builder)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); ParsedExpr expr; ASSERT_TRUE(TextFormat::ParseFromString(kVulnerableExpr, &expr)); EXPECT_THAT( ProtobufRuntimeAdapter::CreateProgram(*runtime, expr), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr("Comprehension contains memory exhaustion vulnerability"))); } TEST(ComprehensionVulnerabilityCheck, EnabledNotVulnerable) { RuntimeOptions runtime_options; ASSERT_OK_AND_ASSIGN(RuntimeBuilder builder, CreateStandardRuntimeBuilder(runtime_options)); ASSERT_OK(EnableComprehensionVulnerabiltyCheck(builder)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); ASSERT_OK_AND_ASSIGN(ParsedExpr expr, Parse("[0, 0, 0, 0].map(x, x + 1)")); EXPECT_THAT(ProtobufRuntimeAdapter::CreateProgram(*runtime, expr), IsOk()); } TEST(ComprehensionVulnerabilityCheck, DisabledVulnerable) { RuntimeOptions runtime_options; ASSERT_OK_AND_ASSIGN(RuntimeBuilder builder, CreateStandardRuntimeBuilder(runtime_options)); ASSERT_OK_AND_ASSIGN(auto runtime, std::move(builder).Build()); ParsedExpr expr; ASSERT_TRUE(TextFormat::ParseFromString(kVulnerableExpr, &expr)); EXPECT_THAT(ProtobufRuntimeAdapter::CreateProgram(*runtime, expr), IsOk()); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/compiler/comprehension_vulnerability_check.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/comprehension_vulnerability_check_test.cc
4552db5798fb0853b131b783d8875794334fae7f
578d4096-9bda-4a7a-be74-8cdd6b64c2cb
cpp
google/cel-cpp
mutable_list_impl
runtime/internal/mutable_list_impl.cc
runtime/internal/mutable_list_impl_test.cc
#include "runtime/internal/mutable_list_impl.h" #include <memory> #include <string> #include <utility> #include "common/native_type.h" #include "common/type.h" #include "common/value.h" namespace cel::runtime_internal { using ::cel::NativeTypeId; MutableListValue::MutableListValue( cel::Unique<cel::ListValueBuilder> list_builder) : cel::OpaqueValueInterface(), list_builder_(std::move(list_builder)) {} absl::Status MutableListValue::Append(cel::Value element) { return list_builder_->Add(std::move(element)); } absl::StatusOr<cel::ListValue> MutableListValue::Build() && { return std::move(*list_builder_).Build(); } std::string MutableListValue::DebugString() const { return kMutableListTypeName; } NativeTypeId MutableListValue::GetNativeTypeId() const { return cel::NativeTypeId::For<MutableListValue>(); } }
#include "runtime/internal/mutable_list_impl.h" #include "base/type_provider.h" #include "common/memory.h" #include "common/type.h" #include "common/type_factory.h" #include "common/value.h" #include "common/value_manager.h" #include "common/values/legacy_value_manager.h" #include "internal/testing.h" namespace cel::runtime_internal { namespace { using ::absl_testing::IsOkAndHolds; TEST(MutableListImplValue, Creation) { common_internal::LegacyValueManager value_factory( MemoryManagerRef::ReferenceCounting(), TypeProvider::Builtin()); ASSERT_OK_AND_ASSIGN(auto builder, value_factory.NewListValueBuilder( value_factory.GetDynListType())); auto mutable_list_value = value_factory.GetMemoryManager().MakeShared<MutableListValue>( std::move(builder)); OpaqueValue opaque_handle = mutable_list_value; EXPECT_EQ(NativeTypeId::Of(opaque_handle), NativeTypeId::For<MutableListValue>()); EXPECT_EQ(opaque_handle.operator->(), mutable_list_value.operator->()); } TEST(MutableListImplValue, ListBuilding) { common_internal::LegacyValueManager value_factory( MemoryManagerRef::ReferenceCounting(), TypeProvider::Builtin()); ASSERT_OK_AND_ASSIGN(auto builder, value_factory.NewListValueBuilder( value_factory.GetDynListType())); auto mutable_list_value = value_factory.GetMemoryManager().MakeShared<MutableListValue>( std::move(builder)); MutableListValue& mutable_ref = const_cast<MutableListValue&>(*mutable_list_value); ASSERT_OK(mutable_ref.Append(value_factory.CreateIntValue(1))); ASSERT_OK_AND_ASSIGN(ListValue list_value, std::move(mutable_ref).Build()); EXPECT_THAT(list_value.Size(), IsOkAndHolds(1)); ASSERT_OK_AND_ASSIGN(auto element, list_value.Get(value_factory, 0)); ASSERT_TRUE(InstanceOf<IntValue>(element)); EXPECT_EQ(Cast<IntValue>(element).NativeValue(), 1); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/internal/mutable_list_impl.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/internal/mutable_list_impl_test.cc
4552db5798fb0853b131b783d8875794334fae7f
8dcaa8a0-e5c8-4330-b8cd-5a56f66cfb40
cpp
google/cel-cpp
time_functions
runtime/standard/time_functions.cc
runtime/standard/time_functions_test.cc
#include "runtime/standard/time_functions.h" #include <functional> #include <string> #include "absl/status/status.h" #include "absl/strings/match.h" #include "absl/strings/str_replace.h" #include "absl/strings/string_view.h" #include "base/builtins.h" #include "base/function_adapter.h" #include "common/value.h" #include "common/value_manager.h" #include "internal/overflow.h" #include "internal/status_macros.h" namespace cel { namespace { absl::Status FindTimeBreakdown(absl::Time timestamp, absl::string_view tz, absl::TimeZone::CivilInfo* breakdown) { absl::TimeZone time_zone; if (tz.empty()) { *breakdown = time_zone.At(timestamp); return absl::OkStatus(); } if (absl::LoadTimeZone(tz, &time_zone)) { *breakdown = time_zone.At(timestamp); return absl::OkStatus(); } if (absl::StrContains(tz, ":")) { std::string dur = absl::StrCat(tz, "m"); absl::StrReplaceAll({{":", "h"}}, &dur); absl::Duration d; if (absl::ParseDuration(dur, &d)) { timestamp += d; *breakdown = time_zone.At(timestamp); return absl::OkStatus(); } } return absl::InvalidArgumentError("Invalid timezone"); } Value GetTimeBreakdownPart( ValueManager& value_factory, absl::Time timestamp, absl::string_view tz, const std::function<int64_t(const absl::TimeZone::CivilInfo&)>& extractor_func) { absl::TimeZone::CivilInfo breakdown; auto status = FindTimeBreakdown(timestamp, tz, &breakdown); if (!status.ok()) { return value_factory.CreateErrorValue(status); } return value_factory.CreateIntValue(extractor_func(breakdown)); } Value GetFullYear(ValueManager& value_factory, absl::Time timestamp, absl::string_view tz) { return GetTimeBreakdownPart(value_factory, timestamp, tz, [](const absl::TimeZone::CivilInfo& breakdown) { return breakdown.cs.year(); }); } Value GetMonth(ValueManager& value_factory, absl::Time timestamp, absl::string_view tz) { return GetTimeBreakdownPart(value_factory, timestamp, tz, [](const absl::TimeZone::CivilInfo& breakdown) { return breakdown.cs.month() - 1; }); } Value GetDayOfYear(ValueManager& value_factory, absl::Time timestamp, absl::string_view tz) { return GetTimeBreakdownPart( value_factory, timestamp, tz, [](const absl::TimeZone::CivilInfo& breakdown) { return absl::GetYearDay(absl::CivilDay(breakdown.cs)) - 1; }); } Value GetDayOfMonth(ValueManager& value_factory, absl::Time timestamp, absl::string_view tz) { return GetTimeBreakdownPart(value_factory, timestamp, tz, [](const absl::TimeZone::CivilInfo& breakdown) { return breakdown.cs.day() - 1; }); } Value GetDate(ValueManager& value_factory, absl::Time timestamp, absl::string_view tz) { return GetTimeBreakdownPart(value_factory, timestamp, tz, [](const absl::TimeZone::CivilInfo& breakdown) { return breakdown.cs.day(); }); } Value GetDayOfWeek(ValueManager& value_factory, absl::Time timestamp, absl::string_view tz) { return GetTimeBreakdownPart( value_factory, timestamp, tz, [](const absl::TimeZone::CivilInfo& breakdown) { absl::Weekday weekday = absl::GetWeekday(breakdown.cs); int weekday_num = static_cast<int>(weekday); weekday_num = (weekday_num == 6) ? 0 : weekday_num + 1; return weekday_num; }); } Value GetHours(ValueManager& value_factory, absl::Time timestamp, absl::string_view tz) { return GetTimeBreakdownPart(value_factory, timestamp, tz, [](const absl::TimeZone::CivilInfo& breakdown) { return breakdown.cs.hour(); }); } Value GetMinutes(ValueManager& value_factory, absl::Time timestamp, absl::string_view tz) { return GetTimeBreakdownPart(value_factory, timestamp, tz, [](const absl::TimeZone::CivilInfo& breakdown) { return breakdown.cs.minute(); }); } Value GetSeconds(ValueManager& value_factory, absl::Time timestamp, absl::string_view tz) { return GetTimeBreakdownPart(value_factory, timestamp, tz, [](const absl::TimeZone::CivilInfo& breakdown) { return breakdown.cs.second(); }); } Value GetMilliseconds(ValueManager& value_factory, absl::Time timestamp, absl::string_view tz) { return GetTimeBreakdownPart( value_factory, timestamp, tz, [](const absl::TimeZone::CivilInfo& breakdown) { return absl::ToInt64Milliseconds(breakdown.subsecond); }); } absl::Status RegisterTimestampFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: CreateDescriptor(builtin::kFullYear, true), BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: WrapFunction([](ValueManager& value_factory, absl::Time ts, const StringValue& tz) -> Value { return GetFullYear(value_factory, ts, tz.ToString()); }))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, absl::Time>::CreateDescriptor( builtin::kFullYear, true), UnaryFunctionAdapter<Value, absl::Time>::WrapFunction( [](ValueManager& value_factory, absl::Time ts) -> Value { return GetFullYear(value_factory, ts, ""); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: CreateDescriptor(builtin::kMonth, true), BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: WrapFunction([](ValueManager& value_factory, absl::Time ts, const StringValue& tz) -> Value { return GetMonth(value_factory, ts, tz.ToString()); }))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, absl::Time>::CreateDescriptor(builtin::kMonth, true), UnaryFunctionAdapter<Value, absl::Time>::WrapFunction( [](ValueManager& value_factory, absl::Time ts) -> Value { return GetMonth(value_factory, ts, ""); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: CreateDescriptor(builtin::kDayOfYear, true), BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: WrapFunction([](ValueManager& value_factory, absl::Time ts, const StringValue& tz) -> Value { return GetDayOfYear(value_factory, ts, tz.ToString()); }))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, absl::Time>::CreateDescriptor( builtin::kDayOfYear, true), UnaryFunctionAdapter<Value, absl::Time>::WrapFunction( [](ValueManager& value_factory, absl::Time ts) -> Value { return GetDayOfYear(value_factory, ts, ""); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: CreateDescriptor(builtin::kDayOfMonth, true), BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: WrapFunction([](ValueManager& value_factory, absl::Time ts, const StringValue& tz) -> Value { return GetDayOfMonth(value_factory, ts, tz.ToString()); }))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, absl::Time>::CreateDescriptor( builtin::kDayOfMonth, true), UnaryFunctionAdapter<Value, absl::Time>::WrapFunction( [](ValueManager& value_factory, absl::Time ts) -> Value { return GetDayOfMonth(value_factory, ts, ""); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: CreateDescriptor(builtin::kDate, true), BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: WrapFunction([](ValueManager& value_factory, absl::Time ts, const StringValue& tz) -> Value { return GetDate(value_factory, ts, tz.ToString()); }))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, absl::Time>::CreateDescriptor(builtin::kDate, true), UnaryFunctionAdapter<Value, absl::Time>::WrapFunction( [](ValueManager& value_factory, absl::Time ts) -> Value { return GetDate(value_factory, ts, ""); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: CreateDescriptor(builtin::kDayOfWeek, true), BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: WrapFunction([](ValueManager& value_factory, absl::Time ts, const StringValue& tz) -> Value { return GetDayOfWeek(value_factory, ts, tz.ToString()); }))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, absl::Time>::CreateDescriptor( builtin::kDayOfWeek, true), UnaryFunctionAdapter<Value, absl::Time>::WrapFunction( [](ValueManager& value_factory, absl::Time ts) -> Value { return GetDayOfWeek(value_factory, ts, ""); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: CreateDescriptor(builtin::kHours, true), BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: WrapFunction([](ValueManager& value_factory, absl::Time ts, const StringValue& tz) -> Value { return GetHours(value_factory, ts, tz.ToString()); }))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, absl::Time>::CreateDescriptor(builtin::kHours, true), UnaryFunctionAdapter<Value, absl::Time>::WrapFunction( [](ValueManager& value_factory, absl::Time ts) -> Value { return GetHours(value_factory, ts, ""); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: CreateDescriptor(builtin::kMinutes, true), BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: WrapFunction([](ValueManager& value_factory, absl::Time ts, const StringValue& tz) -> Value { return GetMinutes(value_factory, ts, tz.ToString()); }))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, absl::Time>::CreateDescriptor( builtin::kMinutes, true), UnaryFunctionAdapter<Value, absl::Time>::WrapFunction( [](ValueManager& value_factory, absl::Time ts) -> Value { return GetMinutes(value_factory, ts, ""); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: CreateDescriptor(builtin::kSeconds, true), BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: WrapFunction([](ValueManager& value_factory, absl::Time ts, const StringValue& tz) -> Value { return GetSeconds(value_factory, ts, tz.ToString()); }))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, absl::Time>::CreateDescriptor( builtin::kSeconds, true), UnaryFunctionAdapter<Value, absl::Time>::WrapFunction( [](ValueManager& value_factory, absl::Time ts) -> Value { return GetSeconds(value_factory, ts, ""); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: CreateDescriptor(builtin::kMilliseconds, true), BinaryFunctionAdapter<Value, absl::Time, const StringValue&>:: WrapFunction([](ValueManager& value_factory, absl::Time ts, const StringValue& tz) -> Value { return GetMilliseconds(value_factory, ts, tz.ToString()); }))); return registry.Register( UnaryFunctionAdapter<Value, absl::Time>::CreateDescriptor( builtin::kMilliseconds, true), UnaryFunctionAdapter<Value, absl::Time>::WrapFunction( [](ValueManager& value_factory, absl::Time ts) -> Value { return GetMilliseconds(value_factory, ts, ""); })); } absl::Status RegisterCheckedTimeArithmeticFunctions( FunctionRegistry& registry) { CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Time, absl::Duration>::CreateDescriptor(builtin::kAdd, false), BinaryFunctionAdapter<absl::StatusOr<Value>, absl::Time, absl::Duration>:: WrapFunction([](ValueManager& value_factory, absl::Time t1, absl::Duration d2) -> absl::StatusOr<Value> { auto sum = cel::internal::CheckedAdd(t1, d2); if (!sum.ok()) { return value_factory.CreateErrorValue(sum.status()); } return value_factory.CreateTimestampValue(*sum); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<absl::StatusOr<Value>, absl::Duration, absl::Time>::CreateDescriptor(builtin::kAdd, false), BinaryFunctionAdapter<absl::StatusOr<Value>, absl::Duration, absl::Time>:: WrapFunction([](ValueManager& value_factory, absl::Duration d2, absl::Time t1) -> absl::StatusOr<Value> { auto sum = cel::internal::CheckedAdd(t1, d2); if (!sum.ok()) { return value_factory.CreateErrorValue(sum.status()); } return value_factory.CreateTimestampValue(*sum); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<absl::StatusOr<Value>, absl::Duration, absl::Duration>::CreateDescriptor(builtin::kAdd, false), BinaryFunctionAdapter<absl::StatusOr<Value>, absl::Duration, absl::Duration>:: WrapFunction([](ValueManager& value_factory, absl::Duration d1, absl::Duration d2) -> absl::StatusOr<Value> { auto sum = cel::internal::CheckedAdd(d1, d2); if (!sum.ok()) { return value_factory.CreateErrorValue(sum.status()); } return value_factory.CreateDurationValue(*sum); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<absl::StatusOr<Value>, absl::Time, absl::Duration>:: CreateDescriptor(builtin::kSubtract, false), BinaryFunctionAdapter<absl::StatusOr<Value>, absl::Time, absl::Duration>:: WrapFunction([](ValueManager& value_factory, absl::Time t1, absl::Duration d2) -> absl::StatusOr<Value> { auto diff = cel::internal::CheckedSub(t1, d2); if (!diff.ok()) { return value_factory.CreateErrorValue(diff.status()); } return value_factory.CreateTimestampValue(*diff); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<absl::StatusOr<Value>, absl::Time, absl::Time>::CreateDescriptor(builtin::kSubtract, false), BinaryFunctionAdapter<absl::StatusOr<Value>, absl::Time, absl::Time>:: WrapFunction([](ValueManager& value_factory, absl::Time t1, absl::Time t2) -> absl::StatusOr<Value> { auto diff = cel::internal::CheckedSub(t1, t2); if (!diff.ok()) { return value_factory.CreateErrorValue(diff.status()); } return value_factory.CreateDurationValue(*diff); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter< absl::StatusOr<Value>, absl::Duration, absl::Duration>::CreateDescriptor(builtin::kSubtract, false), BinaryFunctionAdapter<absl::StatusOr<Value>, absl::Duration, absl::Duration>:: WrapFunction([](ValueManager& value_factory, absl::Duration d1, absl::Duration d2) -> absl::StatusOr<Value> { auto diff = cel::internal::CheckedSub(d1, d2); if (!diff.ok()) { return value_factory.CreateErrorValue(diff.status()); } return value_factory.CreateDurationValue(*diff); }))); return absl::OkStatus(); } absl::Status RegisterUncheckedTimeArithmeticFunctions( FunctionRegistry& registry) { CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Time, absl::Duration>::CreateDescriptor(builtin::kAdd, false), BinaryFunctionAdapter<Value, absl::Time, absl::Duration>::WrapFunction( [](ValueManager& value_factory, absl::Time t1, absl::Duration d2) -> Value { return value_factory.CreateUncheckedTimestampValue(t1 + d2); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Duration, absl::Time>::CreateDescriptor(builtin::kAdd, false), BinaryFunctionAdapter<Value, absl::Duration, absl::Time>::WrapFunction( [](ValueManager& value_factory, absl::Duration d2, absl::Time t1) -> Value { return value_factory.CreateUncheckedTimestampValue(t1 + d2); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Duration, absl::Duration>::CreateDescriptor(builtin::kAdd, false), BinaryFunctionAdapter<Value, absl::Duration, absl::Duration>:: WrapFunction([](ValueManager& value_factory, absl::Duration d1, absl::Duration d2) -> Value { return value_factory.CreateUncheckedDurationValue(d1 + d2); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Time, absl::Duration>:: CreateDescriptor(builtin::kSubtract, false), BinaryFunctionAdapter<Value, absl::Time, absl::Duration>::WrapFunction( [](ValueManager& value_factory, absl::Time t1, absl::Duration d2) -> Value { return value_factory.CreateUncheckedTimestampValue(t1 - d2); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Time, absl::Time>::CreateDescriptor( builtin::kSubtract, false), BinaryFunctionAdapter<Value, absl::Time, absl::Time>::WrapFunction( [](ValueManager& value_factory, absl::Time t1, absl::Time t2) -> Value { return value_factory.CreateUncheckedDurationValue(t1 - t2); }))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, absl::Duration, absl::Duration>:: CreateDescriptor(builtin::kSubtract, false), BinaryFunctionAdapter<Value, absl::Duration, absl::Duration>:: WrapFunction([](ValueManager& value_factory, absl::Duration d1, absl::Duration d2) -> Value { return value_factory.CreateUncheckedDurationValue(d1 - d2); }))); return absl::OkStatus(); } absl::Status RegisterDurationFunctions(FunctionRegistry& registry) { using DurationAccessorFunction = UnaryFunctionAdapter<int64_t, absl::Duration>; CEL_RETURN_IF_ERROR(registry.Register( DurationAccessorFunction::CreateDescriptor(builtin::kHours, true), DurationAccessorFunction::WrapFunction( [](ValueManager&, absl::Duration d) -> int64_t { return absl::ToInt64Hours(d); }))); CEL_RETURN_IF_ERROR(registry.Register( DurationAccessorFunction::CreateDescriptor(builtin::kMinutes, true), DurationAccessorFunction::WrapFunction( [](ValueManager&, absl::Duration d) -> int64_t { return absl::ToInt64Minutes(d); }))); CEL_RETURN_IF_ERROR(registry.Register( DurationAccessorFunction::CreateDescriptor(builtin::kSeconds, true), DurationAccessorFunction::WrapFunction( [](ValueManager&, absl::Duration d) -> int64_t { return absl::ToInt64Seconds(d); }))); return registry.Register( DurationAccessorFunction::CreateDescriptor(builtin::kMilliseconds, true), DurationAccessorFunction::WrapFunction( [](ValueManager&, absl::Duration d) -> int64_t { constexpr int64_t millis_per_second = 1000L; return absl::ToInt64Milliseconds(d) % millis_per_second; })); } } absl::Status RegisterTimeFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { CEL_RETURN_IF_ERROR(RegisterTimestampFunctions(registry, options)); CEL_RETURN_IF_ERROR(RegisterDurationFunctions(registry)); if (options.enable_timestamp_duration_overflow_errors) { return RegisterCheckedTimeArithmeticFunctions(registry); } return RegisterUncheckedTimeArithmeticFunctions(registry); } }
#include "runtime/standard/time_functions.h" #include <vector> #include "base/builtins.h" #include "base/function_descriptor.h" #include "internal/testing.h" namespace cel { namespace { using ::testing::UnorderedElementsAre; MATCHER_P3(MatchesOperatorDescriptor, name, expected_kind1, expected_kind2, "") { const FunctionDescriptor& descriptor = *arg; std::vector<Kind> types{expected_kind1, expected_kind2}; return descriptor.name() == name && descriptor.receiver_style() == false && descriptor.types() == types; } MATCHER_P2(MatchesTimeAccessor, name, kind, "") { const FunctionDescriptor& descriptor = *arg; std::vector<Kind> types{kind}; return descriptor.name() == name && descriptor.receiver_style() == true && descriptor.types() == types; } MATCHER_P2(MatchesTimezoneTimeAccessor, name, kind, "") { const FunctionDescriptor& descriptor = *arg; std::vector<Kind> types{kind, Kind::kString}; return descriptor.name() == name && descriptor.receiver_style() == true && descriptor.types() == types; } TEST(RegisterTimeFunctions, MathOperatorsRegistered) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterTimeFunctions(registry, options)); auto registered_functions = registry.ListFunctions(); EXPECT_THAT(registered_functions[builtin::kAdd], UnorderedElementsAre( MatchesOperatorDescriptor(builtin::kAdd, Kind::kDuration, Kind::kDuration), MatchesOperatorDescriptor(builtin::kAdd, Kind::kTimestamp, Kind::kDuration), MatchesOperatorDescriptor(builtin::kAdd, Kind::kDuration, Kind::kTimestamp))); EXPECT_THAT(registered_functions[builtin::kSubtract], UnorderedElementsAre( MatchesOperatorDescriptor(builtin::kSubtract, Kind::kDuration, Kind::kDuration), MatchesOperatorDescriptor(builtin::kSubtract, Kind::kTimestamp, Kind::kDuration), MatchesOperatorDescriptor( builtin::kSubtract, Kind::kTimestamp, Kind::kTimestamp))); } TEST(RegisterTimeFunctions, AccessorsRegistered) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterTimeFunctions(registry, options)); auto registered_functions = registry.ListFunctions(); EXPECT_THAT( registered_functions[builtin::kFullYear], UnorderedElementsAre( MatchesTimeAccessor(builtin::kFullYear, Kind::kTimestamp), MatchesTimezoneTimeAccessor(builtin::kFullYear, Kind::kTimestamp))); EXPECT_THAT( registered_functions[builtin::kDate], UnorderedElementsAre( MatchesTimeAccessor(builtin::kDate, Kind::kTimestamp), MatchesTimezoneTimeAccessor(builtin::kDate, Kind::kTimestamp))); EXPECT_THAT( registered_functions[builtin::kMonth], UnorderedElementsAre( MatchesTimeAccessor(builtin::kMonth, Kind::kTimestamp), MatchesTimezoneTimeAccessor(builtin::kMonth, Kind::kTimestamp))); EXPECT_THAT( registered_functions[builtin::kDayOfYear], UnorderedElementsAre( MatchesTimeAccessor(builtin::kDayOfYear, Kind::kTimestamp), MatchesTimezoneTimeAccessor(builtin::kDayOfYear, Kind::kTimestamp))); EXPECT_THAT( registered_functions[builtin::kDayOfMonth], UnorderedElementsAre( MatchesTimeAccessor(builtin::kDayOfMonth, Kind::kTimestamp), MatchesTimezoneTimeAccessor(builtin::kDayOfMonth, Kind::kTimestamp))); EXPECT_THAT( registered_functions[builtin::kDayOfWeek], UnorderedElementsAre( MatchesTimeAccessor(builtin::kDayOfWeek, Kind::kTimestamp), MatchesTimezoneTimeAccessor(builtin::kDayOfWeek, Kind::kTimestamp))); EXPECT_THAT( registered_functions[builtin::kHours], UnorderedElementsAre( MatchesTimeAccessor(builtin::kHours, Kind::kTimestamp), MatchesTimezoneTimeAccessor(builtin::kHours, Kind::kTimestamp), MatchesTimeAccessor(builtin::kHours, Kind::kDuration))); EXPECT_THAT( registered_functions[builtin::kMinutes], UnorderedElementsAre( MatchesTimeAccessor(builtin::kMinutes, Kind::kTimestamp), MatchesTimezoneTimeAccessor(builtin::kMinutes, Kind::kTimestamp), MatchesTimeAccessor(builtin::kMinutes, Kind::kDuration))); EXPECT_THAT( registered_functions[builtin::kSeconds], UnorderedElementsAre( MatchesTimeAccessor(builtin::kSeconds, Kind::kTimestamp), MatchesTimezoneTimeAccessor(builtin::kSeconds, Kind::kTimestamp), MatchesTimeAccessor(builtin::kSeconds, Kind::kDuration))); EXPECT_THAT( registered_functions[builtin::kMilliseconds], UnorderedElementsAre( MatchesTimeAccessor(builtin::kMilliseconds, Kind::kTimestamp), MatchesTimezoneTimeAccessor(builtin::kMilliseconds, Kind::kTimestamp), MatchesTimeAccessor(builtin::kMilliseconds, Kind::kDuration))); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/standard/time_functions.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/standard/time_functions_test.cc
4552db5798fb0853b131b783d8875794334fae7f
ea0cdbc9-2758-4931-92c9-7bad4053a615
cpp
google/cel-cpp
container_membership_functions
runtime/standard/container_membership_functions.cc
runtime/standard/container_membership_functions_test.cc
#include "runtime/standard/container_membership_functions.h" #include <array> #include <cstdint> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "base/builtins.h" #include "base/function_adapter.h" #include "common/value.h" #include "internal/number.h" #include "internal/status_macros.h" #include "runtime/function_registry.h" #include "runtime/register_function_helper.h" #include "runtime/runtime_options.h" namespace cel { namespace { using ::cel::internal::Number; static constexpr std::array<absl::string_view, 3> in_operators = { cel::builtin::kIn, cel::builtin::kInFunction, cel::builtin::kInDeprecated, }; template <class T> bool ValueEquals(const Value& value, T other); template <> bool ValueEquals(const Value& value, bool other) { if (auto bool_value = As<BoolValue>(value); bool_value) { return bool_value->NativeValue() == other; } return false; } template <> bool ValueEquals(const Value& value, int64_t other) { if (auto int_value = As<IntValue>(value); int_value) { return int_value->NativeValue() == other; } return false; } template <> bool ValueEquals(const Value& value, uint64_t other) { if (auto uint_value = As<UintValue>(value); uint_value) { return uint_value->NativeValue() == other; } return false; } template <> bool ValueEquals(const Value& value, double other) { if (auto double_value = As<DoubleValue>(value); double_value) { return double_value->NativeValue() == other; } return false; } template <> bool ValueEquals(const Value& value, const StringValue& other) { if (auto string_value = As<StringValue>(value); string_value) { return string_value->Equals(other); } return false; } template <> bool ValueEquals(const Value& value, const BytesValue& other) { if (auto bytes_value = As<BytesValue>(value); bytes_value) { return bytes_value->Equals(other); } return false; } template <typename T> absl::StatusOr<bool> In(ValueManager& value_factory, T value, const ListValue& list) { CEL_ASSIGN_OR_RETURN(auto size, list.Size()); Value element; for (int i = 0; i < size; i++) { CEL_RETURN_IF_ERROR(list.Get(value_factory, i, element)); if (ValueEquals<T>(element, value)) { return true; } } return false; } absl::StatusOr<Value> HeterogeneousEqualityIn(ValueManager& value_factory, const Value& value, const ListValue& list) { return list.Contains(value_factory, value); } absl::Status RegisterListMembershipFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { for (absl::string_view op : in_operators) { if (options.enable_heterogeneous_equality) { CEL_RETURN_IF_ERROR( (RegisterHelper<BinaryFunctionAdapter< absl::StatusOr<Value>, const Value&, const ListValue&>>:: RegisterGlobalOverload(op, &HeterogeneousEqualityIn, registry))); } else { CEL_RETURN_IF_ERROR( (RegisterHelper<BinaryFunctionAdapter<absl::StatusOr<bool>, bool, const ListValue&>>:: RegisterGlobalOverload(op, In<bool>, registry))); CEL_RETURN_IF_ERROR( (RegisterHelper<BinaryFunctionAdapter<absl::StatusOr<bool>, int64_t, const ListValue&>>:: RegisterGlobalOverload(op, In<int64_t>, registry))); CEL_RETURN_IF_ERROR( (RegisterHelper<BinaryFunctionAdapter<absl::StatusOr<bool>, uint64_t, const ListValue&>>:: RegisterGlobalOverload(op, In<uint64_t>, registry))); CEL_RETURN_IF_ERROR( (RegisterHelper<BinaryFunctionAdapter<absl::StatusOr<bool>, double, const ListValue&>>:: RegisterGlobalOverload(op, In<double>, registry))); CEL_RETURN_IF_ERROR( (RegisterHelper<BinaryFunctionAdapter< absl::StatusOr<bool>, const StringValue&, const ListValue&>>:: RegisterGlobalOverload(op, In<const StringValue&>, registry))); CEL_RETURN_IF_ERROR( (RegisterHelper<BinaryFunctionAdapter< absl::StatusOr<bool>, const BytesValue&, const ListValue&>>:: RegisterGlobalOverload(op, In<const BytesValue&>, registry))); } } return absl::OkStatus(); } absl::Status RegisterMapMembershipFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { const bool enable_heterogeneous_equality = options.enable_heterogeneous_equality; auto boolKeyInSet = [enable_heterogeneous_equality]( ValueManager& factory, bool key, const MapValue& map_value) -> absl::StatusOr<Value> { auto result = map_value.Has(factory, factory.CreateBoolValue(key)); if (result.ok()) { return std::move(*result); } if (enable_heterogeneous_equality) { return factory.CreateBoolValue(false); } return factory.CreateErrorValue(result.status()); }; auto intKeyInSet = [enable_heterogeneous_equality]( ValueManager& factory, int64_t key, const MapValue& map_value) -> absl::StatusOr<Value> { Value int_key = factory.CreateIntValue(key); auto result = map_value.Has(factory, int_key); if (enable_heterogeneous_equality) { if (result.ok() && (*result).Is<BoolValue>() && result->GetBool().NativeValue()) { return std::move(*result); } Number number = Number::FromInt64(key); if (number.LosslessConvertibleToUint()) { const auto& result = map_value.Has(factory, factory.CreateUintValue(number.AsUint())); if (result.ok() && (*result).Is<BoolValue>() && result->GetBool().NativeValue()) { return std::move(*result); } } return factory.CreateBoolValue(false); } if (!result.ok()) { return factory.CreateErrorValue(result.status()); } return std::move(*result); }; auto stringKeyInSet = [enable_heterogeneous_equality]( ValueManager& factory, const StringValue& key, const MapValue& map_value) -> absl::StatusOr<Value> { auto result = map_value.Has(factory, key); if (result.ok()) { return std::move(*result); } if (enable_heterogeneous_equality) { return factory.CreateBoolValue(false); } return factory.CreateErrorValue(result.status()); }; auto uintKeyInSet = [enable_heterogeneous_equality]( ValueManager& factory, uint64_t key, const MapValue& map_value) -> absl::StatusOr<Value> { Value uint_key = factory.CreateUintValue(key); const auto& result = map_value.Has(factory, uint_key); if (enable_heterogeneous_equality) { if (result.ok() && (*result).Is<BoolValue>() && result->GetBool().NativeValue()) { return std::move(*result); } Number number = Number::FromUint64(key); if (number.LosslessConvertibleToInt()) { const auto& result = map_value.Has(factory, factory.CreateIntValue(number.AsInt())); if (result.ok() && (*result).Is<BoolValue>() && result->GetBool().NativeValue()) { return std::move(*result); } } return factory.CreateBoolValue(false); } if (!result.ok()) { return factory.CreateErrorValue(result.status()); } return std::move(*result); }; auto doubleKeyInSet = [](ValueManager& factory, double key, const MapValue& map_value) -> absl::StatusOr<Value> { Number number = Number::FromDouble(key); if (number.LosslessConvertibleToInt()) { const auto& result = map_value.Has(factory, factory.CreateIntValue(number.AsInt())); if (result.ok() && (*result).Is<BoolValue>() && result->GetBool().NativeValue()) { return std::move(*result); } } if (number.LosslessConvertibleToUint()) { const auto& result = map_value.Has(factory, factory.CreateUintValue(number.AsUint())); if (result.ok() && (*result).Is<BoolValue>() && result->GetBool().NativeValue()) { return std::move(*result); } } return factory.CreateBoolValue(false); }; for (auto op : in_operators) { auto status = RegisterHelper<BinaryFunctionAdapter< absl::StatusOr<Value>, const StringValue&, const MapValue&>>::RegisterGlobalOverload(op, stringKeyInSet, registry); if (!status.ok()) return status; status = RegisterHelper< BinaryFunctionAdapter<absl::StatusOr<Value>, bool, const MapValue&>>:: RegisterGlobalOverload(op, boolKeyInSet, registry); if (!status.ok()) return status; status = RegisterHelper<BinaryFunctionAdapter<absl::StatusOr<Value>, int64_t, const MapValue&>>:: RegisterGlobalOverload(op, intKeyInSet, registry); if (!status.ok()) return status; status = RegisterHelper<BinaryFunctionAdapter<absl::StatusOr<Value>, uint64_t, const MapValue&>>:: RegisterGlobalOverload(op, uintKeyInSet, registry); if (!status.ok()) return status; if (enable_heterogeneous_equality) { status = RegisterHelper<BinaryFunctionAdapter<absl::StatusOr<Value>, double, const MapValue&>>:: RegisterGlobalOverload(op, doubleKeyInSet, registry); if (!status.ok()) return status; } } return absl::OkStatus(); } } absl::Status RegisterContainerMembershipFunctions( FunctionRegistry& registry, const RuntimeOptions& options) { if (options.enable_list_contains) { CEL_RETURN_IF_ERROR(RegisterListMembershipFunctions(registry, options)); } return RegisterMapMembershipFunctions(registry, options); } }
#include "runtime/standard/container_membership_functions.h" #include <array> #include <vector> #include "absl/strings/string_view.h" #include "base/builtins.h" #include "base/function_descriptor.h" #include "base/kind.h" #include "internal/testing.h" #include "runtime/function_registry.h" #include "runtime/runtime_options.h" namespace cel { namespace { using ::testing::UnorderedElementsAre; MATCHER_P3(MatchesDescriptor, name, receiver, expected_kinds, "") { const FunctionDescriptor& descriptor = *arg; const std::vector<Kind>& types = expected_kinds; return descriptor.name() == name && descriptor.receiver_style() == receiver && descriptor.types() == types; } static constexpr std::array<absl::string_view, 3> kInOperators = { builtin::kIn, builtin::kInDeprecated, builtin::kInFunction}; TEST(RegisterContainerMembershipFunctions, RegistersHomogeneousInOperator) { FunctionRegistry registry; RuntimeOptions options; options.enable_heterogeneous_equality = false; ASSERT_OK(RegisterContainerMembershipFunctions(registry, options)); auto overloads = registry.ListFunctions(); for (absl::string_view operator_name : kInOperators) { EXPECT_THAT( overloads[operator_name], UnorderedElementsAre( MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kInt, Kind::kList}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kUint, Kind::kList}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kDouble, Kind::kList}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kString, Kind::kList}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kBytes, Kind::kList}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kBool, Kind::kList}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kInt, Kind::kMap}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kUint, Kind::kMap}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kString, Kind::kMap}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kBool, Kind::kMap}))); } } TEST(RegisterContainerMembershipFunctions, RegistersHeterogeneousInOperation) { FunctionRegistry registry; RuntimeOptions options; options.enable_heterogeneous_equality = true; ASSERT_OK(RegisterContainerMembershipFunctions(registry, options)); auto overloads = registry.ListFunctions(); for (absl::string_view operator_name : kInOperators) { EXPECT_THAT( overloads[operator_name], UnorderedElementsAre( MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kAny, Kind::kList}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kInt, Kind::kMap}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kUint, Kind::kMap}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kDouble, Kind::kMap}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kString, Kind::kMap}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kBool, Kind::kMap}))); } } TEST(RegisterContainerMembershipFunctions, RegistersInOperatorListsDisabled) { FunctionRegistry registry; RuntimeOptions options; options.enable_list_contains = false; ASSERT_OK(RegisterContainerMembershipFunctions(registry, options)); auto overloads = registry.ListFunctions(); for (absl::string_view operator_name : kInOperators) { EXPECT_THAT( overloads[operator_name], UnorderedElementsAre( MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kInt, Kind::kMap}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kUint, Kind::kMap}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kDouble, Kind::kMap}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kString, Kind::kMap}), MatchesDescriptor(operator_name, false, std::vector<Kind>{Kind::kBool, Kind::kMap}))); } } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/standard/container_membership_functions.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/standard/container_membership_functions_test.cc
4552db5798fb0853b131b783d8875794334fae7f
4f14c747-ef98-43b0-acd7-2d6670658ee5
cpp
google/cel-cpp
arithmetic_functions
runtime/standard/arithmetic_functions.cc
runtime/standard/arithmetic_functions_test.cc
#include "runtime/standard/arithmetic_functions.h" #include <limits> #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "base/builtins.h" #include "base/function_adapter.h" #include "common/value.h" #include "common/value_manager.h" #include "internal/overflow.h" #include "internal/status_macros.h" namespace cel { namespace { template <class Type> Value Add(ValueManager&, Type v0, Type v1); template <> Value Add<int64_t>(ValueManager& value_factory, int64_t v0, int64_t v1) { auto sum = cel::internal::CheckedAdd(v0, v1); if (!sum.ok()) { return value_factory.CreateErrorValue(sum.status()); } return value_factory.CreateIntValue(*sum); } template <> Value Add<uint64_t>(ValueManager& value_factory, uint64_t v0, uint64_t v1) { auto sum = cel::internal::CheckedAdd(v0, v1); if (!sum.ok()) { return value_factory.CreateErrorValue(sum.status()); } return value_factory.CreateUintValue(*sum); } template <> Value Add<double>(ValueManager& value_factory, double v0, double v1) { return value_factory.CreateDoubleValue(v0 + v1); } template <class Type> Value Sub(ValueManager&, Type v0, Type v1); template <> Value Sub<int64_t>(ValueManager& value_factory, int64_t v0, int64_t v1) { auto diff = cel::internal::CheckedSub(v0, v1); if (!diff.ok()) { return value_factory.CreateErrorValue(diff.status()); } return value_factory.CreateIntValue(*diff); } template <> Value Sub<uint64_t>(ValueManager& value_factory, uint64_t v0, uint64_t v1) { auto diff = cel::internal::CheckedSub(v0, v1); if (!diff.ok()) { return value_factory.CreateErrorValue(diff.status()); } return value_factory.CreateUintValue(*diff); } template <> Value Sub<double>(ValueManager& value_factory, double v0, double v1) { return value_factory.CreateDoubleValue(v0 - v1); } template <class Type> Value Mul(ValueManager&, Type v0, Type v1); template <> Value Mul<int64_t>(ValueManager& value_factory, int64_t v0, int64_t v1) { auto prod = cel::internal::CheckedMul(v0, v1); if (!prod.ok()) { return value_factory.CreateErrorValue(prod.status()); } return value_factory.CreateIntValue(*prod); } template <> Value Mul<uint64_t>(ValueManager& value_factory, uint64_t v0, uint64_t v1) { auto prod = cel::internal::CheckedMul(v0, v1); if (!prod.ok()) { return value_factory.CreateErrorValue(prod.status()); } return value_factory.CreateUintValue(*prod); } template <> Value Mul<double>(ValueManager& value_factory, double v0, double v1) { return value_factory.CreateDoubleValue(v0 * v1); } template <class Type> Value Div(ValueManager&, Type v0, Type v1); template <> Value Div<int64_t>(ValueManager& value_factory, int64_t v0, int64_t v1) { auto quot = cel::internal::CheckedDiv(v0, v1); if (!quot.ok()) { return value_factory.CreateErrorValue(quot.status()); } return value_factory.CreateIntValue(*quot); } template <> Value Div<uint64_t>(ValueManager& value_factory, uint64_t v0, uint64_t v1) { auto quot = cel::internal::CheckedDiv(v0, v1); if (!quot.ok()) { return value_factory.CreateErrorValue(quot.status()); } return value_factory.CreateUintValue(*quot); } template <> Value Div<double>(ValueManager& value_factory, double v0, double v1) { static_assert(std::numeric_limits<double>::is_iec559, "Division by zero for doubles must be supported"); return value_factory.CreateDoubleValue(v0 / v1); } template <class Type> Value Modulo(ValueManager& value_factory, Type v0, Type v1); template <> Value Modulo<int64_t>(ValueManager& value_factory, int64_t v0, int64_t v1) { auto mod = cel::internal::CheckedMod(v0, v1); if (!mod.ok()) { return value_factory.CreateErrorValue(mod.status()); } return value_factory.CreateIntValue(*mod); } template <> Value Modulo<uint64_t>(ValueManager& value_factory, uint64_t v0, uint64_t v1) { auto mod = cel::internal::CheckedMod(v0, v1); if (!mod.ok()) { return value_factory.CreateErrorValue(mod.status()); } return value_factory.CreateUintValue(*mod); } template <class Type> absl::Status RegisterArithmeticFunctionsForType(FunctionRegistry& registry) { using FunctionAdapter = cel::BinaryFunctionAdapter<Value, Type, Type>; CEL_RETURN_IF_ERROR(registry.Register( FunctionAdapter::CreateDescriptor(cel::builtin::kAdd, false), FunctionAdapter::WrapFunction(&Add<Type>))); CEL_RETURN_IF_ERROR(registry.Register( FunctionAdapter::CreateDescriptor(cel::builtin::kSubtract, false), FunctionAdapter::WrapFunction(&Sub<Type>))); CEL_RETURN_IF_ERROR(registry.Register( FunctionAdapter::CreateDescriptor(cel::builtin::kMultiply, false), FunctionAdapter::WrapFunction(&Mul<Type>))); return registry.Register( FunctionAdapter::CreateDescriptor(cel::builtin::kDivide, false), FunctionAdapter::WrapFunction(&Div<Type>)); } } absl::Status RegisterArithmeticFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { CEL_RETURN_IF_ERROR(RegisterArithmeticFunctionsForType<int64_t>(registry)); CEL_RETURN_IF_ERROR(RegisterArithmeticFunctionsForType<uint64_t>(registry)); CEL_RETURN_IF_ERROR(RegisterArithmeticFunctionsForType<double>(registry)); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, int64_t, int64_t>::CreateDescriptor( cel::builtin::kModulo, false), BinaryFunctionAdapter<Value, int64_t, int64_t>::WrapFunction( &Modulo<int64_t>))); CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter<Value, uint64_t, uint64_t>::CreateDescriptor( cel::builtin::kModulo, false), BinaryFunctionAdapter<Value, uint64_t, uint64_t>::WrapFunction( &Modulo<uint64_t>))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<Value, int64_t>::CreateDescriptor(cel::builtin::kNeg, false), UnaryFunctionAdapter<Value, int64_t>::WrapFunction( [](ValueManager& value_factory, int64_t value) -> Value { auto inv = cel::internal::CheckedNegation(value); if (!inv.ok()) { return value_factory.CreateErrorValue(inv.status()); } return value_factory.CreateIntValue(*inv); }))); return registry.Register( UnaryFunctionAdapter<double, double>::CreateDescriptor(cel::builtin::kNeg, false), UnaryFunctionAdapter<double, double>::WrapFunction( [](ValueManager&, double value) -> double { return -value; })); } }
#include "runtime/standard/arithmetic_functions.h" #include <vector> #include "base/builtins.h" #include "base/function_descriptor.h" #include "internal/testing.h" namespace cel { namespace { using ::testing::UnorderedElementsAre; MATCHER_P2(MatchesOperatorDescriptor, name, expected_kind, "") { const FunctionDescriptor& descriptor = arg.descriptor; std::vector<Kind> types{expected_kind, expected_kind}; return descriptor.name() == name && descriptor.receiver_style() == false && descriptor.types() == types; } MATCHER_P(MatchesNegationDescriptor, expected_kind, "") { const FunctionDescriptor& descriptor = arg.descriptor; std::vector<Kind> types{expected_kind}; return descriptor.name() == builtin::kNeg && descriptor.receiver_style() == false && descriptor.types() == types; } TEST(RegisterArithmeticFunctions, Registered) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterArithmeticFunctions(registry, options)); EXPECT_THAT(registry.FindStaticOverloads(builtin::kAdd, false, {Kind::kAny, Kind::kAny}), UnorderedElementsAre( MatchesOperatorDescriptor(builtin::kAdd, Kind::kInt), MatchesOperatorDescriptor(builtin::kAdd, Kind::kDouble), MatchesOperatorDescriptor(builtin::kAdd, Kind::kUint))); EXPECT_THAT(registry.FindStaticOverloads(builtin::kSubtract, false, {Kind::kAny, Kind::kAny}), UnorderedElementsAre( MatchesOperatorDescriptor(builtin::kSubtract, Kind::kInt), MatchesOperatorDescriptor(builtin::kSubtract, Kind::kDouble), MatchesOperatorDescriptor(builtin::kSubtract, Kind::kUint))); EXPECT_THAT(registry.FindStaticOverloads(builtin::kDivide, false, {Kind::kAny, Kind::kAny}), UnorderedElementsAre( MatchesOperatorDescriptor(builtin::kDivide, Kind::kInt), MatchesOperatorDescriptor(builtin::kDivide, Kind::kDouble), MatchesOperatorDescriptor(builtin::kDivide, Kind::kUint))); EXPECT_THAT(registry.FindStaticOverloads(builtin::kMultiply, false, {Kind::kAny, Kind::kAny}), UnorderedElementsAre( MatchesOperatorDescriptor(builtin::kMultiply, Kind::kInt), MatchesOperatorDescriptor(builtin::kMultiply, Kind::kDouble), MatchesOperatorDescriptor(builtin::kMultiply, Kind::kUint))); EXPECT_THAT(registry.FindStaticOverloads(builtin::kModulo, false, {Kind::kAny, Kind::kAny}), UnorderedElementsAre( MatchesOperatorDescriptor(builtin::kModulo, Kind::kInt), MatchesOperatorDescriptor(builtin::kModulo, Kind::kUint))); EXPECT_THAT(registry.FindStaticOverloads(builtin::kNeg, false, {Kind::kAny}), UnorderedElementsAre(MatchesNegationDescriptor(Kind::kInt), MatchesNegationDescriptor(Kind::kDouble))); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/standard/arithmetic_functions.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/standard/arithmetic_functions_test.cc
4552db5798fb0853b131b783d8875794334fae7f
bdef13db-c741-4232-920e-67c8a8818eeb
cpp
google/cel-cpp
container_functions
runtime/standard/container_functions.cc
runtime/standard/container_functions_test.cc
#include "runtime/standard/container_functions.h" #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "base/builtins.h" #include "base/function_adapter.h" #include "common/value.h" #include "common/value_manager.h" #include "internal/status_macros.h" #include "runtime/function_registry.h" #include "runtime/internal/mutable_list_impl.h" #include "runtime/runtime_options.h" namespace cel { namespace { using cel::runtime_internal::MutableListValue; absl::StatusOr<int64_t> MapSizeImpl(ValueManager&, const MapValue& value) { return value.Size(); } absl::StatusOr<int64_t> ListSizeImpl(ValueManager&, const ListValue& value) { return value.Size(); } absl::StatusOr<ListValue> ConcatList(ValueManager& factory, const ListValue& value1, const ListValue& value2) { CEL_ASSIGN_OR_RETURN(auto size1, value1.Size()); if (size1 == 0) { return value2; } CEL_ASSIGN_OR_RETURN(auto size2, value2.Size()); if (size2 == 0) { return value1; } CEL_ASSIGN_OR_RETURN(auto list_builder, factory.NewListValueBuilder(factory.GetDynListType())); list_builder->Reserve(size1 + size2); for (int i = 0; i < size1; i++) { CEL_ASSIGN_OR_RETURN(Value elem, value1.Get(factory, i)); CEL_RETURN_IF_ERROR(list_builder->Add(std::move(elem))); } for (int i = 0; i < size2; i++) { CEL_ASSIGN_OR_RETURN(Value elem, value2.Get(factory, i)); CEL_RETURN_IF_ERROR(list_builder->Add(std::move(elem))); } return std::move(*list_builder).Build(); } absl::StatusOr<OpaqueValue> AppendList(ValueManager& factory, OpaqueValue value1, const ListValue& value2) { if (!MutableListValue::Is(value1)) { return absl::InvalidArgumentError( "Unexpected call to runtime list append."); } MutableListValue& mutable_list = MutableListValue::Cast(value1); CEL_ASSIGN_OR_RETURN(auto size2, value2.Size()); for (int i = 0; i < size2; i++) { CEL_ASSIGN_OR_RETURN(Value elem, value2.Get(factory, i)); CEL_RETURN_IF_ERROR(mutable_list.Append(std::move(elem))); } return value1; } } absl::Status RegisterContainerFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { for (bool receiver_style : {true, false}) { CEL_RETURN_IF_ERROR(registry.Register( cel::UnaryFunctionAdapter<absl::StatusOr<int64_t>, const ListValue&>:: CreateDescriptor(cel::builtin::kSize, receiver_style), UnaryFunctionAdapter<absl::StatusOr<int64_t>, const ListValue&>::WrapFunction(ListSizeImpl))); CEL_RETURN_IF_ERROR(registry.Register( UnaryFunctionAdapter<absl::StatusOr<int64_t>, const MapValue&>:: CreateDescriptor(cel::builtin::kSize, receiver_style), UnaryFunctionAdapter<absl::StatusOr<int64_t>, const MapValue&>::WrapFunction(MapSizeImpl))); } if (options.enable_list_concat) { CEL_RETURN_IF_ERROR(registry.Register( BinaryFunctionAdapter< absl::StatusOr<Value>, const ListValue&, const ListValue&>::CreateDescriptor(cel::builtin::kAdd, false), BinaryFunctionAdapter<absl::StatusOr<Value>, const ListValue&, const ListValue&>::WrapFunction(ConcatList))); } return registry.Register( BinaryFunctionAdapter< absl::StatusOr<OpaqueValue>, OpaqueValue, const ListValue&>::CreateDescriptor(cel::builtin::kRuntimeListAppend, false), BinaryFunctionAdapter<absl::StatusOr<OpaqueValue>, OpaqueValue, const ListValue&>::WrapFunction(AppendList)); } }
#include "runtime/standard/container_functions.h" #include <vector> #include "base/builtins.h" #include "base/function_descriptor.h" #include "internal/testing.h" namespace cel { namespace { using ::testing::IsEmpty; using ::testing::UnorderedElementsAre; MATCHER_P3(MatchesDescriptor, name, receiver, expected_kinds, "") { const FunctionDescriptor& descriptor = arg.descriptor; const std::vector<Kind>& types = expected_kinds; return descriptor.name() == name && descriptor.receiver_style() == receiver && descriptor.types() == types; } TEST(RegisterContainerFunctions, RegistersSizeFunctions) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterContainerFunctions(registry, options)); EXPECT_THAT( registry.FindStaticOverloads(builtin::kSize, false, {Kind::kAny}), UnorderedElementsAre(MatchesDescriptor(builtin::kSize, false, std::vector<Kind>{Kind::kList}), MatchesDescriptor(builtin::kSize, false, std::vector<Kind>{Kind::kMap}))); EXPECT_THAT( registry.FindStaticOverloads(builtin::kSize, true, {Kind::kAny}), UnorderedElementsAre(MatchesDescriptor(builtin::kSize, true, std::vector<Kind>{Kind::kList}), MatchesDescriptor(builtin::kSize, true, std::vector<Kind>{Kind::kMap}))); } TEST(RegisterContainerFunctions, RegisterListConcatEnabled) { FunctionRegistry registry; RuntimeOptions options; options.enable_list_concat = true; ASSERT_OK(RegisterContainerFunctions(registry, options)); EXPECT_THAT( registry.FindStaticOverloads(builtin::kAdd, false, {Kind::kAny, Kind::kAny}), UnorderedElementsAre(MatchesDescriptor( builtin::kAdd, false, std::vector<Kind>{Kind::kList, Kind::kList}))); } TEST(RegisterContainerFunctions, RegisterListConcateDisabled) { FunctionRegistry registry; RuntimeOptions options; options.enable_list_concat = false; ASSERT_OK(RegisterContainerFunctions(registry, options)); EXPECT_THAT(registry.FindStaticOverloads(builtin::kAdd, false, {Kind::kAny, Kind::kAny}), IsEmpty()); } TEST(RegisterContainerFunctions, RegisterRuntimeListAppend) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterContainerFunctions(registry, options)); EXPECT_THAT(registry.FindStaticOverloads(builtin::kRuntimeListAppend, false, {Kind::kAny, Kind::kAny}), UnorderedElementsAre(MatchesDescriptor( builtin::kRuntimeListAppend, false, std::vector<Kind>{Kind::kOpaque, Kind::kList}))); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/standard/container_functions.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/standard/container_functions_test.cc
4552db5798fb0853b131b783d8875794334fae7f
9b3032c4-cbe2-4b9a-85fc-77dc67256bd2
cpp
google/cel-cpp
equality_functions
runtime/standard/equality_functions.cc
runtime/standard/equality_functions_test.cc
#include "runtime/standard/equality_functions.h" #include <cstdint> #include <functional> #include <optional> #include <type_traits> #include <utility> #include "absl/functional/function_ref.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "absl/types/optional.h" #include "base/builtins.h" #include "base/function_adapter.h" #include "base/kind.h" #include "common/casting.h" #include "common/value.h" #include "common/value_manager.h" #include "internal/number.h" #include "internal/status_macros.h" #include "runtime/function_registry.h" #include "runtime/internal/errors.h" #include "runtime/register_function_helper.h" #include "runtime/runtime_options.h" namespace cel { namespace { using ::cel::Cast; using ::cel::InstanceOf; using ::cel::builtin::kEqual; using ::cel::builtin::kInequal; using ::cel::internal::Number; struct HomogenousEqualProvider { static constexpr bool kIsHeterogeneous = false; absl::StatusOr<absl::optional<bool>> operator()(ValueManager& value_factory, const Value& lhs, const Value& rhs) const; }; struct HeterogeneousEqualProvider { static constexpr bool kIsHeterogeneous = true; absl::StatusOr<absl::optional<bool>> operator()(ValueManager& value_factory, const Value& lhs, const Value& rhs) const; }; template <class Type> absl::optional<bool> Inequal(Type lhs, Type rhs) { return lhs != rhs; } template <> absl::optional<bool> Inequal(const StringValue& lhs, const StringValue& rhs) { return !lhs.Equals(rhs); } template <> absl::optional<bool> Inequal(const BytesValue& lhs, const BytesValue& rhs) { return !lhs.Equals(rhs); } template <> absl::optional<bool> Inequal(const NullValue&, const NullValue&) { return false; } template <> absl::optional<bool> Inequal(const TypeValue& lhs, const TypeValue& rhs) { return lhs.name() != rhs.name(); } template <class Type> absl::optional<bool> Equal(Type lhs, Type rhs) { return lhs == rhs; } template <> absl::optional<bool> Equal(const StringValue& lhs, const StringValue& rhs) { return lhs.Equals(rhs); } template <> absl::optional<bool> Equal(const BytesValue& lhs, const BytesValue& rhs) { return lhs.Equals(rhs); } template <> absl::optional<bool> Equal(const NullValue&, const NullValue&) { return true; } template <> absl::optional<bool> Equal(const TypeValue& lhs, const TypeValue& rhs) { return lhs.name() == rhs.name(); } template <typename EqualsProvider> absl::StatusOr<absl::optional<bool>> ListEqual(ValueManager& factory, const ListValue& lhs, const ListValue& rhs) { if (&lhs == &rhs) { return true; } CEL_ASSIGN_OR_RETURN(auto lhs_size, lhs.Size()); CEL_ASSIGN_OR_RETURN(auto rhs_size, rhs.Size()); if (lhs_size != rhs_size) { return false; } for (int i = 0; i < lhs_size; ++i) { CEL_ASSIGN_OR_RETURN(auto lhs_i, lhs.Get(factory, i)); CEL_ASSIGN_OR_RETURN(auto rhs_i, rhs.Get(factory, i)); CEL_ASSIGN_OR_RETURN(absl::optional<bool> eq, EqualsProvider()(factory, lhs_i, rhs_i)); if (!eq.has_value() || !*eq) { return eq; } } return true; } absl::StatusOr<absl::optional<bool>> OpaqueEqual(ValueManager& manager, const OpaqueValue& lhs, const OpaqueValue& rhs) { Value result; CEL_RETURN_IF_ERROR(lhs.Equal(manager, rhs, result)); if (auto bool_value = As<BoolValue>(result); bool_value) { return bool_value->NativeValue(); } return TypeConversionError(result.GetTypeName(), "bool").NativeValue(); } absl::optional<Number> NumberFromValue(const Value& value) { if (value.Is<IntValue>()) { return Number::FromInt64(value.GetInt().NativeValue()); } else if (value.Is<UintValue>()) { return Number::FromUint64(value.GetUint().NativeValue()); } else if (value.Is<DoubleValue>()) { return Number::FromDouble(value.GetDouble().NativeValue()); } return absl::nullopt; } absl::StatusOr<absl::optional<Value>> CheckAlternativeNumericType( ValueManager& value_factory, const Value& key, const MapValue& rhs) { absl::optional<Number> number = NumberFromValue(key); if (!number.has_value()) { return absl::nullopt; } if (!InstanceOf<IntValue>(key) && number->LosslessConvertibleToInt()) { Value entry; bool ok; CEL_ASSIGN_OR_RETURN( std::tie(entry, ok), rhs.Find(value_factory, value_factory.CreateIntValue(number->AsInt()))); if (ok) { return entry; } } if (!InstanceOf<UintValue>(key) && number->LosslessConvertibleToUint()) { Value entry; bool ok; CEL_ASSIGN_OR_RETURN(std::tie(entry, ok), rhs.Find(value_factory, value_factory.CreateUintValue( number->AsUint()))); if (ok) { return entry; } } return absl::nullopt; } template <typename EqualsProvider> absl::StatusOr<absl::optional<bool>> MapEqual(ValueManager& value_factory, const MapValue& lhs, const MapValue& rhs) { if (&lhs == &rhs) { return true; } if (lhs.Size() != rhs.Size()) { return false; } CEL_ASSIGN_OR_RETURN(auto iter, lhs.NewIterator(value_factory)); while (iter->HasNext()) { CEL_ASSIGN_OR_RETURN(auto lhs_key, iter->Next(value_factory)); Value rhs_value; bool rhs_ok; CEL_ASSIGN_OR_RETURN(std::tie(rhs_value, rhs_ok), rhs.Find(value_factory, lhs_key)); if (!rhs_ok && EqualsProvider::kIsHeterogeneous) { CEL_ASSIGN_OR_RETURN( auto maybe_rhs_value, CheckAlternativeNumericType(value_factory, lhs_key, rhs)); rhs_ok = maybe_rhs_value.has_value(); if (rhs_ok) { rhs_value = std::move(*maybe_rhs_value); } } if (!rhs_ok) { return false; } CEL_ASSIGN_OR_RETURN(auto lhs_value, lhs.Get(value_factory, lhs_key)); CEL_ASSIGN_OR_RETURN(absl::optional<bool> eq, EqualsProvider()(value_factory, lhs_value, rhs_value)); if (!eq.has_value() || !*eq) { return eq; } } return true; } template <typename Type, typename Op> std::function<Value(cel::ValueManager& factory, Type, Type)> WrapComparison( Op op, absl::string_view name) { return [op = std::move(op), name](cel::ValueManager& factory, Type lhs, Type rhs) -> Value { absl::optional<bool> result = op(lhs, rhs); if (result.has_value()) { return factory.CreateBoolValue(*result); } return factory.CreateErrorValue( cel::runtime_internal::CreateNoMatchingOverloadError(name)); }; } template <class Type> absl::Status RegisterEqualityFunctionsForType(cel::FunctionRegistry& registry) { using FunctionAdapter = cel::RegisterHelper<BinaryFunctionAdapter<Value, Type, Type>>; CEL_RETURN_IF_ERROR(FunctionAdapter::RegisterGlobalOverload( kInequal, WrapComparison<Type>(&Inequal<Type>, kInequal), registry)); CEL_RETURN_IF_ERROR(FunctionAdapter::RegisterGlobalOverload( kEqual, WrapComparison<Type>(&Equal<Type>, kEqual), registry)); return absl::OkStatus(); } template <typename Type, typename Op> auto ComplexEquality(Op&& op) { return [op = std::forward<Op>(op)](cel::ValueManager& f, const Type& t1, const Type& t2) -> absl::StatusOr<Value> { CEL_ASSIGN_OR_RETURN(absl::optional<bool> result, op(f, t1, t2)); if (!result.has_value()) { return f.CreateErrorValue( cel::runtime_internal::CreateNoMatchingOverloadError(kEqual)); } return f.CreateBoolValue(*result); }; } template <typename Type, typename Op> auto ComplexInequality(Op&& op) { return [op = std::forward<Op>(op)](cel::ValueManager& f, Type t1, Type t2) -> absl::StatusOr<Value> { CEL_ASSIGN_OR_RETURN(absl::optional<bool> result, op(f, t1, t2)); if (!result.has_value()) { return f.CreateErrorValue( cel::runtime_internal::CreateNoMatchingOverloadError(kInequal)); } return f.CreateBoolValue(!*result); }; } template <class Type> absl::Status RegisterComplexEqualityFunctionsForType( absl::FunctionRef<absl::StatusOr<absl::optional<bool>>(ValueManager&, Type, Type)> op, cel::FunctionRegistry& registry) { using FunctionAdapter = cel::RegisterHelper< BinaryFunctionAdapter<absl::StatusOr<Value>, Type, Type>>; CEL_RETURN_IF_ERROR(FunctionAdapter::RegisterGlobalOverload( kInequal, ComplexInequality<Type>(op), registry)); CEL_RETURN_IF_ERROR(FunctionAdapter::RegisterGlobalOverload( kEqual, ComplexEquality<Type>(op), registry)); return absl::OkStatus(); } absl::Status RegisterHomogenousEqualityFunctions( cel::FunctionRegistry& registry) { CEL_RETURN_IF_ERROR(RegisterEqualityFunctionsForType<bool>(registry)); CEL_RETURN_IF_ERROR(RegisterEqualityFunctionsForType<int64_t>(registry)); CEL_RETURN_IF_ERROR(RegisterEqualityFunctionsForType<uint64_t>(registry)); CEL_RETURN_IF_ERROR(RegisterEqualityFunctionsForType<double>(registry)); CEL_RETURN_IF_ERROR( RegisterEqualityFunctionsForType<const cel::StringValue&>(registry)); CEL_RETURN_IF_ERROR( RegisterEqualityFunctionsForType<const cel::BytesValue&>(registry)); CEL_RETURN_IF_ERROR( RegisterEqualityFunctionsForType<absl::Duration>(registry)); CEL_RETURN_IF_ERROR(RegisterEqualityFunctionsForType<absl::Time>(registry)); CEL_RETURN_IF_ERROR( RegisterEqualityFunctionsForType<const cel::NullValue&>(registry)); CEL_RETURN_IF_ERROR( RegisterEqualityFunctionsForType<const cel::TypeValue&>(registry)); CEL_RETURN_IF_ERROR( RegisterComplexEqualityFunctionsForType<const cel::ListValue&>( &ListEqual<HomogenousEqualProvider>, registry)); CEL_RETURN_IF_ERROR( RegisterComplexEqualityFunctionsForType<const cel::MapValue&>( &MapEqual<HomogenousEqualProvider>, registry)); return absl::OkStatus(); } absl::Status RegisterNullMessageEqualityFunctions(FunctionRegistry& registry) { CEL_RETURN_IF_ERROR( (cel::RegisterHelper< BinaryFunctionAdapter<bool, const StructValue&, const NullValue&>>:: RegisterGlobalOverload( kEqual, [](ValueManager&, const StructValue&, const NullValue&) { return false; }, registry))); CEL_RETURN_IF_ERROR( (cel::RegisterHelper< BinaryFunctionAdapter<bool, const NullValue&, const StructValue&>>:: RegisterGlobalOverload( kEqual, [](ValueManager&, const NullValue&, const StructValue&) { return false; }, registry))); CEL_RETURN_IF_ERROR( (cel::RegisterHelper< BinaryFunctionAdapter<bool, const StructValue&, const NullValue&>>:: RegisterGlobalOverload( kInequal, [](ValueManager&, const StructValue&, const NullValue&) { return true; }, registry))); return cel::RegisterHelper< BinaryFunctionAdapter<bool, const NullValue&, const StructValue&>>:: RegisterGlobalOverload( kInequal, [](ValueManager&, const NullValue&, const StructValue&) { return true; }, registry); } template <typename EqualsProvider> absl::StatusOr<absl::optional<bool>> HomogenousValueEqual(ValueManager& factory, const Value& v1, const Value& v2) { if (v1->kind() != v2->kind()) { return absl::nullopt; } static_assert(std::is_lvalue_reference_v<decltype(Cast<StringValue>(v1))>, "unexpected value copy"); switch (v1->kind()) { case ValueKind::kBool: return Equal<bool>(Cast<BoolValue>(v1).NativeValue(), Cast<BoolValue>(v2).NativeValue()); case ValueKind::kNull: return Equal<const NullValue&>(Cast<NullValue>(v1), Cast<NullValue>(v2)); case ValueKind::kInt: return Equal<int64_t>(Cast<IntValue>(v1).NativeValue(), Cast<IntValue>(v2).NativeValue()); case ValueKind::kUint: return Equal<uint64_t>(Cast<UintValue>(v1).NativeValue(), Cast<UintValue>(v2).NativeValue()); case ValueKind::kDouble: return Equal<double>(Cast<DoubleValue>(v1).NativeValue(), Cast<DoubleValue>(v2).NativeValue()); case ValueKind::kDuration: return Equal<absl::Duration>(Cast<DurationValue>(v1).NativeValue(), Cast<DurationValue>(v2).NativeValue()); case ValueKind::kTimestamp: return Equal<absl::Time>(Cast<TimestampValue>(v1).NativeValue(), Cast<TimestampValue>(v2).NativeValue()); case ValueKind::kCelType: return Equal<const TypeValue&>(Cast<TypeValue>(v1), Cast<TypeValue>(v2)); case ValueKind::kString: return Equal<const StringValue&>(Cast<StringValue>(v1), Cast<StringValue>(v2)); case ValueKind::kBytes: return Equal<const cel::BytesValue&>(v1.GetBytes(), v2.GetBytes()); case ValueKind::kList: return ListEqual<EqualsProvider>(factory, Cast<ListValue>(v1), Cast<ListValue>(v2)); case ValueKind::kMap: return MapEqual<EqualsProvider>(factory, Cast<MapValue>(v1), Cast<MapValue>(v2)); case ValueKind::kOpaque: return OpaqueEqual(factory, Cast<OpaqueValue>(v1), Cast<OpaqueValue>(v2)); default: return absl::nullopt; } } absl::StatusOr<Value> EqualOverloadImpl(ValueManager& factory, const Value& lhs, const Value& rhs) { CEL_ASSIGN_OR_RETURN(absl::optional<bool> result, runtime_internal::ValueEqualImpl(factory, lhs, rhs)); if (result.has_value()) { return factory.CreateBoolValue(*result); } return factory.CreateErrorValue( cel::runtime_internal::CreateNoMatchingOverloadError(kEqual)); } absl::StatusOr<Value> InequalOverloadImpl(ValueManager& factory, const Value& lhs, const Value& rhs) { CEL_ASSIGN_OR_RETURN(absl::optional<bool> result, runtime_internal::ValueEqualImpl(factory, lhs, rhs)); if (result.has_value()) { return factory.CreateBoolValue(!*result); } return factory.CreateErrorValue( cel::runtime_internal::CreateNoMatchingOverloadError(kInequal)); } absl::Status RegisterHeterogeneousEqualityFunctions( cel::FunctionRegistry& registry) { using Adapter = cel::RegisterHelper< BinaryFunctionAdapter<absl::StatusOr<Value>, const Value&, const Value&>>; CEL_RETURN_IF_ERROR( Adapter::RegisterGlobalOverload(kEqual, &EqualOverloadImpl, registry)); CEL_RETURN_IF_ERROR(Adapter::RegisterGlobalOverload( kInequal, &InequalOverloadImpl, registry)); return absl::OkStatus(); } absl::StatusOr<absl::optional<bool>> HomogenousEqualProvider::operator()( ValueManager& factory, const Value& lhs, const Value& rhs) const { return HomogenousValueEqual<HomogenousEqualProvider>(factory, lhs, rhs); } absl::StatusOr<absl::optional<bool>> HeterogeneousEqualProvider::operator()( ValueManager& factory, const Value& lhs, const Value& rhs) const { return runtime_internal::ValueEqualImpl(factory, lhs, rhs); } } namespace runtime_internal { absl::StatusOr<absl::optional<bool>> ValueEqualImpl(ValueManager& value_factory, const Value& v1, const Value& v2) { if (v1->kind() == v2->kind()) { if (InstanceOf<StructValue>(v1) && InstanceOf<StructValue>(v2)) { CEL_ASSIGN_OR_RETURN(Value result, Cast<StructValue>(v1).Equal(value_factory, v2)); if (InstanceOf<BoolValue>(result)) { return Cast<BoolValue>(result).NativeValue(); } return false; } return HomogenousValueEqual<HeterogeneousEqualProvider>(value_factory, v1, v2); } absl::optional<Number> lhs = NumberFromValue(v1); absl::optional<Number> rhs = NumberFromValue(v2); if (rhs.has_value() && lhs.has_value()) { return *lhs == *rhs; } if (InstanceOf<ErrorValue>(v1) || InstanceOf<UnknownValue>(v1) || InstanceOf<ErrorValue>(v2) || InstanceOf<UnknownValue>(v2)) { return absl::nullopt; } return false; } } absl::Status RegisterEqualityFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { if (options.enable_heterogeneous_equality) { CEL_RETURN_IF_ERROR(RegisterHeterogeneousEqualityFunctions(registry)); } else { CEL_RETURN_IF_ERROR(RegisterHomogenousEqualityFunctions(registry)); CEL_RETURN_IF_ERROR(RegisterNullMessageEqualityFunctions(registry)); } return absl::OkStatus(); } }
#include "runtime/standard/equality_functions.h" #include <vector> #include "base/builtins.h" #include "base/function_descriptor.h" #include "base/kind.h" #include "internal/testing.h" #include "runtime/function_registry.h" #include "runtime/runtime_options.h" namespace cel { namespace { using ::testing::UnorderedElementsAre; MATCHER_P3(MatchesDescriptor, name, receiver, expected_kinds, "") { const FunctionDescriptor& descriptor = *arg; const std::vector<Kind>& types = expected_kinds; return descriptor.name() == name && descriptor.receiver_style() == receiver && descriptor.types() == types; } TEST(RegisterEqualityFunctionsHomogeneous, RegistersEqualOperators) { FunctionRegistry registry; RuntimeOptions options; options.enable_heterogeneous_equality = false; ASSERT_OK(RegisterEqualityFunctions(registry, options)); auto overloads = registry.ListFunctions(); EXPECT_THAT( overloads[builtin::kEqual], UnorderedElementsAre( MatchesDescriptor(builtin::kEqual, false, std::vector<Kind>{Kind::kList, Kind::kList}), MatchesDescriptor(builtin::kEqual, false, std::vector<Kind>{Kind::kMap, Kind::kMap}), MatchesDescriptor(builtin::kEqual, false, std::vector<Kind>{Kind::kBool, Kind::kBool}), MatchesDescriptor(builtin::kEqual, false, std::vector<Kind>{Kind::kInt, Kind::kInt}), MatchesDescriptor(builtin::kEqual, false, std::vector<Kind>{Kind::kUint, Kind::kUint}), MatchesDescriptor(builtin::kEqual, false, std::vector<Kind>{Kind::kDouble, Kind::kDouble}), MatchesDescriptor( builtin::kEqual, false, std::vector<Kind>{Kind::kDuration, Kind::kDuration}), MatchesDescriptor( builtin::kEqual, false, std::vector<Kind>{Kind::kTimestamp, Kind::kTimestamp}), MatchesDescriptor(builtin::kEqual, false, std::vector<Kind>{Kind::kString, Kind::kString}), MatchesDescriptor(builtin::kEqual, false, std::vector<Kind>{Kind::kBytes, Kind::kBytes}), MatchesDescriptor(builtin::kEqual, false, std::vector<Kind>{Kind::kType, Kind::kType}), MatchesDescriptor(builtin::kEqual, false, std::vector<Kind>{Kind::kStruct, Kind::kNullType}), MatchesDescriptor(builtin::kEqual, false, std::vector<Kind>{Kind::kNullType, Kind::kStruct}), MatchesDescriptor( builtin::kEqual, false, std::vector<Kind>{Kind::kNullType, Kind::kNullType}))); EXPECT_THAT( overloads[builtin::kInequal], UnorderedElementsAre( MatchesDescriptor(builtin::kInequal, false, std::vector<Kind>{Kind::kList, Kind::kList}), MatchesDescriptor(builtin::kInequal, false, std::vector<Kind>{Kind::kMap, Kind::kMap}), MatchesDescriptor(builtin::kInequal, false, std::vector<Kind>{Kind::kBool, Kind::kBool}), MatchesDescriptor(builtin::kInequal, false, std::vector<Kind>{Kind::kInt, Kind::kInt}), MatchesDescriptor(builtin::kInequal, false, std::vector<Kind>{Kind::kUint, Kind::kUint}), MatchesDescriptor(builtin::kInequal, false, std::vector<Kind>{Kind::kDouble, Kind::kDouble}), MatchesDescriptor( builtin::kInequal, false, std::vector<Kind>{Kind::kDuration, Kind::kDuration}), MatchesDescriptor( builtin::kInequal, false, std::vector<Kind>{Kind::kTimestamp, Kind::kTimestamp}), MatchesDescriptor(builtin::kInequal, false, std::vector<Kind>{Kind::kString, Kind::kString}), MatchesDescriptor(builtin::kInequal, false, std::vector<Kind>{Kind::kBytes, Kind::kBytes}), MatchesDescriptor(builtin::kInequal, false, std::vector<Kind>{Kind::kType, Kind::kType}), MatchesDescriptor(builtin::kInequal, false, std::vector<Kind>{Kind::kStruct, Kind::kNullType}), MatchesDescriptor(builtin::kInequal, false, std::vector<Kind>{Kind::kNullType, Kind::kStruct}), MatchesDescriptor( builtin::kInequal, false, std::vector<Kind>{Kind::kNullType, Kind::kNullType}))); } TEST(RegisterEqualityFunctionsHeterogeneous, RegistersEqualOperators) { FunctionRegistry registry; RuntimeOptions options; options.enable_heterogeneous_equality = true; ASSERT_OK(RegisterEqualityFunctions(registry, options)); auto overloads = registry.ListFunctions(); EXPECT_THAT( overloads[builtin::kEqual], UnorderedElementsAre(MatchesDescriptor( builtin::kEqual, false, std::vector<Kind>{Kind::kAny, Kind::kAny}))); EXPECT_THAT(overloads[builtin::kInequal], UnorderedElementsAre(MatchesDescriptor( builtin::kInequal, false, std::vector<Kind>{Kind::kAny, Kind::kAny}))); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/standard/equality_functions.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/standard/equality_functions_test.cc
4552db5798fb0853b131b783d8875794334fae7f
4ff22835-9a9a-423f-8510-b19d25979eff
cpp
google/cel-cpp
logical_functions
runtime/standard/logical_functions.cc
runtime/standard/logical_functions_test.cc
#include "runtime/standard/logical_functions.h" #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "base/builtins.h" #include "base/function_adapter.h" #include "common/casting.h" #include "common/value.h" #include "common/value_manager.h" #include "internal/status_macros.h" #include "runtime/function_registry.h" #include "runtime/internal/errors.h" #include "runtime/register_function_helper.h" namespace cel { namespace { using ::cel::runtime_internal::CreateNoMatchingOverloadError; Value NotStrictlyFalseImpl(ValueManager& value_factory, const Value& value) { if (InstanceOf<BoolValue>(value)) { return value; } if (InstanceOf<ErrorValue>(value) || InstanceOf<UnknownValue>(value)) { return value_factory.CreateBoolValue(true); } return value_factory.CreateErrorValue( CreateNoMatchingOverloadError(builtin::kNotStrictlyFalse)); } } absl::Status RegisterLogicalFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { CEL_RETURN_IF_ERROR( (RegisterHelper<UnaryFunctionAdapter<bool, bool>>::RegisterGlobalOverload( builtin::kNot, [](ValueManager&, bool value) -> bool { return !value; }, registry))); using StrictnessHelper = RegisterHelper<UnaryFunctionAdapter<Value, Value>>; CEL_RETURN_IF_ERROR(StrictnessHelper::RegisterNonStrictOverload( builtin::kNotStrictlyFalse, &NotStrictlyFalseImpl, registry)); CEL_RETURN_IF_ERROR(StrictnessHelper::RegisterNonStrictOverload( builtin::kNotStrictlyFalseDeprecated, &NotStrictlyFalseImpl, registry)); return absl::OkStatus(); } }
#include "runtime/standard/logical_functions.h" #include <functional> #include <string> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "base/builtins.h" #include "base/function.h" #include "base/function_descriptor.h" #include "base/kind.h" #include "base/type_provider.h" #include "common/type_factory.h" #include "common/type_manager.h" #include "common/value.h" #include "common/value_manager.h" #include "common/values/legacy_value_manager.h" #include "internal/testing.h" #include "runtime/function_overload_reference.h" #include "runtime/function_registry.h" #include "runtime/runtime_options.h" namespace cel { namespace { using ::testing::ElementsAre; using ::testing::HasSubstr; using ::testing::Matcher; using ::testing::Truly; MATCHER_P3(DescriptorIs, name, arg_kinds, is_receiver, "") { const FunctionOverloadReference& ref = arg; const FunctionDescriptor& descriptor = ref.descriptor; return descriptor.name() == name && descriptor.ShapeMatches(is_receiver, arg_kinds); } MATCHER_P(IsBool, expected, "") { const Value& value = arg; return value->Is<BoolValue>() && value.GetBool().NativeValue() == expected; } absl::StatusOr<Value> TestDispatchToFunction(const FunctionRegistry& registry, absl::string_view simple_name, absl::Span<const Value> args, ValueManager& value_factory) { std::vector<Kind> arg_matcher_; arg_matcher_.reserve(args.size()); for (const auto& value : args) { arg_matcher_.push_back(ValueKindToKind(value->kind())); } std::vector<FunctionOverloadReference> refs = registry.FindStaticOverloads( simple_name, false, arg_matcher_); if (refs.size() != 1) { return absl::InvalidArgumentError("ambiguous overloads"); } Function::InvokeContext ctx(value_factory); return refs[0].implementation.Invoke(ctx, args); } TEST(RegisterLogicalFunctions, NotStrictlyFalseRegistered) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterLogicalFunctions(registry, options)); EXPECT_THAT( registry.FindStaticOverloads(builtin::kNotStrictlyFalse, false, {Kind::kAny}), ElementsAre(DescriptorIs(builtin::kNotStrictlyFalse, std::vector<Kind>{Kind::kBool}, false))); } TEST(RegisterLogicalFunctions, LogicalNotRegistered) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterLogicalFunctions(registry, options)); EXPECT_THAT( registry.FindStaticOverloads(builtin::kNot, false, {Kind::kAny}), ElementsAre( DescriptorIs(builtin::kNot, std::vector<Kind>{Kind::kBool}, false))); } struct TestCase { using ArgumentFactory = std::function<std::vector<Value>(ValueManager&)>; std::string function; ArgumentFactory arguments; absl::StatusOr<Matcher<Value>> result_matcher; }; class LogicalFunctionsTest : public testing::TestWithParam<TestCase> { public: LogicalFunctionsTest() : value_factory_(MemoryManagerRef::ReferenceCounting(), TypeProvider::Builtin()) {} protected: common_internal::LegacyValueManager value_factory_; }; TEST_P(LogicalFunctionsTest, Runner) { const TestCase& test_case = GetParam(); cel::FunctionRegistry registry; ASSERT_OK(RegisterLogicalFunctions(registry, RuntimeOptions())); std::vector<Value> args = test_case.arguments(value_factory_); absl::StatusOr<Value> result = TestDispatchToFunction( registry, test_case.function, args, value_factory_); EXPECT_EQ(result.ok(), test_case.result_matcher.ok()); if (!test_case.result_matcher.ok()) { EXPECT_EQ(result.status().code(), test_case.result_matcher.status().code()); EXPECT_THAT(result.status().message(), HasSubstr(test_case.result_matcher.status().message())); } else { ASSERT_TRUE(result.ok()) << "unexpected error" << result.status(); EXPECT_THAT(*result, *test_case.result_matcher); } } INSTANTIATE_TEST_SUITE_P( Cases, LogicalFunctionsTest, testing::ValuesIn(std::vector<TestCase>{ TestCase{builtin::kNot, [](ValueManager& value_factory) -> std::vector<Value> { return {value_factory.CreateBoolValue(true)}; }, IsBool(false)}, TestCase{builtin::kNot, [](ValueManager& value_factory) -> std::vector<Value> { return {value_factory.CreateBoolValue(false)}; }, IsBool(true)}, TestCase{builtin::kNot, [](ValueManager& value_factory) -> std::vector<Value> { return {value_factory.CreateBoolValue(true), value_factory.CreateBoolValue(false)}; }, absl::InvalidArgumentError("")}, TestCase{builtin::kNotStrictlyFalse, [](ValueManager& value_factory) -> std::vector<Value> { return {value_factory.CreateBoolValue(true)}; }, IsBool(true)}, TestCase{builtin::kNotStrictlyFalse, [](ValueManager& value_factory) -> std::vector<Value> { return {value_factory.CreateBoolValue(false)}; }, IsBool(false)}, TestCase{builtin::kNotStrictlyFalse, [](ValueManager& value_factory) -> std::vector<Value> { return {value_factory.CreateErrorValue( absl::InternalError("test"))}; }, IsBool(true)}, TestCase{builtin::kNotStrictlyFalse, [](ValueManager& value_factory) -> std::vector<Value> { return {value_factory.CreateUnknownValue()}; }, IsBool(true)}, TestCase{builtin::kNotStrictlyFalse, [](ValueManager& value_factory) -> std::vector<Value> { return {value_factory.CreateIntValue(42)}; }, Truly([](const Value& v) { return v->Is<ErrorValue>() && absl::StrContains( v.GetError().NativeValue().message(), "No matching overloads"); })}, })); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/standard/logical_functions.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/standard/logical_functions_test.cc
4552db5798fb0853b131b783d8875794334fae7f
439b36a0-6382-423f-8d8b-44e0b13c9471
cpp
google/cel-cpp
string_functions
runtime/standard/string_functions.cc
runtime/standard/string_functions_test.cc
#include "runtime/standard/string_functions.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "base/builtins.h" #include "base/function_adapter.h" #include "common/value.h" #include "common/value_manager.h" #include "internal/status_macros.h" #include "runtime/function_registry.h" namespace cel { namespace { absl::StatusOr<StringValue> ConcatString(ValueManager& factory, const StringValue& value1, const StringValue& value2) { return factory.CreateUncheckedStringValue( absl::StrCat(value1.ToString(), value2.ToString())); } absl::StatusOr<BytesValue> ConcatBytes(ValueManager& factory, const BytesValue& value1, const BytesValue& value2) { return factory.CreateBytesValue( absl::StrCat(value1.ToString(), value2.ToString())); } bool StringContains(ValueManager&, const StringValue& value, const StringValue& substr) { return absl::StrContains(value.ToString(), substr.ToString()); } bool StringEndsWith(ValueManager&, const StringValue& value, const StringValue& suffix) { return absl::EndsWith(value.ToString(), suffix.ToString()); } bool StringStartsWith(ValueManager&, const StringValue& value, const StringValue& prefix) { return absl::StartsWith(value.ToString(), prefix.ToString()); } absl::Status RegisterSizeFunctions(FunctionRegistry& registry) { auto size_func = [](ValueManager& value_factory, const StringValue& value) -> int64_t { return value.Size(); }; using StrSizeFnAdapter = UnaryFunctionAdapter<int64_t, const StringValue&>; CEL_RETURN_IF_ERROR(StrSizeFnAdapter::RegisterGlobalOverload( cel::builtin::kSize, size_func, registry)); CEL_RETURN_IF_ERROR(StrSizeFnAdapter::RegisterMemberOverload( cel::builtin::kSize, size_func, registry)); auto bytes_size_func = [](ValueManager&, const BytesValue& value) -> int64_t { return value.Size(); }; using BytesSizeFnAdapter = UnaryFunctionAdapter<int64_t, const BytesValue&>; CEL_RETURN_IF_ERROR(BytesSizeFnAdapter::RegisterGlobalOverload( cel::builtin::kSize, bytes_size_func, registry)); return BytesSizeFnAdapter::RegisterMemberOverload(cel::builtin::kSize, bytes_size_func, registry); } absl::Status RegisterConcatFunctions(FunctionRegistry& registry) { using StrCatFnAdapter = BinaryFunctionAdapter<absl::StatusOr<StringValue>, const StringValue&, const StringValue&>; CEL_RETURN_IF_ERROR(StrCatFnAdapter::RegisterGlobalOverload( cel::builtin::kAdd, &ConcatString, registry)); using BytesCatFnAdapter = BinaryFunctionAdapter<absl::StatusOr<BytesValue>, const BytesValue&, const BytesValue&>; return BytesCatFnAdapter::RegisterGlobalOverload(cel::builtin::kAdd, &ConcatBytes, registry); } } absl::Status RegisterStringFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { for (bool receiver_style : {true, false}) { auto status = BinaryFunctionAdapter<bool, const StringValue&, const StringValue&>:: Register(cel::builtin::kStringContains, receiver_style, StringContains, registry); CEL_RETURN_IF_ERROR(status); status = BinaryFunctionAdapter<bool, const StringValue&, const StringValue&>:: Register(cel::builtin::kStringEndsWith, receiver_style, StringEndsWith, registry); CEL_RETURN_IF_ERROR(status); status = BinaryFunctionAdapter<bool, const StringValue&, const StringValue&>:: Register(cel::builtin::kStringStartsWith, receiver_style, StringStartsWith, registry); CEL_RETURN_IF_ERROR(status); } if (options.enable_string_concat) { CEL_RETURN_IF_ERROR(RegisterConcatFunctions(registry)); } return RegisterSizeFunctions(registry); } }
#include "runtime/standard/string_functions.h" #include <vector> #include "base/builtins.h" #include "base/function_descriptor.h" #include "internal/testing.h" namespace cel { namespace { using ::testing::IsEmpty; using ::testing::UnorderedElementsAre; enum class CallStyle { kFree, kReceiver }; MATCHER_P3(MatchesDescriptor, name, call_style, expected_kinds, "") { bool receiver_style; switch (call_style) { case CallStyle::kFree: receiver_style = false; break; case CallStyle::kReceiver: receiver_style = true; break; } const FunctionDescriptor& descriptor = *arg; const std::vector<Kind>& types = expected_kinds; return descriptor.name() == name && descriptor.receiver_style() == receiver_style && descriptor.types() == types; } TEST(RegisterStringFunctions, FunctionsRegistered) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterStringFunctions(registry, options)); auto overloads = registry.ListFunctions(); EXPECT_THAT( overloads[builtin::kAdd], UnorderedElementsAre( MatchesDescriptor(builtin::kAdd, CallStyle::kFree, std::vector<Kind>{Kind::kString, Kind::kString}), MatchesDescriptor(builtin::kAdd, CallStyle::kFree, std::vector<Kind>{Kind::kBytes, Kind::kBytes}))); EXPECT_THAT(overloads[builtin::kSize], UnorderedElementsAre( MatchesDescriptor(builtin::kSize, CallStyle::kFree, std::vector<Kind>{Kind::kString}), MatchesDescriptor(builtin::kSize, CallStyle::kFree, std::vector<Kind>{Kind::kBytes}), MatchesDescriptor(builtin::kSize, CallStyle::kReceiver, std::vector<Kind>{Kind::kString}), MatchesDescriptor(builtin::kSize, CallStyle::kReceiver, std::vector<Kind>{Kind::kBytes}))); EXPECT_THAT( overloads[builtin::kStringContains], UnorderedElementsAre( MatchesDescriptor(builtin::kStringContains, CallStyle::kFree, std::vector<Kind>{Kind::kString, Kind::kString}), MatchesDescriptor(builtin::kStringContains, CallStyle::kReceiver, std::vector<Kind>{Kind::kString, Kind::kString}))); EXPECT_THAT( overloads[builtin::kStringStartsWith], UnorderedElementsAre( MatchesDescriptor(builtin::kStringStartsWith, CallStyle::kFree, std::vector<Kind>{Kind::kString, Kind::kString}), MatchesDescriptor(builtin::kStringStartsWith, CallStyle::kReceiver, std::vector<Kind>{Kind::kString, Kind::kString}))); EXPECT_THAT( overloads[builtin::kStringEndsWith], UnorderedElementsAre( MatchesDescriptor(builtin::kStringEndsWith, CallStyle::kFree, std::vector<Kind>{Kind::kString, Kind::kString}), MatchesDescriptor(builtin::kStringEndsWith, CallStyle::kReceiver, std::vector<Kind>{Kind::kString, Kind::kString}))); } TEST(RegisterStringFunctions, ConcatSkippedWhenDisabled) { FunctionRegistry registry; RuntimeOptions options; options.enable_string_concat = false; ASSERT_OK(RegisterStringFunctions(registry, options)); auto overloads = registry.ListFunctions(); EXPECT_THAT(overloads[builtin::kAdd], IsEmpty()); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/standard/string_functions.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/standard/string_functions_test.cc
4552db5798fb0853b131b783d8875794334fae7f
9be7b229-09c8-4138-96c7-ad097a47e3ee
cpp
google/cel-cpp
type_conversion_functions
runtime/standard/type_conversion_functions.cc
runtime/standard/type_conversion_functions_test.cc
#include "runtime/standard/type_conversion_functions.h" #include <cstdint> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "base/builtins.h" #include "base/function_adapter.h" #include "common/value.h" #include "common/value_manager.h" #include "internal/overflow.h" #include "internal/status_macros.h" #include "internal/time.h" #include "runtime/function_registry.h" #include "runtime/runtime_options.h" namespace cel { namespace { using ::cel::internal::EncodeDurationToJson; using ::cel::internal::EncodeTimestampToJson; using ::cel::internal::MaxTimestamp; const absl::Time kMaxTime = MaxTimestamp(); absl::Status RegisterBoolConversionFunctions(FunctionRegistry& registry, const RuntimeOptions&) { return UnaryFunctionAdapter<bool, bool>::RegisterGlobalOverload( cel::builtin::kBool, [](ValueManager&, bool v) { return v; }, registry); } absl::Status RegisterIntConversionFunctions(FunctionRegistry& registry, const RuntimeOptions&) { absl::Status status = UnaryFunctionAdapter<int64_t, bool>::RegisterGlobalOverload( cel::builtin::kInt, [](ValueManager&, bool v) { return static_cast<int64_t>(v); }, registry); CEL_RETURN_IF_ERROR(status); status = UnaryFunctionAdapter<Value, double>::RegisterGlobalOverload( cel::builtin::kInt, [](ValueManager& value_factory, double v) -> Value { auto conv = cel::internal::CheckedDoubleToInt64(v); if (!conv.ok()) { return value_factory.CreateErrorValue(conv.status()); } return value_factory.CreateIntValue(*conv); }, registry); CEL_RETURN_IF_ERROR(status); status = UnaryFunctionAdapter<int64_t, int64_t>::RegisterGlobalOverload( cel::builtin::kInt, [](ValueManager&, int64_t v) { return v; }, registry); CEL_RETURN_IF_ERROR(status); status = UnaryFunctionAdapter<Value, const StringValue&>::RegisterGlobalOverload( cel::builtin::kInt, [](ValueManager& value_factory, const StringValue& s) -> Value { int64_t result; if (!absl::SimpleAtoi(s.ToString(), &result)) { return value_factory.CreateErrorValue( absl::InvalidArgumentError("cannot convert string to int")); } return value_factory.CreateIntValue(result); }, registry); CEL_RETURN_IF_ERROR(status); status = UnaryFunctionAdapter<int64_t, absl::Time>::RegisterGlobalOverload( cel::builtin::kInt, [](ValueManager&, absl::Time t) { return absl::ToUnixSeconds(t); }, registry); CEL_RETURN_IF_ERROR(status); return UnaryFunctionAdapter<Value, uint64_t>::RegisterGlobalOverload( cel::builtin::kInt, [](ValueManager& value_factory, uint64_t v) -> Value { auto conv = cel::internal::CheckedUint64ToInt64(v); if (!conv.ok()) { return value_factory.CreateErrorValue(conv.status()); } return value_factory.CreateIntValue(*conv); }, registry); } absl::Status RegisterStringConversionFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { if (!options.enable_string_conversion) { return absl::OkStatus(); } absl::Status status = UnaryFunctionAdapter<Value, const BytesValue&>::RegisterGlobalOverload( cel::builtin::kString, [](ValueManager& value_factory, const BytesValue& value) -> Value { auto handle_or = value_factory.CreateStringValue(value.ToString()); if (!handle_or.ok()) { return value_factory.CreateErrorValue(handle_or.status()); } return *handle_or; }, registry); CEL_RETURN_IF_ERROR(status); status = UnaryFunctionAdapter<StringValue, double>::RegisterGlobalOverload( cel::builtin::kString, [](ValueManager& value_factory, double value) -> StringValue { return value_factory.CreateUncheckedStringValue(absl::StrCat(value)); }, registry); CEL_RETURN_IF_ERROR(status); status = UnaryFunctionAdapter<StringValue, int64_t>::RegisterGlobalOverload( cel::builtin::kString, [](ValueManager& value_factory, int64_t value) -> StringValue { return value_factory.CreateUncheckedStringValue(absl::StrCat(value)); }, registry); CEL_RETURN_IF_ERROR(status); status = UnaryFunctionAdapter<StringValue, StringValue>::RegisterGlobalOverload( cel::builtin::kString, [](ValueManager&, StringValue value) -> StringValue { return value; }, registry); CEL_RETURN_IF_ERROR(status); status = UnaryFunctionAdapter<StringValue, uint64_t>::RegisterGlobalOverload( cel::builtin::kString, [](ValueManager& value_factory, uint64_t value) -> StringValue { return value_factory.CreateUncheckedStringValue(absl::StrCat(value)); }, registry); CEL_RETURN_IF_ERROR(status); status = UnaryFunctionAdapter<Value, absl::Duration>::RegisterGlobalOverload( cel::builtin::kString, [](ValueManager& value_factory, absl::Duration value) -> Value { auto encode = EncodeDurationToJson(value); if (!encode.ok()) { return value_factory.CreateErrorValue(encode.status()); } return value_factory.CreateUncheckedStringValue(*encode); }, registry); CEL_RETURN_IF_ERROR(status); return UnaryFunctionAdapter<Value, absl::Time>::RegisterGlobalOverload( cel::builtin::kString, [](ValueManager& value_factory, absl::Time value) -> Value { auto encode = EncodeTimestampToJson(value); if (!encode.ok()) { return value_factory.CreateErrorValue(encode.status()); } return value_factory.CreateUncheckedStringValue(*encode); }, registry); } absl::Status RegisterUintConversionFunctions(FunctionRegistry& registry, const RuntimeOptions&) { absl::Status status = UnaryFunctionAdapter<Value, double>::RegisterGlobalOverload( cel::builtin::kUint, [](ValueManager& value_factory, double v) -> Value { auto conv = cel::internal::CheckedDoubleToUint64(v); if (!conv.ok()) { return value_factory.CreateErrorValue(conv.status()); } return value_factory.CreateUintValue(*conv); }, registry); CEL_RETURN_IF_ERROR(status); status = UnaryFunctionAdapter<Value, int64_t>::RegisterGlobalOverload( cel::builtin::kUint, [](ValueManager& value_factory, int64_t v) -> Value { auto conv = cel::internal::CheckedInt64ToUint64(v); if (!conv.ok()) { return value_factory.CreateErrorValue(conv.status()); } return value_factory.CreateUintValue(*conv); }, registry); CEL_RETURN_IF_ERROR(status); status = UnaryFunctionAdapter<Value, const StringValue&>::RegisterGlobalOverload( cel::builtin::kUint, [](ValueManager& value_factory, const StringValue& s) -> Value { uint64_t result; if (!absl::SimpleAtoi(s.ToString(), &result)) { return value_factory.CreateErrorValue( absl::InvalidArgumentError("doesn't convert to a string")); } return value_factory.CreateUintValue(result); }, registry); CEL_RETURN_IF_ERROR(status); return UnaryFunctionAdapter<uint64_t, uint64_t>::RegisterGlobalOverload( cel::builtin::kUint, [](ValueManager&, uint64_t v) { return v; }, registry); } absl::Status RegisterBytesConversionFunctions(FunctionRegistry& registry, const RuntimeOptions&) { absl::Status status = UnaryFunctionAdapter<BytesValue, BytesValue>::RegisterGlobalOverload( cel::builtin::kBytes, [](ValueManager&, BytesValue value) -> BytesValue { return value; }, registry); CEL_RETURN_IF_ERROR(status); return UnaryFunctionAdapter<absl::StatusOr<BytesValue>, const StringValue&>:: RegisterGlobalOverload( cel::builtin::kBytes, [](ValueManager& value_factory, const StringValue& value) { return value_factory.CreateBytesValue(value.ToString()); }, registry); } absl::Status RegisterDoubleConversionFunctions(FunctionRegistry& registry, const RuntimeOptions&) { absl::Status status = UnaryFunctionAdapter<double, double>::RegisterGlobalOverload( cel::builtin::kDouble, [](ValueManager&, double v) { return v; }, registry); CEL_RETURN_IF_ERROR(status); status = UnaryFunctionAdapter<double, int64_t>::RegisterGlobalOverload( cel::builtin::kDouble, [](ValueManager&, int64_t v) { return static_cast<double>(v); }, registry); CEL_RETURN_IF_ERROR(status); status = UnaryFunctionAdapter<Value, const StringValue&>::RegisterGlobalOverload( cel::builtin::kDouble, [](ValueManager& value_factory, const StringValue& s) -> Value { double result; if (absl::SimpleAtod(s.ToString(), &result)) { return value_factory.CreateDoubleValue(result); } else { return value_factory.CreateErrorValue(absl::InvalidArgumentError( "cannot convert string to double")); } }, registry); CEL_RETURN_IF_ERROR(status); return UnaryFunctionAdapter<double, uint64_t>::RegisterGlobalOverload( cel::builtin::kDouble, [](ValueManager&, uint64_t v) { return static_cast<double>(v); }, registry); } Value CreateDurationFromString(ValueManager& value_factory, const StringValue& dur_str) { absl::Duration d; if (!absl::ParseDuration(dur_str.ToString(), &d)) { return value_factory.CreateErrorValue( absl::InvalidArgumentError("String to Duration conversion failed")); } auto duration = value_factory.CreateDurationValue(d); if (!duration.ok()) { return value_factory.CreateErrorValue(duration.status()); } return *duration; } absl::Status RegisterTimeConversionFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { CEL_RETURN_IF_ERROR( (UnaryFunctionAdapter<Value, const StringValue&>::RegisterGlobalOverload( cel::builtin::kDuration, CreateDurationFromString, registry))); CEL_RETURN_IF_ERROR( (UnaryFunctionAdapter<Value, int64_t>::RegisterGlobalOverload( cel::builtin::kTimestamp, [](ValueManager& value_factory, int64_t epoch_seconds) -> Value { return value_factory.CreateUncheckedTimestampValue( absl::FromUnixSeconds(epoch_seconds)); }, registry))); CEL_RETURN_IF_ERROR( (UnaryFunctionAdapter<Value, absl::Time>::RegisterGlobalOverload( cel::builtin::kTimestamp, [](ValueManager&, absl::Time value) -> Value { return TimestampValue(value); }, registry))); CEL_RETURN_IF_ERROR( (UnaryFunctionAdapter<Value, absl::Duration>::RegisterGlobalOverload( cel::builtin::kDuration, [](ValueManager&, absl::Duration value) -> Value { return DurationValue(value); }, registry))); bool enable_timestamp_duration_overflow_errors = options.enable_timestamp_duration_overflow_errors; return UnaryFunctionAdapter<Value, const StringValue&>:: RegisterGlobalOverload( cel::builtin::kTimestamp, [=](ValueManager& value_factory, const StringValue& time_str) -> Value { absl::Time ts; if (!absl::ParseTime(absl::RFC3339_full, time_str.ToString(), &ts, nullptr)) { return value_factory.CreateErrorValue(absl::InvalidArgumentError( "String to Timestamp conversion failed")); } if (enable_timestamp_duration_overflow_errors) { if (ts < absl::UniversalEpoch() || ts > kMaxTime) { return value_factory.CreateErrorValue( absl::OutOfRangeError("timestamp overflow")); } } return value_factory.CreateUncheckedTimestampValue(ts); }, registry); } } absl::Status RegisterTypeConversionFunctions(FunctionRegistry& registry, const RuntimeOptions& options) { CEL_RETURN_IF_ERROR(RegisterBoolConversionFunctions(registry, options)); CEL_RETURN_IF_ERROR(RegisterBytesConversionFunctions(registry, options)); CEL_RETURN_IF_ERROR(RegisterDoubleConversionFunctions(registry, options)); CEL_RETURN_IF_ERROR(RegisterIntConversionFunctions(registry, options)); CEL_RETURN_IF_ERROR(RegisterStringConversionFunctions(registry, options)); CEL_RETURN_IF_ERROR(RegisterUintConversionFunctions(registry, options)); CEL_RETURN_IF_ERROR(RegisterTimeConversionFunctions(registry, options)); absl::Status status = UnaryFunctionAdapter<Value, const Value&>::RegisterGlobalOverload( cel::builtin::kDyn, [](ValueManager&, const Value& value) -> Value { return value; }, registry); CEL_RETURN_IF_ERROR(status); return UnaryFunctionAdapter<Value, const Value&>::RegisterGlobalOverload( cel::builtin::kType, [](ValueManager& factory, const Value& value) { return factory.CreateTypeValue(value.GetRuntimeType()); }, registry); } }
#include "runtime/standard/type_conversion_functions.h" #include <vector> #include "base/builtins.h" #include "base/function_descriptor.h" #include "internal/testing.h" namespace cel { namespace { using ::testing::IsEmpty; using ::testing::UnorderedElementsAre; MATCHER_P3(MatchesUnaryDescriptor, name, receiver, expected_kind, "") { const FunctionDescriptor& descriptor = arg.descriptor; std::vector<Kind> types{expected_kind}; return descriptor.name() == name && descriptor.receiver_style() == receiver && descriptor.types() == types; } TEST(RegisterTypeConversionFunctions, RegisterBoolConversionFunctions) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterTypeConversionFunctions(registry, options)); EXPECT_THAT(registry.FindStaticOverloads(builtin::kBool, false, {Kind::kAny}), UnorderedElementsAre( MatchesUnaryDescriptor(builtin::kBool, false, Kind::kBool))); } TEST(RegisterTypeConversionFunctions, RegisterIntConversionFunctions) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterTypeConversionFunctions(registry, options)); EXPECT_THAT( registry.FindStaticOverloads(builtin::kInt, false, {Kind::kAny}), UnorderedElementsAre( MatchesUnaryDescriptor(builtin::kInt, false, Kind::kInt), MatchesUnaryDescriptor(builtin::kInt, false, Kind::kDouble), MatchesUnaryDescriptor(builtin::kInt, false, Kind::kUint), MatchesUnaryDescriptor(builtin::kInt, false, Kind::kBool), MatchesUnaryDescriptor(builtin::kInt, false, Kind::kString), MatchesUnaryDescriptor(builtin::kInt, false, Kind::kTimestamp))); } TEST(RegisterTypeConversionFunctions, RegisterUintConversionFunctions) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterTypeConversionFunctions(registry, options)); EXPECT_THAT( registry.FindStaticOverloads(builtin::kUint, false, {Kind::kAny}), UnorderedElementsAre( MatchesUnaryDescriptor(builtin::kUint, false, Kind::kInt), MatchesUnaryDescriptor(builtin::kUint, false, Kind::kDouble), MatchesUnaryDescriptor(builtin::kUint, false, Kind::kUint), MatchesUnaryDescriptor(builtin::kUint, false, Kind::kString))); } TEST(RegisterTypeConversionFunctions, RegisterDoubleConversionFunctions) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterTypeConversionFunctions(registry, options)); EXPECT_THAT( registry.FindStaticOverloads(builtin::kDouble, false, {Kind::kAny}), UnorderedElementsAre( MatchesUnaryDescriptor(builtin::kDouble, false, Kind::kInt), MatchesUnaryDescriptor(builtin::kDouble, false, Kind::kDouble), MatchesUnaryDescriptor(builtin::kDouble, false, Kind::kUint), MatchesUnaryDescriptor(builtin::kDouble, false, Kind::kString))); } TEST(RegisterTypeConversionFunctions, RegisterStringConversionFunctions) { FunctionRegistry registry; RuntimeOptions options; options.enable_string_conversion = true; ASSERT_OK(RegisterTypeConversionFunctions(registry, options)); EXPECT_THAT( registry.FindStaticOverloads(builtin::kString, false, {Kind::kAny}), UnorderedElementsAre( MatchesUnaryDescriptor(builtin::kString, false, Kind::kInt), MatchesUnaryDescriptor(builtin::kString, false, Kind::kDouble), MatchesUnaryDescriptor(builtin::kString, false, Kind::kUint), MatchesUnaryDescriptor(builtin::kString, false, Kind::kString), MatchesUnaryDescriptor(builtin::kString, false, Kind::kBytes), MatchesUnaryDescriptor(builtin::kString, false, Kind::kDuration), MatchesUnaryDescriptor(builtin::kString, false, Kind::kTimestamp))); } TEST(RegisterTypeConversionFunctions, RegisterStringConversionFunctionsDisabled) { FunctionRegistry registry; RuntimeOptions options; options.enable_string_conversion = false; ASSERT_OK(RegisterTypeConversionFunctions(registry, options)); EXPECT_THAT( registry.FindStaticOverloads(builtin::kString, false, {Kind::kAny}), IsEmpty()); } TEST(RegisterTypeConversionFunctions, RegisterBytesConversionFunctions) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterTypeConversionFunctions(registry, options)); EXPECT_THAT( registry.FindStaticOverloads(builtin::kBytes, false, {Kind::kAny}), UnorderedElementsAre( MatchesUnaryDescriptor(builtin::kBytes, false, Kind::kBytes), MatchesUnaryDescriptor(builtin::kBytes, false, Kind::kString))); } TEST(RegisterTypeConversionFunctions, RegisterTimeConversionFunctions) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterTypeConversionFunctions(registry, options)); EXPECT_THAT( registry.FindStaticOverloads(builtin::kTimestamp, false, {Kind::kAny}), UnorderedElementsAre( MatchesUnaryDescriptor(builtin::kTimestamp, false, Kind::kInt), MatchesUnaryDescriptor(builtin::kTimestamp, false, Kind::kString), MatchesUnaryDescriptor(builtin::kTimestamp, false, Kind::kTimestamp))); EXPECT_THAT( registry.FindStaticOverloads(builtin::kDuration, false, {Kind::kAny}), UnorderedElementsAre( MatchesUnaryDescriptor(builtin::kDuration, false, Kind::kString), MatchesUnaryDescriptor(builtin::kDuration, false, Kind::kDuration))); } TEST(RegisterTypeConversionFunctions, RegisterMetaTypeConversionFunctions) { FunctionRegistry registry; RuntimeOptions options; ASSERT_OK(RegisterTypeConversionFunctions(registry, options)); EXPECT_THAT(registry.FindStaticOverloads(builtin::kDyn, false, {Kind::kAny}), UnorderedElementsAre( MatchesUnaryDescriptor(builtin::kDyn, false, Kind::kAny))); EXPECT_THAT(registry.FindStaticOverloads(builtin::kType, false, {Kind::kAny}), UnorderedElementsAre( MatchesUnaryDescriptor(builtin::kType, false, Kind::kAny))); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/standard/type_conversion_functions.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/runtime/standard/type_conversion_functions_test.cc
4552db5798fb0853b131b783d8875794334fae7f
ce5dca60-fff5-4672-8eb0-97c15b454f73
cpp
google/cel-cpp
regex_functions
extensions/regex_functions.cc
extensions/regex_functions_test.cc
#include "extensions/regex_functions.h" #include <memory> #include <string> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/types/span.h" #include "eval/public/cel_function.h" #include "eval/public/cel_options.h" #include "eval/public/cel_value.h" #include "eval/public/containers/container_backed_map_impl.h" #include "eval/public/portable_cel_function_adapter.h" #include "re2/re2.h" namespace cel::extensions { namespace { using ::google::api::expr::runtime::CelFunction; using ::google::api::expr::runtime::CelFunctionRegistry; using ::google::api::expr::runtime::CelValue; using ::google::api::expr::runtime::CreateErrorValue; using ::google::api::expr::runtime::InterpreterOptions; using ::google::api::expr::runtime::PortableBinaryFunctionAdapter; using ::google::api::expr::runtime::PortableFunctionAdapter; using ::google::protobuf::Arena; CelValue ExtractString(Arena* arena, CelValue::StringHolder target, CelValue::StringHolder regex, CelValue::StringHolder rewrite) { RE2 re2(regex.value()); if (!re2.ok()) { return CreateErrorValue( arena, absl::InvalidArgumentError("Given Regex is Invalid")); } std::string output; auto result = RE2::Extract(target.value(), re2, rewrite.value(), &output); if (!result) { return CreateErrorValue( arena, absl::InvalidArgumentError( "Unable to extract string for the given regex")); } return CelValue::CreateString( google::protobuf::Arena::Create<std::string>(arena, output)); } CelValue CaptureString(Arena* arena, CelValue::StringHolder target, CelValue::StringHolder regex) { RE2 re2(regex.value()); if (!re2.ok()) { return CreateErrorValue( arena, absl::InvalidArgumentError("Given Regex is Invalid")); } std::string output; auto result = RE2::FullMatch(target.value(), re2, &output); if (!result) { return CreateErrorValue( arena, absl::InvalidArgumentError( "Unable to capture groups for the given regex")); } else { auto cel_value = CelValue::CreateString( google::protobuf::Arena::Create<std::string>(arena, output)); return cel_value; } } CelValue CaptureStringN(Arena* arena, CelValue::StringHolder target, CelValue::StringHolder regex) { RE2 re2(regex.value()); if (!re2.ok()) { return CreateErrorValue( arena, absl::InvalidArgumentError("Given Regex is Invalid")); } const int capturing_groups_count = re2.NumberOfCapturingGroups(); const auto& named_capturing_groups_map = re2.CapturingGroupNames(); if (capturing_groups_count <= 0) { return CreateErrorValue(arena, absl::InvalidArgumentError( "Capturing groups were not found in the given " "regex.")); } std::vector<std::string> captured_strings(capturing_groups_count); std::vector<RE2::Arg> captured_string_addresses(capturing_groups_count); std::vector<RE2::Arg*> argv(capturing_groups_count); for (int j = 0; j < capturing_groups_count; j++) { captured_string_addresses[j] = &captured_strings[j]; argv[j] = &captured_string_addresses[j]; } auto result = RE2::FullMatchN(target.value(), re2, argv.data(), capturing_groups_count); if (!result) { return CreateErrorValue( arena, absl::InvalidArgumentError( "Unable to capture groups for the given regex")); } std::vector<std::pair<CelValue, CelValue>> cel_values; for (int index = 1; index <= capturing_groups_count; index++) { auto it = named_capturing_groups_map.find(index); std::string name = it != named_capturing_groups_map.end() ? it->second : std::to_string(index); cel_values.emplace_back( CelValue::CreateString(google::protobuf::Arena::Create<std::string>(arena, name)), CelValue::CreateString(google::protobuf::Arena::Create<std::string>( arena, captured_strings[index - 1]))); } auto container_map = google::api::expr::runtime::CreateContainerBackedMap( absl::MakeSpan(cel_values)); ::google::api::expr::runtime::CelMap* cel_map = container_map->release(); arena->Own(cel_map); return CelValue::CreateMap(cel_map); } absl::Status RegisterRegexFunctions(CelFunctionRegistry* registry) { CEL_RETURN_IF_ERROR( (PortableFunctionAdapter<CelValue, CelValue::StringHolder, CelValue::StringHolder, CelValue::StringHolder>:: CreateAndRegister( kRegexExtract, false, [](Arena* arena, CelValue::StringHolder target, CelValue::StringHolder regex, CelValue::StringHolder rewrite) -> CelValue { return ExtractString(arena, target, regex, rewrite); }, registry))); CEL_RETURN_IF_ERROR(registry->Register( PortableBinaryFunctionAdapter<CelValue, CelValue::StringHolder, CelValue::StringHolder>:: Create(kRegexCapture, false, [](Arena* arena, CelValue::StringHolder target, CelValue::StringHolder regex) -> CelValue { return CaptureString(arena, target, regex); }))); return registry->Register( PortableBinaryFunctionAdapter<CelValue, CelValue::StringHolder, CelValue::StringHolder>:: Create(kRegexCaptureN, false, [](Arena* arena, CelValue::StringHolder target, CelValue::StringHolder regex) -> CelValue { return CaptureStringN(arena, target, regex); })); } } absl::Status RegisterRegexFunctions(CelFunctionRegistry* registry, const InterpreterOptions& options) { if (options.enable_regex) { CEL_RETURN_IF_ERROR(RegisterRegexFunctions(registry)); } return absl::OkStatus(); } }
#include "extensions/regex_functions.h" #include <memory> #include <string> #include <utility> #include <vector> #include "google/protobuf/arena.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "eval/public/activation.h" #include "eval/public/cel_expr_builder_factory.h" #include "eval/public/cel_options.h" #include "eval/public/cel_value.h" #include "eval/public/containers/container_backed_map_impl.h" #include "eval/public/testing/matchers.h" #include "internal/testing.h" #include "parser/parser.h" namespace cel::extensions { namespace { using ::absl_testing::StatusIs; using ::google::api::expr::runtime::CelValue; using Builder = ::google::api::expr::runtime::CelExpressionBuilder; using ::absl_testing::IsOkAndHolds; using ::google::api::expr::parser::Parse; using ::google::api::expr::runtime::test::IsCelError; using ::google::api::expr::runtime::test::IsCelString; struct TestCase { const std::string expr_string; const std::string expected_result; }; class RegexFunctionsTest : public ::testing::TestWithParam<TestCase> { public: RegexFunctionsTest() { options_.enable_regex = true; options_.enable_qualified_identifier_rewrites = true; builder_ = CreateCelExpressionBuilder(options_); } absl::StatusOr<CelValue> TestCaptureStringInclusion( const std::string& expr_string) { CEL_RETURN_IF_ERROR( RegisterRegexFunctions(builder_->GetRegistry(), options_)); CEL_ASSIGN_OR_RETURN(auto parsed_expr, Parse(expr_string)); CEL_ASSIGN_OR_RETURN( auto expr_plan, builder_->CreateExpression(&parsed_expr.expr(), &parsed_expr.source_info())); ::google::api::expr::runtime::Activation activation; return expr_plan->Evaluate(activation, &arena_); } google::protobuf::Arena arena_; google::api::expr::runtime::InterpreterOptions options_; std::unique_ptr<Builder> builder_; }; TEST_F(RegexFunctionsTest, CaptureStringSuccessWithCombinationOfGroups) { std::vector<std::pair<CelValue, CelValue>> cel_values; cel_values.emplace_back(std::make_pair( CelValue::CreateString(google::protobuf::Arena::Create<std::string>(&arena_, "1")), CelValue::CreateString( google::protobuf::Arena::Create<std::string>(&arena_, "user")))); cel_values.emplace_back(std::make_pair( CelValue::CreateString( google::protobuf::Arena::Create<std::string>(&arena_, "Username")), CelValue::CreateString( google::protobuf::Arena::Create<std::string>(&arena_, "testuser")))); cel_values.emplace_back( std::make_pair(CelValue::CreateString( google::protobuf::Arena::Create<std::string>(&arena_, "Domain")), CelValue::CreateString(google::protobuf::Arena::Create<std::string>( &arena_, "testdomain")))); auto container_map = google::api::expr::runtime::CreateContainerBackedMap( absl::MakeSpan(cel_values)); auto* cel_map = container_map->release(); arena_.Own(cel_map); CelValue expected_result = CelValue::CreateMap(cel_map); auto status = TestCaptureStringInclusion( (R"(re.captureN('The user testuser belongs to testdomain', 'The (user|domain) (?P<Username>.*) belongs to (?P<Domain>.*)'))")); ASSERT_OK(status.status()); EXPECT_EQ(status.value().DebugString(), expected_result.DebugString()); } TEST_F(RegexFunctionsTest, CaptureStringSuccessWithSingleNamedGroup) { std::vector<std::pair<CelValue, CelValue>> cel_values; cel_values.push_back(std::make_pair( CelValue::CreateString( google::protobuf::Arena::Create<std::string>(&arena_, "username")), CelValue::CreateString( google::protobuf::Arena::Create<std::string>(&arena_, "testuser")))); auto container_map = google::api::expr::runtime::CreateContainerBackedMap( absl::MakeSpan(cel_values)); auto cel_map = container_map->release(); arena_.Own(cel_map); CelValue expected_result = CelValue::CreateMap(cel_map); auto status = TestCaptureStringInclusion((R"(re.captureN('testuser@', '(?P<username>.*)@'))")); ASSERT_OK(status.status()); EXPECT_EQ(status.value().DebugString(), expected_result.DebugString()); } TEST_F(RegexFunctionsTest, CaptureStringSuccessWithMultipleUnamedGroups) { std::vector<std::pair<CelValue, CelValue>> cel_values; cel_values.emplace_back(std::make_pair( CelValue::CreateString(google::protobuf::Arena::Create<std::string>(&arena_, "1")), CelValue::CreateString( google::protobuf::Arena::Create<std::string>(&arena_, "testuser")))); cel_values.emplace_back(std::make_pair( CelValue::CreateString(google::protobuf::Arena::Create<std::string>(&arena_, "2")), CelValue::CreateString( google::protobuf::Arena::Create<std::string>(&arena_, "testdomain")))); auto container_map = google::api::expr::runtime::CreateContainerBackedMap( absl::MakeSpan(cel_values)); auto cel_map = container_map->release(); arena_.Own(cel_map); CelValue expected_result = CelValue::CreateMap(cel_map); auto status = TestCaptureStringInclusion((R"(re.captureN('testuser@testdomain', '(.*)@([^.]*)'))")); ASSERT_OK(status.status()); EXPECT_EQ(status.value().DebugString(), expected_result.DebugString()); } TEST_F(RegexFunctionsTest, ExtractStringWithNamedAndUnnamedGroups) { auto status = TestCaptureStringInclusion( (R"(re.extract('The user testuser belongs to testdomain', 'The (user|domain) (?P<Username>.*) belongs to (?P<Domain>.*)', '\\3 contains \\1 \\2'))")); ASSERT_TRUE(status.value().IsString()); EXPECT_THAT(status, IsOkAndHolds(IsCelString("testdomain contains user testuser"))); } TEST_F(RegexFunctionsTest, ExtractStringWithEmptyStrings) { std::string expected_result = ""; auto status = TestCaptureStringInclusion((R"(re.extract('', '', ''))")); ASSERT_TRUE(status.value().IsString()); EXPECT_THAT(status, IsOkAndHolds(IsCelString(expected_result))); } TEST_F(RegexFunctionsTest, ExtractStringWithUnnamedGroups) { auto status = TestCaptureStringInclusion( (R"(re.extract('[email protected]', '(.*)@([^.]*)', '\\2!\\1'))")); EXPECT_THAT(status, IsOkAndHolds(IsCelString("google!testuser"))); } TEST_F(RegexFunctionsTest, ExtractStringWithNoGroups) { auto status = TestCaptureStringInclusion((R"(re.extract('foo', '.*', '\'\\0\''))")); EXPECT_THAT(status, IsOkAndHolds(IsCelString("'foo'"))); } TEST_F(RegexFunctionsTest, CaptureStringWithUnnamedGroups) { auto status = TestCaptureStringInclusion((R"(re.capture('foo', 'fo(o)'))")); EXPECT_THAT(status, IsOkAndHolds(IsCelString("o"))); } std::vector<TestCase> createParams() { return { { (R"(re.extract('foo', 'f(o+)(s)', '\\1\\2'))"), "Unable to extract string for the given regex"}, { (R"(re.extract('foo', 'f(o+)', '\\1\\2'))"), "Unable to extract string for the given regex"}, { (R"(re.extract('foo', 'f(o+)(abc', '\\1\\2'))"), "Regex is Invalid"}, { (R"(re.capture('foo', ''))"), "Unable to capture groups for the given regex"}, { (R"(re.capture('foo', '.*'))"), "Unable to capture groups for the given regex"}, { (R"(re.capture('', 'bar'))"), "Unable to capture groups for the given regex"}, { (R"(re.capture('foo', 'fo(o+)(s)'))"), "Unable to capture groups for the given regex"}, { (R"(re.capture('foo', 'fo(o+)(abc'))"), "Regex is Invalid"}, { (R"(re.captureN('foo', ''))"), "Capturing groups were not found in the given regex."}, { (R"(re.captureN('foo', '.*'))"), "Capturing groups were not found in the given regex."}, { (R"(re.captureN('', 'bar'))"), "Capturing groups were not found in the given regex."}, { (R"(re.captureN('foo', 'fo(o+)(s)'))"), "Unable to capture groups for the given regex"}, { (R"(re.captureN('foo', 'fo(o+)(abc'))"), "Regex is Invalid"}, }; } TEST_P(RegexFunctionsTest, RegexFunctionsTests) { const TestCase& test_case = GetParam(); ABSL_LOG(INFO) << "Testing Cel Expression: " << test_case.expr_string; auto status = TestCaptureStringInclusion(test_case.expr_string); EXPECT_THAT( status.value(), IsCelError(StatusIs(absl::StatusCode::kInvalidArgument, testing::HasSubstr(test_case.expected_result)))); } INSTANTIATE_TEST_SUITE_P(RegexFunctionsTest, RegexFunctionsTest, testing::ValuesIn(createParams())); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/regex_functions.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/extensions/regex_functions_test.cc
4552db5798fb0853b131b783d8875794334fae7f
1fa7adaf-94c9-45aa-bdf9-54656547fa6f
cpp
google/cel-cpp
comparison_functions
eval/public/comparison_functions.cc
eval/public/comparison_functions_test.cc
#include "eval/public/comparison_functions.h" #include "absl/status/status.h" #include "eval/public/cel_function_registry.h" #include "eval/public/cel_options.h" #include "runtime/function_registry.h" #include "runtime/runtime_options.h" #include "runtime/standard/comparison_functions.h" namespace google::api::expr::runtime { absl::Status RegisterComparisonFunctions(CelFunctionRegistry* registry, const InterpreterOptions& options) { cel::RuntimeOptions modern_options = ConvertToRuntimeOptions(options); cel::FunctionRegistry& modern_registry = registry->InternalGetRegistry(); return cel::RegisterComparisonFunctions(modern_registry, modern_options); } }
#include "eval/public/comparison_functions.h" #include <memory> #include <tuple> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "google/rpc/context/attribute_context.pb.h" #include "google/protobuf/arena.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "eval/public/activation.h" #include "eval/public/cel_expr_builder_factory.h" #include "eval/public/cel_expression.h" #include "eval/public/cel_function_registry.h" #include "eval/public/cel_options.h" #include "eval/public/cel_value.h" #include "eval/public/testing/matchers.h" #include "internal/status_macros.h" #include "internal/testing.h" #include "parser/parser.h" namespace google::api::expr::runtime { namespace { using ::google::api::expr::v1alpha1::ParsedExpr; using ::google::rpc::context::AttributeContext; using ::testing::Combine; using ::testing::ValuesIn; MATCHER_P2(DefinesHomogenousOverload, name, argument_type, absl::StrCat(name, " for ", CelValue::TypeName(argument_type))) { const CelFunctionRegistry& registry = arg; return !registry .FindOverloads(name, false, {argument_type, argument_type}) .empty(); return false; } struct ComparisonTestCase { absl::string_view expr; bool result; CelValue lhs = CelValue::CreateNull(); CelValue rhs = CelValue::CreateNull(); }; class ComparisonFunctionTest : public testing::TestWithParam<std::tuple<ComparisonTestCase, bool>> { public: ComparisonFunctionTest() { options_.enable_heterogeneous_equality = std::get<1>(GetParam()); options_.enable_empty_wrapper_null_unboxing = true; builder_ = CreateCelExpressionBuilder(options_); } CelFunctionRegistry& registry() { return *builder_->GetRegistry(); } absl::StatusOr<CelValue> Evaluate(absl::string_view expr, const CelValue& lhs, const CelValue& rhs) { CEL_ASSIGN_OR_RETURN(ParsedExpr parsed_expr, parser::Parse(expr)); Activation activation; activation.InsertValue("lhs", lhs); activation.InsertValue("rhs", rhs); CEL_ASSIGN_OR_RETURN(auto expression, builder_->CreateExpression( &parsed_expr.expr(), &parsed_expr.source_info())); return expression->Evaluate(activation, &arena_); } protected: std::unique_ptr<CelExpressionBuilder> builder_; InterpreterOptions options_; google::protobuf::Arena arena_; }; TEST_P(ComparisonFunctionTest, SmokeTest) { ComparisonTestCase test_case = std::get<0>(GetParam()); google::protobuf::LinkMessageReflection<AttributeContext>(); ASSERT_OK(RegisterComparisonFunctions(&registry(), options_)); ASSERT_OK_AND_ASSIGN(auto result, Evaluate(test_case.expr, test_case.lhs, test_case.rhs)); EXPECT_THAT(result, test::IsCelBool(test_case.result)); } INSTANTIATE_TEST_SUITE_P( LessThan, ComparisonFunctionTest, Combine(ValuesIn<ComparisonTestCase>( { {"false < true", true}, {"1 < 2", true}, {"-2 < -1", true}, {"1.1 < 1.2", true}, {"'a' < 'b'", true}, {"lhs < rhs", true, CelValue::CreateBytesView("a"), CelValue::CreateBytesView("b")}, {"lhs < rhs", true, CelValue::CreateDuration(absl::Seconds(1)), CelValue::CreateDuration(absl::Seconds(2))}, {"lhs < rhs", true, CelValue::CreateTimestamp(absl::FromUnixSeconds(20)), CelValue::CreateTimestamp(absl::FromUnixSeconds(30))}}), testing::Bool())); INSTANTIATE_TEST_SUITE_P( GreaterThan, ComparisonFunctionTest, testing::Combine( testing::ValuesIn<ComparisonTestCase>( {{"false > true", false}, {"1 > 2", false}, {"-2 > -1", false}, {"1.1 > 1.2", false}, {"'a' > 'b'", false}, {"lhs > rhs", false, CelValue::CreateBytesView("a"), CelValue::CreateBytesView("b")}, {"lhs > rhs", false, CelValue::CreateDuration(absl::Seconds(1)), CelValue::CreateDuration(absl::Seconds(2))}, {"lhs > rhs", false, CelValue::CreateTimestamp(absl::FromUnixSeconds(20)), CelValue::CreateTimestamp(absl::FromUnixSeconds(30))}}), testing::Bool())); INSTANTIATE_TEST_SUITE_P( GreaterOrEqual, ComparisonFunctionTest, Combine(ValuesIn<ComparisonTestCase>( {{"false >= true", false}, {"1 >= 2", false}, {"-2 >= -1", false}, {"1.1 >= 1.2", false}, {"'a' >= 'b'", false}, {"lhs >= rhs", false, CelValue::CreateBytesView("a"), CelValue::CreateBytesView("b")}, {"lhs >= rhs", false, CelValue::CreateDuration(absl::Seconds(1)), CelValue::CreateDuration(absl::Seconds(2))}, {"lhs >= rhs", false, CelValue::CreateTimestamp(absl::FromUnixSeconds(20)), CelValue::CreateTimestamp(absl::FromUnixSeconds(30))}}), testing::Bool())); INSTANTIATE_TEST_SUITE_P( LessOrEqual, ComparisonFunctionTest, Combine(testing::ValuesIn<ComparisonTestCase>( {{"false <= true", true}, {"1 <= 2", true}, {"-2 <= -1", true}, {"1.1 <= 1.2", true}, {"'a' <= 'b'", true}, {"lhs <= rhs", true, CelValue::CreateBytesView("a"), CelValue::CreateBytesView("b")}, {"lhs <= rhs", true, CelValue::CreateDuration(absl::Seconds(1)), CelValue::CreateDuration(absl::Seconds(2))}, {"lhs <= rhs", true, CelValue::CreateTimestamp(absl::FromUnixSeconds(20)), CelValue::CreateTimestamp(absl::FromUnixSeconds(30))}}), testing::Bool())); INSTANTIATE_TEST_SUITE_P(HeterogeneousNumericComparisons, ComparisonFunctionTest, Combine(testing::ValuesIn<ComparisonTestCase>( { {"1 < 2u", true}, {"2 < 1u", false}, {"1 < 2.1", true}, {"3 < 2.1", false}, {"1u < 2", true}, {"2u < 1", false}, {"1u < -1.1", false}, {"1u < 2.1", true}, {"1.1 < 2", true}, {"1.1 < 1", false}, {"1.0 < 1u", false}, {"1.0 < 3u", true}, {"1 <= 2u", true}, {"2 <= 1u", false}, {"1 <= 2.1", true}, {"3 <= 2.1", false}, {"1u <= 2", true}, {"1u <= 0", false}, {"1u <= -1.1", false}, {"2u <= 1.0", false}, {"1.1 <= 2", true}, {"2.1 <= 2", false}, {"1.0 <= 1u", true}, {"1.1 <= 1u", false}, {"3 > 2u", true}, {"3 > 4u", false}, {"3 > 2.1", true}, {"3 > 4.1", false}, {"3u > 2", true}, {"3u > 4", false}, {"3u > -1.1", true}, {"3u > 4.1", false}, {"3.1 > 2", true}, {"3.1 > 4", false}, {"3.0 > 1u", true}, {"3.0 > 4u", false}, {"3 >= 2u", true}, {"3 >= 4u", false}, {"3 >= 2.1", true}, {"3 >= 4.1", false}, {"3u >= 2", true}, {"3u >= 4", false}, {"3u >= -1.1", true}, {"3u >= 4.1", false}, {"3.1 >= 2", true}, {"3.1 >= 4", false}, {"3.0 >= 1u", true}, {"3.0 >= 4u", false}, {"1u >= -1", true}, {"1 >= 4u", false}, {"-1 < 1u", true}, {"1 < 9223372036854775808u", true}}), testing::Values<bool>(true))); } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/comparison_functions.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/comparison_functions_test.cc
4552db5798fb0853b131b783d8875794334fae7f
adc22d8c-272f-464f-8084-ea7c051b14e6
cpp
google/cel-cpp
message_equality
internal/message_equality.cc
internal/message_equality_test.cc
#include "internal/message_equality.h" #include <cstddef> #include <cstdint> #include <functional> #include <limits> #include <memory> #include <string> #include <type_traits> #include "absl/base/attributes.h" #include "absl/base/nullability.h" #include "absl/base/optimization.h" #include "absl/functional/overload.h" #include "absl/log/absl_check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "absl/types/variant.h" #include "common/memory.h" #include "extensions/protobuf/internal/map_reflection.h" #include "internal/json.h" #include "internal/number.h" #include "internal/status_macros.h" #include "internal/well_known_types.h" #include "google/protobuf/arena.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/message.h" #include "google/protobuf/util/message_differencer.h" namespace cel::internal { namespace { using ::cel::extensions::protobuf_internal::LookupMapValue; using ::cel::extensions::protobuf_internal::MapBegin; using ::cel::extensions::protobuf_internal::MapEnd; using ::cel::extensions::protobuf_internal::MapSize; using ::google::protobuf::Descriptor; using ::google::protobuf::DescriptorPool; using ::google::protobuf::FieldDescriptor; using ::google::protobuf::Message; using ::google::protobuf::MessageFactory; using ::google::protobuf::util::MessageDifferencer; class EquatableListValue final : public std::reference_wrapper<const google::protobuf::Message> { public: using std::reference_wrapper<const google::protobuf::Message>::reference_wrapper; }; class EquatableStruct final : public std::reference_wrapper<const google::protobuf::Message> { public: using std::reference_wrapper<const google::protobuf::Message>::reference_wrapper; }; class EquatableAny final : public std::reference_wrapper<const google::protobuf::Message> { public: using std::reference_wrapper<const google::protobuf::Message>::reference_wrapper; }; class EquatableMessage final : public std::reference_wrapper<const google::protobuf::Message> { public: using std::reference_wrapper<const google::protobuf::Message>::reference_wrapper; }; using EquatableValue = absl::variant<std::nullptr_t, bool, int64_t, uint64_t, double, well_known_types::BytesValue, well_known_types::StringValue, absl::Duration, absl::Time, EquatableListValue, EquatableStruct, EquatableAny, EquatableMessage>; struct NullValueEqualer { bool operator()(std::nullptr_t, std::nullptr_t) const { return true; } template <typename T> std::enable_if_t<std::negation_v<std::is_same<std::nullptr_t, T>>, bool> operator()(std::nullptr_t, const T&) const { return false; } }; struct BoolValueEqualer { bool operator()(bool lhs, bool rhs) const { return lhs == rhs; } template <typename T> std::enable_if_t<std::negation_v<std::is_same<bool, T>>, bool> operator()( bool, const T&) const { return false; } }; struct BytesValueEqualer { bool operator()(const well_known_types::BytesValue& lhs, const well_known_types::BytesValue& rhs) const { return lhs == rhs; } template <typename T> std::enable_if_t< std::negation_v<std::is_same<well_known_types::BytesValue, T>>, bool> operator()(const well_known_types::BytesValue&, const T&) const { return false; } }; struct IntValueEqualer { bool operator()(int64_t lhs, int64_t rhs) const { return lhs == rhs; } bool operator()(int64_t lhs, uint64_t rhs) const { return Number::FromInt64(lhs) == Number::FromUint64(rhs); } bool operator()(int64_t lhs, double rhs) const { return Number::FromInt64(lhs) == Number::FromDouble(rhs); } template <typename T> std::enable_if_t<std::conjunction_v<std::negation<std::is_same<int64_t, T>>, std::negation<std::is_same<uint64_t, T>>, std::negation<std::is_same<double, T>>>, bool> operator()(int64_t, const T&) const { return false; } }; struct UintValueEqualer { bool operator()(uint64_t lhs, int64_t rhs) const { return Number::FromUint64(lhs) == Number::FromInt64(rhs); } bool operator()(uint64_t lhs, uint64_t rhs) const { return lhs == rhs; } bool operator()(uint64_t lhs, double rhs) const { return Number::FromUint64(lhs) == Number::FromDouble(rhs); } template <typename T> std::enable_if_t<std::conjunction_v<std::negation<std::is_same<int64_t, T>>, std::negation<std::is_same<uint64_t, T>>, std::negation<std::is_same<double, T>>>, bool> operator()(uint64_t, const T&) const { return false; } }; struct DoubleValueEqualer { bool operator()(double lhs, int64_t rhs) const { return Number::FromDouble(lhs) == Number::FromInt64(rhs); } bool operator()(double lhs, uint64_t rhs) const { return Number::FromDouble(lhs) == Number::FromUint64(rhs); } bool operator()(double lhs, double rhs) const { return lhs == rhs; } template <typename T> std::enable_if_t<std::conjunction_v<std::negation<std::is_same<int64_t, T>>, std::negation<std::is_same<uint64_t, T>>, std::negation<std::is_same<double, T>>>, bool> operator()(double, const T&) const { return false; } }; struct StringValueEqualer { bool operator()(const well_known_types::StringValue& lhs, const well_known_types::StringValue& rhs) const { return lhs == rhs; } template <typename T> std::enable_if_t< std::negation_v<std::is_same<well_known_types::StringValue, T>>, bool> operator()(const well_known_types::StringValue&, const T&) const { return false; } }; struct DurationEqualer { bool operator()(absl::Duration lhs, absl::Duration rhs) const { return lhs == rhs; } template <typename T> std::enable_if_t<std::negation_v<std::is_same<absl::Duration, T>>, bool> operator()(absl::Duration, const T&) const { return false; } }; struct TimestampEqualer { bool operator()(absl::Time lhs, absl::Time rhs) const { return lhs == rhs; } template <typename T> std::enable_if_t<std::negation_v<std::is_same<absl::Time, T>>, bool> operator()(absl::Time, const T&) const { return false; } }; struct ListValueEqualer { bool operator()(EquatableListValue lhs, EquatableListValue rhs) const { return JsonListEquals(lhs, rhs); } template <typename T> std::enable_if_t<std::negation_v<std::is_same<EquatableListValue, T>>, bool> operator()(EquatableListValue, const T&) const { return false; } }; struct StructEqualer { bool operator()(EquatableStruct lhs, EquatableStruct rhs) const { return JsonMapEquals(lhs, rhs); } template <typename T> std::enable_if_t<std::negation_v<std::is_same<EquatableStruct, T>>, bool> operator()(EquatableStruct, const T&) const { return false; } }; struct AnyEqualer { bool operator()(EquatableAny lhs, EquatableAny rhs) const { auto lhs_reflection = well_known_types::GetAnyReflectionOrDie(lhs.get().GetDescriptor()); std::string lhs_type_url_scratch; std::string lhs_value_scratch; auto rhs_reflection = well_known_types::GetAnyReflectionOrDie(rhs.get().GetDescriptor()); std::string rhs_type_url_scratch; std::string rhs_value_scratch; return lhs_reflection.GetTypeUrl(lhs.get(), lhs_type_url_scratch) == rhs_reflection.GetTypeUrl(rhs.get(), rhs_type_url_scratch) && lhs_reflection.GetValue(lhs.get(), lhs_value_scratch) == rhs_reflection.GetValue(rhs.get(), rhs_value_scratch); } template <typename T> std::enable_if_t<std::negation_v<std::is_same<EquatableAny, T>>, bool> operator()(EquatableAny, const T&) const { return false; } }; struct MessageEqualer { bool operator()(EquatableMessage lhs, EquatableMessage rhs) const { return lhs.get().GetDescriptor() == rhs.get().GetDescriptor() && MessageDifferencer::Equals(lhs.get(), rhs.get()); } template <typename T> std::enable_if_t<std::negation_v<std::is_same<EquatableMessage, T>>, bool> operator()(EquatableMessage, const T&) const { return false; } }; struct EquatableValueReflection final { well_known_types::DoubleValueReflection double_value_reflection; well_known_types::FloatValueReflection float_value_reflection; well_known_types::Int64ValueReflection int64_value_reflection; well_known_types::UInt64ValueReflection uint64_value_reflection; well_known_types::Int32ValueReflection int32_value_reflection; well_known_types::UInt32ValueReflection uint32_value_reflection; well_known_types::StringValueReflection string_value_reflection; well_known_types::BytesValueReflection bytes_value_reflection; well_known_types::BoolValueReflection bool_value_reflection; well_known_types::AnyReflection any_reflection; well_known_types::DurationReflection duration_reflection; well_known_types::TimestampReflection timestamp_reflection; well_known_types::ValueReflection value_reflection; well_known_types::ListValueReflection list_value_reflection; well_known_types::StructReflection struct_reflection; }; absl::StatusOr<EquatableValue> AsEquatableValue( EquatableValueReflection& reflection, const Message& message ABSL_ATTRIBUTE_LIFETIME_BOUND, absl::Nonnull<const Descriptor*> descriptor, Descriptor::WellKnownType well_known_type, std::string& scratch ABSL_ATTRIBUTE_LIFETIME_BOUND) { switch (well_known_type) { case Descriptor::WELLKNOWNTYPE_DOUBLEVALUE: CEL_RETURN_IF_ERROR( reflection.double_value_reflection.Initialize(descriptor)); return reflection.double_value_reflection.GetValue(message); case Descriptor::WELLKNOWNTYPE_FLOATVALUE: CEL_RETURN_IF_ERROR( reflection.float_value_reflection.Initialize(descriptor)); return static_cast<double>( reflection.float_value_reflection.GetValue(message)); case Descriptor::WELLKNOWNTYPE_INT64VALUE: CEL_RETURN_IF_ERROR( reflection.int64_value_reflection.Initialize(descriptor)); return reflection.int64_value_reflection.GetValue(message); case Descriptor::WELLKNOWNTYPE_UINT64VALUE: CEL_RETURN_IF_ERROR( reflection.uint64_value_reflection.Initialize(descriptor)); return reflection.uint64_value_reflection.GetValue(message); case Descriptor::WELLKNOWNTYPE_INT32VALUE: CEL_RETURN_IF_ERROR( reflection.int32_value_reflection.Initialize(descriptor)); return static_cast<int64_t>( reflection.int32_value_reflection.GetValue(message)); case Descriptor::WELLKNOWNTYPE_UINT32VALUE: CEL_RETURN_IF_ERROR( reflection.uint32_value_reflection.Initialize(descriptor)); return static_cast<uint64_t>( reflection.uint32_value_reflection.GetValue(message)); case Descriptor::WELLKNOWNTYPE_STRINGVALUE: CEL_RETURN_IF_ERROR( reflection.string_value_reflection.Initialize(descriptor)); return reflection.string_value_reflection.GetValue(message, scratch); case Descriptor::WELLKNOWNTYPE_BYTESVALUE: CEL_RETURN_IF_ERROR( reflection.bytes_value_reflection.Initialize(descriptor)); return reflection.bytes_value_reflection.GetValue(message, scratch); case Descriptor::WELLKNOWNTYPE_BOOLVALUE: CEL_RETURN_IF_ERROR( reflection.bool_value_reflection.Initialize(descriptor)); return reflection.bool_value_reflection.GetValue(message); case Descriptor::WELLKNOWNTYPE_VALUE: { CEL_RETURN_IF_ERROR(reflection.value_reflection.Initialize(descriptor)); const auto kind_case = reflection.value_reflection.GetKindCase(message); switch (kind_case) { case google::protobuf::Value::KIND_NOT_SET: ABSL_FALLTHROUGH_INTENDED; case google::protobuf::Value::kNullValue: return nullptr; case google::protobuf::Value::kBoolValue: return reflection.value_reflection.GetBoolValue(message); case google::protobuf::Value::kNumberValue: return reflection.value_reflection.GetNumberValue(message); case google::protobuf::Value::kStringValue: return reflection.value_reflection.GetStringValue(message, scratch); case google::protobuf::Value::kListValue: return EquatableListValue( reflection.value_reflection.GetListValue(message)); case google::protobuf::Value::kStructValue: return EquatableStruct( reflection.value_reflection.GetStructValue(message)); default: return absl::InternalError( absl::StrCat("unexpected value kind case: ", kind_case)); } } case Descriptor::WELLKNOWNTYPE_LISTVALUE: return EquatableListValue(message); case Descriptor::WELLKNOWNTYPE_STRUCT: return EquatableStruct(message); case Descriptor::WELLKNOWNTYPE_DURATION: CEL_RETURN_IF_ERROR( reflection.duration_reflection.Initialize(descriptor)); return reflection.duration_reflection.ToAbslDuration(message); case Descriptor::WELLKNOWNTYPE_TIMESTAMP: CEL_RETURN_IF_ERROR( reflection.timestamp_reflection.Initialize(descriptor)); return reflection.timestamp_reflection.ToAbslTime(message); case Descriptor::WELLKNOWNTYPE_ANY: return EquatableAny(message); default: return EquatableMessage(message); } } absl::StatusOr<EquatableValue> AsEquatableValue( EquatableValueReflection& reflection, const Message& message ABSL_ATTRIBUTE_LIFETIME_BOUND, absl::Nonnull<const Descriptor*> descriptor, std::string& scratch ABSL_ATTRIBUTE_LIFETIME_BOUND) { return AsEquatableValue(reflection, message, descriptor, descriptor->well_known_type(), scratch); } absl::StatusOr<EquatableValue> AsEquatableValue( EquatableValueReflection& reflection, const Message& message ABSL_ATTRIBUTE_LIFETIME_BOUND, absl::Nonnull<const FieldDescriptor*> field, std::string& scratch ABSL_ATTRIBUTE_LIFETIME_BOUND) { ABSL_DCHECK(!field->is_repeated() && !field->is_map()); switch (field->cpp_type()) { case FieldDescriptor::CPPTYPE_INT32: return static_cast<int64_t>( message.GetReflection()->GetInt32(message, field)); case FieldDescriptor::CPPTYPE_INT64: return message.GetReflection()->GetInt64(message, field); case FieldDescriptor::CPPTYPE_UINT32: return static_cast<uint64_t>( message.GetReflection()->GetUInt32(message, field)); case FieldDescriptor::CPPTYPE_UINT64: return message.GetReflection()->GetUInt64(message, field); case FieldDescriptor::CPPTYPE_DOUBLE: return message.GetReflection()->GetDouble(message, field); case FieldDescriptor::CPPTYPE_FLOAT: return static_cast<double>( message.GetReflection()->GetFloat(message, field)); case FieldDescriptor::CPPTYPE_BOOL: return message.GetReflection()->GetBool(message, field); case FieldDescriptor::CPPTYPE_ENUM: if (field->enum_type()->full_name() == "google.protobuf.NullValue") { return nullptr; } return static_cast<int64_t>( message.GetReflection()->GetEnumValue(message, field)); case FieldDescriptor::CPPTYPE_STRING: if (field->type() == FieldDescriptor::TYPE_BYTES) { return well_known_types::GetBytesField(message, field, scratch); } return well_known_types::GetStringField(message, field, scratch); case FieldDescriptor::CPPTYPE_MESSAGE: return AsEquatableValue( reflection, message.GetReflection()->GetMessage(message, field), field->message_type(), scratch); default: return absl::InternalError( absl::StrCat("unexpected field type: ", field->cpp_type_name())); } } bool IsAny(const Message& message) { return message.GetDescriptor()->well_known_type() == Descriptor::WELLKNOWNTYPE_ANY; } bool IsAnyField(absl::Nonnull<const FieldDescriptor*> field) { return field->type() == FieldDescriptor::TYPE_MESSAGE && field->message_type()->well_known_type() == Descriptor::WELLKNOWNTYPE_ANY; } absl::StatusOr<EquatableValue> MapValueAsEquatableValue( absl::Nonnull<google::protobuf::Arena*> arena, absl::Nonnull<const DescriptorPool*> pool, absl::Nonnull<MessageFactory*> factory, EquatableValueReflection& reflection, const google::protobuf::MapValueConstRef& value, absl::Nonnull<const FieldDescriptor*> field, std::string& scratch, Unique<Message>& unpacked) { if (IsAnyField(field)) { CEL_ASSIGN_OR_RETURN(unpacked, well_known_types::UnpackAnyIfResolveable( arena, reflection.any_reflection, value.GetMessageValue(), pool, factory)); if (unpacked) { return AsEquatableValue(reflection, *unpacked, unpacked->GetDescriptor(), scratch); } return AsEquatableValue(reflection, value.GetMessageValue(), value.GetMessageValue().GetDescriptor(), scratch); } switch (field->cpp_type()) { case FieldDescriptor::CPPTYPE_INT32: return static_cast<int64_t>(value.GetInt32Value()); case FieldDescriptor::CPPTYPE_INT64: return value.GetInt64Value(); case FieldDescriptor::CPPTYPE_UINT32: return static_cast<uint64_t>(value.GetUInt32Value()); case FieldDescriptor::CPPTYPE_UINT64: return value.GetUInt64Value(); case FieldDescriptor::CPPTYPE_DOUBLE: return value.GetDoubleValue(); case FieldDescriptor::CPPTYPE_FLOAT: return static_cast<double>(value.GetFloatValue()); case FieldDescriptor::CPPTYPE_BOOL: return value.GetBoolValue(); case FieldDescriptor::CPPTYPE_ENUM: if (field->enum_type()->full_name() == "google.protobuf.NullValue") { return nullptr; } return static_cast<int64_t>(value.GetEnumValue()); case FieldDescriptor::CPPTYPE_STRING: if (field->type() == FieldDescriptor::TYPE_BYTES) { return well_known_types::BytesValue( absl::string_view(value.GetStringValue())); } return well_known_types::StringValue( absl::string_view(value.GetStringValue())); case FieldDescriptor::CPPTYPE_MESSAGE: { const auto& message = value.GetMessageValue(); return AsEquatableValue(reflection, message, message.GetDescriptor(), scratch); } default: return absl::InternalError( absl::StrCat("unexpected field type: ", field->cpp_type_name())); } } absl::StatusOr<EquatableValue> RepeatedFieldAsEquatableValue( absl::Nonnull<google::protobuf::Arena*> arena, absl::Nonnull<const DescriptorPool*> pool, absl::Nonnull<MessageFactory*> factory, EquatableValueReflection& reflection, const Message& message, absl::Nonnull<const FieldDescriptor*> field, int index, std::string& scratch, Unique<Message>& unpacked) { if (IsAnyField(field)) { const auto& field_value = message.GetReflection()->GetRepeatedMessage(message, field, index); CEL_ASSIGN_OR_RETURN(unpacked, well_known_types::UnpackAnyIfResolveable( arena, reflection.any_reflection, field_value, pool, factory)); if (unpacked) { return AsEquatableValue(reflection, *unpacked, unpacked->GetDescriptor(), scratch); } return AsEquatableValue(reflection, field_value, field_value.GetDescriptor(), scratch); } switch (field->cpp_type()) { case FieldDescriptor::CPPTYPE_INT32: return static_cast<int64_t>( message.GetReflection()->GetRepeatedInt32(message, field, index)); case FieldDescriptor::CPPTYPE_INT64: return message.GetReflection()->GetRepeatedInt64(message, field, index); case FieldDescriptor::CPPTYPE_UINT32: return static_cast<uint64_t>( message.GetReflection()->GetRepeatedUInt32(message, field, index)); case FieldDescriptor::CPPTYPE_UINT64: return message.GetReflection()->GetRepeatedUInt64(message, field, index); case FieldDescriptor::CPPTYPE_DOUBLE: return message.GetReflection()->GetRepeatedDouble(message, field, index); case FieldDescriptor::CPPTYPE_FLOAT: return static_cast<double>( message.GetReflection()->GetRepeatedFloat(message, field, index)); case FieldDescriptor::CPPTYPE_BOOL: return message.GetReflection()->GetRepeatedBool(message, field, index); case FieldDescriptor::CPPTYPE_ENUM: if (field->enum_type()->full_name() == "google.protobuf.NullValue") { return nullptr; } return static_cast<int64_t>( message.GetReflection()->GetRepeatedEnumValue(message, field, index)); case FieldDescriptor::CPPTYPE_STRING: if (field->type() == FieldDescriptor::TYPE_BYTES) { return well_known_types::GetRepeatedBytesField(message, field, index, scratch); } return well_known_types::GetRepeatedStringField(message, field, index, scratch); case FieldDescriptor::CPPTYPE_MESSAGE: { const auto& submessage = message.GetReflection()->GetRepeatedMessage(message, field, index); return AsEquatableValue(reflection, submessage, submessage.GetDescriptor(), scratch); } default: return absl::InternalError( absl::StrCat("unexpected field type: ", field->cpp_type_name())); } } bool EquatableValueEquals(const EquatableValue& lhs, const EquatableValue& rhs) { return absl::visit( absl::Overload(NullValueEqualer{}, BoolValueEqualer{}, BytesValueEqualer{}, IntValueEqualer{}, UintValueEqualer{}, DoubleValueEqualer{}, StringValueEqualer{}, DurationEqualer{}, TimestampEqualer{}, ListValueEqualer{}, StructEqualer{}, AnyEqualer{}, MessageEqualer{}), lhs, rhs); } bool CoalesceMapKey(const google::protobuf::MapKey& src, FieldDescriptor::CppType dest_type, absl::Nonnull<google::protobuf::MapKey*> dest) { switch (src.type()) { case FieldDescriptor::CPPTYPE_BOOL: if (dest_type != FieldDescriptor::CPPTYPE_BOOL) { return false; } dest->SetBoolValue(src.GetBoolValue()); return true; case FieldDescriptor::CPPTYPE_INT32: { const auto src_value = src.GetInt32Value(); switch (dest_type) { case FieldDescriptor::CPPTYPE_INT32: dest->SetInt32Value(src_value); return true; case FieldDescriptor::CPPTYPE_INT64: dest->SetInt64Value(src_value); return true; case FieldDescriptor::CPPTYPE_UINT32: if (src_value < 0) { return false; } dest->SetUInt32Value(static_cast<uint32_t>(src_value)); return true; case FieldDescriptor::CPPTYPE_UINT64: if (src_value < 0) { return false; } dest->SetUInt64Value(static_cast<uint64_t>(src_value)); return true; default: return false; } } case FieldDescriptor::CPPTYPE_INT64: { const auto src_value = src.GetInt64Value(); switch (dest_type) { case FieldDescriptor::CPPTYPE_INT32: if (src_value < std::numeric_limits<int32_t>::min() || src_value > std::numeric_limits<int32_t>::max()) { return false; } dest->SetInt32Value(static_cast<int32_t>(src_value)); return true; case FieldDescriptor::CPPTYPE_INT64: dest->SetInt64Value(src_value); return true; case FieldDescriptor::CPPTYPE_UINT32: if (src_value < 0 || src_value > std::numeric_limits<uint32_t>::max()) { return false; } dest->SetUInt32Value(static_cast<uint32_t>(src_value)); return true; case FieldDescriptor::CPPTYPE_UINT64: if (src_value < 0) { return false; } dest->SetUInt64Value(static_cast<uint64_t>(src_value)); return true; default: return false; } } case FieldDescriptor::CPPTYPE_UINT32: { const auto src_value = src.GetUInt32Value(); switch (dest_type) { case FieldDescriptor::CPPTYPE_INT32: if (src_value > std::numeric_limits<int32_t>::max()) { return false; } dest->SetInt32Value(static_cast<int32_t>(src_value)); return true; case FieldDescriptor::CPPTYPE_INT64: dest->SetInt64Value(static_cast<int64_t>(src_value)); return true; case FieldDescriptor::CPPTYPE_UINT32: dest->SetUInt32Value(src_value); return true; case FieldDescriptor::CPPTYPE_UINT64: dest->SetUInt64Value(static_cast<uint64_t>(src_value)); return true; default: return false; } } case FieldDescriptor::CPPTYPE_UINT64: { const auto src_value = src.GetUInt64Value(); switch (dest_type) { case FieldDescriptor::CPPTYPE_INT32: if (src_value > std::numeric_limits<int32_t>::max()) { return false; } dest->SetInt32Value(static_cast<int32_t>(src_value)); return true; case FieldDescriptor::CPPTYPE_INT64: if (src_value > std::numeric_limits<int64_t>::max()) { return false; } dest->SetInt64Value(static_cast<int64_t>(src_value)); return true; case FieldDescriptor::CPPTYPE_UINT32: if (src_value > std::numeric_limits<uint32_t>::max()) { return false; } dest->SetUInt32Value(src_value); return true; case FieldDescriptor::CPPTYPE_UINT64: dest->SetUInt64Value(src_value); return true; default: return false; } } case FieldDescriptor::CPPTYPE_STRING: if (dest_type != FieldDescriptor::CPPTYPE_STRING) { return false; } dest->SetStringValue(src.GetStringValue()); return true; default: ABSL_UNREACHABLE(); } } enum class EquatableCategory { kNone = 0, kNullLike = 1 << 0, kBoolLike = 1 << 1, kNumericLike = 1 << 2, kBytesLike = 1 << 3, kStringLike = 1 << 4, kList = 1 << 5, kMap = 1 << 6, kMessage = 1 << 7, kDuration = 1 << 8, kTimestamp = 1 << 9, kAny = kNullLike | kBoolLike | kNumericLike | kBytesLike | kStringLike | kList | kMap | kMessage | kDuration | kTimestamp, kValue = kNullLike | kBoolLike | kNumericLike | kStringLike | kList | kMap, }; constexpr EquatableCategory operator&(EquatableCategory lhs, EquatableCategory rhs) { return static_cast<EquatableCategory>( static_cast<std::underlying_type_t<EquatableCategory>>(lhs) & static_cast<std::underlying_type_t<EquatableCategory>>(rhs)); } constexpr bool operator==(EquatableCategory lhs, EquatableCategory rhs) { return static_cast<std::underlying_type_t<EquatableCategory>>(lhs) == static_cast<std::underlying_type_t<EquatableCategory>>(rhs); } EquatableCategory GetEquatableCategory( absl::Nonnull<const Descriptor*> descriptor) { switch (descriptor->well_known_type()) { case Descriptor::WELLKNOWNTYPE_BOOLVALUE: return EquatableCategory::kBoolLike; case Descriptor::WELLKNOWNTYPE_FLOATVALUE: ABSL_FALLTHROUGH_INTENDED; case Descriptor::WELLKNOWNTYPE_DOUBLEVALUE: ABSL_FALLTHROUGH_INTENDED; case Descriptor::WELLKNOWNTYPE_INT32VALUE: ABSL_FALLTHROUGH_INTENDED; case Descriptor::WELLKNOWNTYPE_UINT32VALUE: ABSL_FALLTHROUGH_INTENDED; case Descriptor::WELLKNOWNTYPE_INT64VALUE: ABSL_FALLTHROUGH_INTENDED; case Descriptor::WELLKNOWNTYPE_UINT64VALUE: return EquatableCategory::kNumericLike; case Descriptor::WELLKNOWNTYPE_BYTESVALUE: return EquatableCategory::kBytesLike; case Descriptor::WELLKNOWNTYPE_STRINGVALUE: return EquatableCategory::kStringLike; case Descriptor::WELLKNOWNTYPE_VALUE: return EquatableCategory::kValue; case Descriptor::WELLKNOWNTYPE_LISTVALUE: return EquatableCategory::kList; case Descriptor::WELLKNOWNTYPE_STRUCT: return EquatableCategory::kMap; case Descriptor::WELLKNOWNTYPE_ANY: return EquatableCategory::kAny; case Descriptor::WELLKNOWNTYPE_DURATION: return EquatableCategory::kDuration; case Descriptor::WELLKNOWNTYPE_TIMESTAMP: return EquatableCategory::kTimestamp; default: return EquatableCategory::kAny; } } EquatableCategory GetEquatableFieldCategory( absl::Nonnull<const FieldDescriptor*> field) { switch (field->cpp_type()) { case FieldDescriptor::CPPTYPE_ENUM: return field->enum_type()->full_name() == "google.protobuf.NullValue" ? EquatableCategory::kNullLike : EquatableCategory::kNumericLike; case FieldDescriptor::CPPTYPE_BOOL: return EquatableCategory::kBoolLike; case FieldDescriptor::CPPTYPE_FLOAT: ABSL_FALLTHROUGH_INTENDED; case FieldDescriptor::CPPTYPE_DOUBLE: ABSL_FALLTHROUGH_INTENDED; case FieldDescriptor::CPPTYPE_INT32: ABSL_FALLTHROUGH_INTENDED; case FieldDescriptor::CPPTYPE_UINT32: ABSL_FALLTHROUGH_INTENDED; case FieldDescriptor::CPPTYPE_INT64: ABSL_FALLTHROUGH_INTENDED; case FieldDescriptor::CPPTYPE_UINT64: return EquatableCategory::kNumericLike; case FieldDescriptor::CPPTYPE_STRING: return field->type() == FieldDescriptor::TYPE_BYTES ? EquatableCategory::kBytesLike : EquatableCategory::kStringLike; case FieldDescriptor::CPPTYPE_MESSAGE: return GetEquatableCategory(field->message_type()); default: return EquatableCategory::kAny; } } class MessageEqualsState final { public: MessageEqualsState(absl::Nonnull<const DescriptorPool*> pool, absl::Nonnull<MessageFactory*> factory) : pool_(pool), factory_(factory) {} absl::StatusOr<bool> Equals(const Message& lhs, const Message& rhs) { const auto* lhs_descriptor = lhs.GetDescriptor(); const auto* rhs_descriptor = rhs.GetDescriptor(); auto lhs_well_known_type = lhs_descriptor->well_known_type(); auto rhs_well_known_type = rhs_descriptor->well_known_type(); absl::Nonnull<const Message*> lhs_ptr = &lhs; absl::Nonnull<const Message*> rhs_ptr = &rhs; Unique<Message> lhs_unpacked; Unique<Message> rhs_unpacked; if (lhs_well_known_type == Descriptor::WELLKNOWNTYPE_ANY) { CEL_ASSIGN_OR_RETURN( lhs_unpacked, well_known_types::UnpackAnyIfResolveable( &arena_, lhs_reflection_.any_reflection, lhs, pool_, factory_)); if (lhs_unpacked) { lhs_ptr = cel::to_address(lhs_unpacked); lhs_descriptor = lhs_ptr->GetDescriptor(); lhs_well_known_type = lhs_descriptor->well_known_type(); } } if (rhs_well_known_type == Descriptor::WELLKNOWNTYPE_ANY) { CEL_ASSIGN_OR_RETURN( rhs_unpacked, well_known_types::UnpackAnyIfResolveable( &arena_, rhs_reflection_.any_reflection, rhs, pool_, factory_)); if (rhs_unpacked) { rhs_ptr = cel::to_address(rhs_unpacked); rhs_descriptor = rhs_ptr->GetDescriptor(); rhs_well_known_type = rhs_descriptor->well_known_type(); } } CEL_ASSIGN_OR_RETURN( auto lhs_value, AsEquatableValue(lhs_reflection_, *lhs_ptr, lhs_descriptor, lhs_well_known_type, lhs_scratch_)); CEL_ASSIGN_OR_RETURN( auto rhs_value, AsEquatableValue(rhs_reflection_, *rhs_ptr, rhs_descriptor, rhs_well_known_type, rhs_scratch_)); return EquatableValueEquals(lhs_value, rhs_value); } absl::StatusOr<bool> MapFieldEquals( const Message& lhs, absl::Nonnull<const FieldDescriptor*> lhs_field, const Message& rhs, absl::Nonnull<const FieldDescriptor*> rhs_field) { ABSL_DCHECK(lhs_field->is_map()); ABSL_DCHECK_EQ(lhs_field->containing_type(), lhs.GetDescriptor()); ABSL_DCHECK(rhs_field->is_map()); ABSL_DCHECK_EQ(rhs_field->containing_type(), rhs.GetDescriptor()); const auto* lhs_entry = lhs_field->message_type(); const auto* lhs_entry_key_field = lhs_entry->map_key(); const auto* lhs_entry_value_field = lhs_entry->map_value(); const auto* rhs_entry = rhs_field->message_type(); const auto* rhs_entry_key_field = rhs_entry->map_key(); const auto* rhs_entry_value_field = rhs_entry->map_value(); if (lhs_field != rhs_field && ((GetEquatableFieldCategory(lhs_entry_key_field) & GetEquatableFieldCategory(rhs_entry_key_field)) == EquatableCategory::kNone || (GetEquatableFieldCategory(lhs_entry_value_field) & GetEquatableFieldCategory(rhs_entry_value_field)) == EquatableCategory::kNone)) { return false; } const auto* lhs_reflection = lhs.GetReflection(); const auto* rhs_reflection = rhs.GetReflection(); if (MapSize(*lhs_reflection, lhs, *lhs_field) != MapSize(*rhs_reflection, rhs, *rhs_field)) { return false; } auto lhs_begin = MapBegin(*lhs_reflection, lhs, *lhs_field); const auto lhs_end = MapEnd(*lhs_reflection, lhs, *lhs_field); Unique<Message> lhs_unpacked; EquatableValue lhs_value; Unique<Message> rhs_unpacked; EquatableValue rhs_value; google::protobuf::MapKey rhs_map_key; google::protobuf::MapValueConstRef rhs_map_value; for (; lhs_begin != lhs_end; ++lhs_begin) { if (!CoalesceMapKey(lhs_begin.GetKey(), rhs_entry_key_field->cpp_type(), &rhs_map_key)) { return false; } if (!LookupMapValue(*rhs_reflection, rhs, *rhs_field, rhs_map_key, &rhs_map_value)) { return false; } CEL_ASSIGN_OR_RETURN(lhs_value, MapValueAsEquatableValue( &arena_, pool_, factory_, lhs_reflection_, lhs_begin.GetValueRef(), lhs_entry_value_field, lhs_scratch_, lhs_unpacked)); CEL_ASSIGN_OR_RETURN( rhs_value, MapValueAsEquatableValue(&arena_, pool_, factory_, rhs_reflection_, rhs_map_value, rhs_entry_value_field, rhs_scratch_, rhs_unpacked)); if (!EquatableValueEquals(lhs_value, rhs_value)) { return false; } } return true; } absl::StatusOr<bool> RepeatedFieldEquals( const Message& lhs, absl::Nonnull<const FieldDescriptor*> lhs_field, const Message& rhs, absl::Nonnull<const FieldDescriptor*> rhs_field) { ABSL_DCHECK(lhs_field->is_repeated() && !lhs_field->is_map()); ABSL_DCHECK_EQ(lhs_field->containing_type(), lhs.GetDescriptor()); ABSL_DCHECK(rhs_field->is_repeated() && !rhs_field->is_map()); ABSL_DCHECK_EQ(rhs_field->containing_type(), rhs.GetDescriptor()); if (lhs_field != rhs_field && (GetEquatableFieldCategory(lhs_field) & GetEquatableFieldCategory(rhs_field)) == EquatableCategory::kNone) { return false; } const auto* lhs_reflection = lhs.GetReflection(); const auto* rhs_reflection = rhs.GetReflection(); const auto size = lhs_reflection->FieldSize(lhs, lhs_field); if (size != rhs_reflection->FieldSize(rhs, rhs_field)) { return false; } Unique<Message> lhs_unpacked; EquatableValue lhs_value; Unique<Message> rhs_unpacked; EquatableValue rhs_value; for (int i = 0; i < size; ++i) { CEL_ASSIGN_OR_RETURN(lhs_value, RepeatedFieldAsEquatableValue( &arena_, pool_, factory_, lhs_reflection_, lhs, lhs_field, i, lhs_scratch_, lhs_unpacked)); CEL_ASSIGN_OR_RETURN(rhs_value, RepeatedFieldAsEquatableValue( &arena_, pool_, factory_, rhs_reflection_, rhs, rhs_field, i, rhs_scratch_, rhs_unpacked)); if (!EquatableValueEquals(lhs_value, rhs_value)) { return false; } } return true; } absl::StatusOr<bool> SingularFieldEquals( const Message& lhs, absl::Nullable<const FieldDescriptor*> lhs_field, const Message& rhs, absl::Nullable<const FieldDescriptor*> rhs_field) { ABSL_DCHECK(lhs_field == nullptr || (!lhs_field->is_repeated() && !lhs_field->is_map())); ABSL_DCHECK(lhs_field == nullptr || lhs_field->containing_type() == lhs.GetDescriptor()); ABSL_DCHECK(rhs_field == nullptr || (!rhs_field->is_repeated() && !rhs_field->is_map())); ABSL_DCHECK(rhs_field == nullptr || rhs_field->containing_type() == rhs.GetDescriptor()); if (lhs_field != rhs_field && ((lhs_field != nullptr ? GetEquatableFieldCategory(lhs_field) : GetEquatableCategory(lhs.GetDescriptor())) & (rhs_field != nullptr ? GetEquatableFieldCategory(rhs_field) : GetEquatableCategory(rhs.GetDescriptor()))) == EquatableCategory::kNone) { return false; } absl::Nonnull<const Message*> lhs_ptr = &lhs; absl::Nonnull<const Message*> rhs_ptr = &rhs; Unique<Message> lhs_unpacked; Unique<Message> rhs_unpacked; if (lhs_field != nullptr && IsAnyField(lhs_field)) { CEL_ASSIGN_OR_RETURN(lhs_unpacked, well_known_types::UnpackAnyIfResolveable( &arena_, lhs_reflection_.any_reflection, lhs.GetReflection()->GetMessage(lhs, lhs_field), pool_, factory_)); if (lhs_unpacked) { lhs_ptr = cel::to_address(lhs_unpacked); lhs_field = nullptr; } } else if (lhs_field == nullptr && IsAny(lhs)) { CEL_ASSIGN_OR_RETURN( lhs_unpacked, well_known_types::UnpackAnyIfResolveable( &arena_, lhs_reflection_.any_reflection, lhs, pool_, factory_)); if (lhs_unpacked) { lhs_ptr = cel::to_address(lhs_unpacked); } } if (rhs_field != nullptr && IsAnyField(rhs_field)) { CEL_ASSIGN_OR_RETURN(rhs_unpacked, well_known_types::UnpackAnyIfResolveable( &arena_, rhs_reflection_.any_reflection, rhs.GetReflection()->GetMessage(rhs, rhs_field), pool_, factory_)); if (rhs_unpacked) { rhs_ptr = cel::to_address(rhs_unpacked); rhs_field = nullptr; } } else if (rhs_field == nullptr && IsAny(rhs)) { CEL_ASSIGN_OR_RETURN( rhs_unpacked, well_known_types::UnpackAnyIfResolveable( &arena_, rhs_reflection_.any_reflection, rhs, pool_, factory_)); if (rhs_unpacked) { rhs_ptr = cel::to_address(rhs_unpacked); } } EquatableValue lhs_value; if (lhs_field != nullptr) { CEL_ASSIGN_OR_RETURN( lhs_value, AsEquatableValue(lhs_reflection_, *lhs_ptr, lhs_field, lhs_scratch_)); } else { CEL_ASSIGN_OR_RETURN( lhs_value, AsEquatableValue(lhs_reflection_, *lhs_ptr, lhs_ptr->GetDescriptor(), lhs_scratch_)); } EquatableValue rhs_value; if (rhs_field != nullptr) { CEL_ASSIGN_OR_RETURN( rhs_value, AsEquatableValue(rhs_reflection_, *rhs_ptr, rhs_field, rhs_scratch_)); } else { CEL_ASSIGN_OR_RETURN( rhs_value, AsEquatableValue(rhs_reflection_, *rhs_ptr, rhs_ptr->GetDescriptor(), rhs_scratch_)); } return EquatableValueEquals(lhs_value, rhs_value); } absl::StatusOr<bool> FieldEquals( const Message& lhs, absl::Nullable<const FieldDescriptor*> lhs_field, const Message& rhs, absl::Nullable<const FieldDescriptor*> rhs_field) { ABSL_DCHECK(lhs_field != nullptr || rhs_field != nullptr); if (lhs_field != nullptr && lhs_field->is_map()) { if (rhs_field != nullptr && rhs_field->is_map()) { return MapFieldEquals(lhs, lhs_field, rhs, rhs_field); } if (rhs_field != nullptr && (rhs_field->is_repeated() || rhs_field->type() != FieldDescriptor::TYPE_MESSAGE)) { return false; } absl::Nullable<const Message*> rhs_packed = nullptr; Unique<Message> rhs_unpacked; if (rhs_field != nullptr && IsAnyField(rhs_field)) { rhs_packed = &rhs.GetReflection()->GetMessage(rhs, rhs_field); } else if (rhs_field == nullptr && IsAny(rhs)) { rhs_packed = &rhs; } if (rhs_packed != nullptr) { CEL_RETURN_IF_ERROR(rhs_reflection_.any_reflection.Initialize( rhs_packed->GetDescriptor())); auto rhs_type_url = rhs_reflection_.any_reflection.GetTypeUrl( *rhs_packed, rhs_scratch_); if (!rhs_type_url.ConsumePrefix("type.googleapis.com/") && !rhs_type_url.ConsumePrefix("type.googleprod.com/")) { return false; } if (rhs_type_url != "google.protobuf.Value" && rhs_type_url != "google.protobuf.Struct" && rhs_type_url != "google.protobuf.Any") { return false; } CEL_ASSIGN_OR_RETURN(rhs_unpacked, well_known_types::UnpackAnyIfResolveable( &arena_, rhs_reflection_.any_reflection, *rhs_packed, pool_, factory_)); if (rhs_unpacked) { rhs_field = nullptr; } } absl::Nonnull<const Message*> rhs_message = rhs_field != nullptr ? &rhs.GetReflection()->GetMessage(rhs, rhs_field) : rhs_unpacked != nullptr ? cel::to_address(rhs_unpacked) : &rhs; const auto* rhs_descriptor = rhs_message->GetDescriptor(); const auto rhs_well_known_type = rhs_descriptor->well_known_type(); switch (rhs_well_known_type) { case Descriptor::WELLKNOWNTYPE_VALUE: { CEL_RETURN_IF_ERROR( rhs_reflection_.value_reflection.Initialize(rhs_descriptor)); if (rhs_reflection_.value_reflection.GetKindCase(*rhs_message) != google::protobuf::Value::kStructValue) { return false; } CEL_RETURN_IF_ERROR(rhs_reflection_.struct_reflection.Initialize( rhs_reflection_.value_reflection.GetStructDescriptor())); return MapFieldEquals( lhs, lhs_field, rhs_reflection_.value_reflection.GetStructValue(*rhs_message), rhs_reflection_.struct_reflection.GetFieldsDescriptor()); } case Descriptor::WELLKNOWNTYPE_STRUCT: { CEL_RETURN_IF_ERROR( rhs_reflection_.struct_reflection.Initialize(rhs_descriptor)); return MapFieldEquals( lhs, lhs_field, *rhs_message, rhs_reflection_.struct_reflection.GetFieldsDescriptor()); } default: return false; } ABSL_UNREACHABLE(); } if (rhs_field != nullptr && rhs_field->is_map()) { ABSL_DCHECK(lhs_field == nullptr || !lhs_field->is_map()); if (lhs_field != nullptr && (lhs_field->is_repeated() || lhs_field->type() != FieldDescriptor::TYPE_MESSAGE)) { return false; } absl::Nullable<const Message*> lhs_packed = nullptr; Unique<Message> lhs_unpacked; if (lhs_field != nullptr && IsAnyField(lhs_field)) { lhs_packed = &lhs.GetReflection()->GetMessage(lhs, lhs_field); } else if (lhs_field == nullptr && IsAny(lhs)) { lhs_packed = &lhs; } if (lhs_packed != nullptr) { CEL_RETURN_IF_ERROR(lhs_reflection_.any_reflection.Initialize( lhs_packed->GetDescriptor())); auto lhs_type_url = lhs_reflection_.any_reflection.GetTypeUrl( *lhs_packed, lhs_scratch_); if (!lhs_type_url.ConsumePrefix("type.googleapis.com/") && !lhs_type_url.ConsumePrefix("type.googleprod.com/")) { return false; } if (lhs_type_url != "google.protobuf.Value" && lhs_type_url != "google.protobuf.Struct" && lhs_type_url != "google.protobuf.Any") { return false; } CEL_ASSIGN_OR_RETURN(lhs_unpacked, well_known_types::UnpackAnyIfResolveable( &arena_, lhs_reflection_.any_reflection, *lhs_packed, pool_, factory_)); if (lhs_unpacked) { lhs_field = nullptr; } } absl::Nonnull<const Message*> lhs_message = lhs_field != nullptr ? &lhs.GetReflection()->GetMessage(lhs, lhs_field) : lhs_unpacked != nullptr ? cel::to_address(lhs_unpacked) : &lhs; const auto* lhs_descriptor = lhs_message->GetDescriptor(); const auto lhs_well_known_type = lhs_descriptor->well_known_type(); switch (lhs_well_known_type) { case Descriptor::WELLKNOWNTYPE_VALUE: { CEL_RETURN_IF_ERROR( lhs_reflection_.value_reflection.Initialize(lhs_descriptor)); if (lhs_reflection_.value_reflection.GetKindCase(*lhs_message) != google::protobuf::Value::kStructValue) { return false; } CEL_RETURN_IF_ERROR(lhs_reflection_.struct_reflection.Initialize( lhs_reflection_.value_reflection.GetStructDescriptor())); return MapFieldEquals( lhs_reflection_.value_reflection.GetStructValue(*lhs_message), lhs_reflection_.struct_reflection.GetFieldsDescriptor(), rhs, rhs_field); } case Descriptor::WELLKNOWNTYPE_STRUCT: { CEL_RETURN_IF_ERROR( lhs_reflection_.struct_reflection.Initialize(lhs_descriptor)); return MapFieldEquals( *lhs_message, lhs_reflection_.struct_reflection.GetFieldsDescriptor(), rhs, rhs_field); } default: return false; } ABSL_UNREACHABLE(); } ABSL_DCHECK(lhs_field == nullptr || !lhs_field->is_map()); ABSL_DCHECK(rhs_field == nullptr || !rhs_field->is_map()); if (lhs_field != nullptr && lhs_field->is_repeated()) { if (rhs_field != nullptr && rhs_field->is_repeated()) { return RepeatedFieldEquals(lhs, lhs_field, rhs, rhs_field); } if (rhs_field != nullptr && rhs_field->type() != FieldDescriptor::TYPE_MESSAGE) { return false; } absl::Nullable<const Message*> rhs_packed = nullptr; Unique<Message> rhs_unpacked; if (rhs_field != nullptr && IsAnyField(rhs_field)) { rhs_packed = &rhs.GetReflection()->GetMessage(rhs, rhs_field); } else if (rhs_field == nullptr && IsAny(rhs)) { rhs_packed = &rhs; } if (rhs_packed != nullptr) { CEL_RETURN_IF_ERROR(rhs_reflection_.any_reflection.Initialize( rhs_packed->GetDescriptor())); auto rhs_type_url = rhs_reflection_.any_reflection.GetTypeUrl( *rhs_packed, rhs_scratch_); if (!rhs_type_url.ConsumePrefix("type.googleapis.com/") && !rhs_type_url.ConsumePrefix("type.googleprod.com/")) { return false; } if (rhs_type_url != "google.protobuf.Value" && rhs_type_url != "google.protobuf.ListValue" && rhs_type_url != "google.protobuf.Any") { return false; } CEL_ASSIGN_OR_RETURN(rhs_unpacked, well_known_types::UnpackAnyIfResolveable( &arena_, rhs_reflection_.any_reflection, *rhs_packed, pool_, factory_)); if (rhs_unpacked) { rhs_field = nullptr; } } absl::Nonnull<const Message*> rhs_message = rhs_field != nullptr ? &rhs.GetReflection()->GetMessage(rhs, rhs_field) : rhs_unpacked != nullptr ? cel::to_address(rhs_unpacked) : &rhs; const auto* rhs_descriptor = rhs_message->GetDescriptor(); const auto rhs_well_known_type = rhs_descriptor->well_known_type(); switch (rhs_well_known_type) { case Descriptor::WELLKNOWNTYPE_VALUE: { CEL_RETURN_IF_ERROR( rhs_reflection_.value_reflection.Initialize(rhs_descriptor)); if (rhs_reflection_.value_reflection.GetKindCase(*rhs_message) != google::protobuf::Value::kListValue) { return false; } CEL_RETURN_IF_ERROR(rhs_reflection_.list_value_reflection.Initialize( rhs_reflection_.value_reflection.GetListValueDescriptor())); return RepeatedFieldEquals( lhs, lhs_field, rhs_reflection_.value_reflection.GetListValue(*rhs_message), rhs_reflection_.list_value_reflection.GetValuesDescriptor()); } case Descriptor::WELLKNOWNTYPE_LISTVALUE: { CEL_RETURN_IF_ERROR( rhs_reflection_.list_value_reflection.Initialize(rhs_descriptor)); return RepeatedFieldEquals( lhs, lhs_field, *rhs_message, rhs_reflection_.list_value_reflection.GetValuesDescriptor()); } default: return false; } ABSL_UNREACHABLE(); } if (rhs_field != nullptr && rhs_field->is_repeated()) { ABSL_DCHECK(lhs_field == nullptr || !lhs_field->is_repeated()); if (lhs_field != nullptr && lhs_field->type() != FieldDescriptor::TYPE_MESSAGE) { return false; } absl::Nullable<const Message*> lhs_packed = nullptr; Unique<Message> lhs_unpacked; if (lhs_field != nullptr && IsAnyField(lhs_field)) { lhs_packed = &lhs.GetReflection()->GetMessage(lhs, lhs_field); } else if (lhs_field == nullptr && IsAny(lhs)) { lhs_packed = &lhs; } if (lhs_packed != nullptr) { CEL_RETURN_IF_ERROR(lhs_reflection_.any_reflection.Initialize( lhs_packed->GetDescriptor())); auto lhs_type_url = lhs_reflection_.any_reflection.GetTypeUrl( *lhs_packed, lhs_scratch_); if (!lhs_type_url.ConsumePrefix("type.googleapis.com/") && !lhs_type_url.ConsumePrefix("type.googleprod.com/")) { return false; } if (lhs_type_url != "google.protobuf.Value" && lhs_type_url != "google.protobuf.ListValue" && lhs_type_url != "google.protobuf.Any") { return false; } CEL_ASSIGN_OR_RETURN(lhs_unpacked, well_known_types::UnpackAnyIfResolveable( &arena_, lhs_reflection_.any_reflection, *lhs_packed, pool_, factory_)); if (lhs_unpacked) { lhs_field = nullptr; } } absl::Nonnull<const Message*> lhs_message = lhs_field != nullptr ? &lhs.GetReflection()->GetMessage(lhs, lhs_field) : lhs_unpacked != nullptr ? cel::to_address(lhs_unpacked) : &lhs; const auto* lhs_descriptor = lhs_message->GetDescriptor(); const auto lhs_well_known_type = lhs_descriptor->well_known_type(); switch (lhs_well_known_type) { case Descriptor::WELLKNOWNTYPE_VALUE: { CEL_RETURN_IF_ERROR( lhs_reflection_.value_reflection.Initialize(lhs_descriptor)); if (lhs_reflection_.value_reflection.GetKindCase(*lhs_message) != google::protobuf::Value::kListValue) { return false; } CEL_RETURN_IF_ERROR(lhs_reflection_.list_value_reflection.Initialize( lhs_reflection_.value_reflection.GetListValueDescriptor())); return RepeatedFieldEquals( lhs_reflection_.value_reflection.GetListValue(*lhs_message), lhs_reflection_.list_value_reflection.GetValuesDescriptor(), rhs, rhs_field); } case Descriptor::WELLKNOWNTYPE_LISTVALUE: { CEL_RETURN_IF_ERROR( lhs_reflection_.list_value_reflection.Initialize(lhs_descriptor)); return RepeatedFieldEquals( *lhs_message, lhs_reflection_.list_value_reflection.GetValuesDescriptor(), rhs, rhs_field); } default: return false; } ABSL_UNREACHABLE(); } return SingularFieldEquals(lhs, lhs_field, rhs, rhs_field); } private: const absl::Nonnull<const DescriptorPool*> pool_; const absl::Nonnull<MessageFactory*> factory_; google::protobuf::Arena arena_; EquatableValueReflection lhs_reflection_; EquatableValueReflection rhs_reflection_; std::string lhs_scratch_; std::string rhs_scratch_; }; } absl::StatusOr<bool> MessageEquals(const Message& lhs, const Message& rhs, absl::Nonnull<const DescriptorPool*> pool, absl::Nonnull<MessageFactory*> factory) { ABSL_DCHECK(pool != nullptr); ABSL_DCHECK(factory != nullptr); if (&lhs == &rhs) { return true; } return std::make_unique<MessageEqualsState>(pool, factory)->Equals(lhs, rhs); } absl::StatusOr<bool> MessageFieldEquals( const Message& lhs, absl::Nonnull<const FieldDescriptor*> lhs_field, const Message& rhs, absl::Nonnull<const FieldDescriptor*> rhs_field, absl::Nonnull<const DescriptorPool*> pool, absl::Nonnull<MessageFactory*> factory) { ABSL_DCHECK(lhs_field != nullptr); ABSL_DCHECK(rhs_field != nullptr); ABSL_DCHECK(pool != nullptr); ABSL_DCHECK(factory != nullptr); if (&lhs == &rhs && lhs_field == rhs_field) { return true; } return std::make_unique<MessageEqualsState>(pool, factory) ->FieldEquals(lhs, lhs_field, rhs, rhs_field); } absl::StatusOr<bool> MessageFieldEquals( const google::protobuf::Message& lhs, const google::protobuf::Message& rhs, absl::Nonnull<const google::protobuf::FieldDescriptor*> rhs_field, absl::Nonnull<const google::protobuf::DescriptorPool*> pool, absl::Nonnull<google::protobuf::MessageFactory*> factory) { ABSL_DCHECK(rhs_field != nullptr); ABSL_DCHECK(pool != nullptr); ABSL_DCHECK(factory != nullptr); return std::make_unique<MessageEqualsState>(pool, factory) ->FieldEquals(lhs, nullptr, rhs, rhs_field); } absl::StatusOr<bool> MessageFieldEquals( const google::protobuf::Message& lhs, absl::Nonnull<const google::protobuf::FieldDescriptor*> lhs_field, const google::protobuf::Message& rhs, absl::Nonnull<const google::protobuf::DescriptorPool*> pool, absl::Nonnull<google::protobuf::MessageFactory*> factory) { ABSL_DCHECK(lhs_field != nullptr); ABSL_DCHECK(pool != nullptr); ABSL_DCHECK(factory != nullptr); return std::make_unique<MessageEqualsState>(pool, factory) ->FieldEquals(lhs, lhs_field, rhs, nullptr); } }
#include "internal/message_equality.h" #include <string> #include <utility> #include <vector> #include "google/protobuf/any.pb.h" #include "google/protobuf/duration.pb.h" #include "google/protobuf/struct.pb.h" #include "google/protobuf/timestamp.pb.h" #include "google/protobuf/wrappers.pb.h" #include "absl/base/nullability.h" #include "absl/log/absl_check.h" #include "absl/log/die_if_null.h" #include "absl/status/status_matchers.h" #include "absl/strings/cord.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "common/allocator.h" #include "common/memory.h" #include "internal/message_type_name.h" #include "internal/parse_text_proto.h" #include "internal/testing.h" #include "internal/testing_descriptor_pool.h" #include "internal/testing_message_factory.h" #include "internal/well_known_types.h" #include "proto/test/v1/proto3/test_all_types.pb.h" #include "google/protobuf/arena.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/message.h" namespace cel::internal { namespace { using ::absl_testing::IsOkAndHolds; using ::testing::IsFalse; using ::testing::IsTrue; using ::testing::TestParamInfo; using ::testing::TestWithParam; using ::testing::ValuesIn; using TestAllTypesProto3 = ::google::api::expr::test::v1::proto3::TestAllTypes; template <typename T> Owned<google::protobuf::Message> ParseTextProto(absl::string_view text) { return DynamicParseTextProto<T>(NewDeleteAllocator(), text, GetTestingDescriptorPool(), GetTestingMessageFactory()); } struct UnaryMessageEqualsTestParam { std::string name; std::vector<Owned<google::protobuf::Message>> ops; bool equal; }; std::string UnaryMessageEqualsTestParamName( const TestParamInfo<UnaryMessageEqualsTestParam>& param_info) { return param_info.param.name; } using UnaryMessageEqualsTest = TestWithParam<UnaryMessageEqualsTestParam>; Owned<google::protobuf::Message> PackMessage(const google::protobuf::Message& message) { const auto* descriptor = ABSL_DIE_IF_NULL(GetTestingDescriptorPool()->FindMessageTypeByName( MessageTypeNameFor<google::protobuf::Any>())); const auto* prototype = ABSL_DIE_IF_NULL(GetTestingMessageFactory()->GetPrototype(descriptor)); auto instance = WrapShared(prototype->New(), NewDeleteAllocator()); auto reflection = well_known_types::GetAnyReflectionOrDie(descriptor); reflection.SetTypeUrl( cel::to_address(instance), absl::StrCat("type.googleapis.com/", message.GetTypeName())); absl::Cord value; ABSL_CHECK(message.SerializeToCord(&value)); reflection.SetValue(cel::to_address(instance), value); return instance; } TEST_P(UnaryMessageEqualsTest, Equals) { const auto* pool = GetTestingDescriptorPool(); auto* factory = GetTestingMessageFactory(); const auto& test_case = GetParam(); for (const auto& lhs : test_case.ops) { for (const auto& rhs : test_case.ops) { if (!test_case.equal && &lhs == &rhs) { continue; } EXPECT_THAT(MessageEquals(*lhs, *rhs, pool, factory), IsOkAndHolds(test_case.equal)) << *lhs << " " << *rhs; EXPECT_THAT(MessageEquals(*rhs, *lhs, pool, factory), IsOkAndHolds(test_case.equal)) << *lhs << " " << *rhs; auto lhs_any = PackMessage(*lhs); auto rhs_any = PackMessage(*rhs); EXPECT_THAT(MessageEquals(*lhs_any, *rhs, pool, factory), IsOkAndHolds(test_case.equal)) << *lhs_any << " " << *rhs; EXPECT_THAT(MessageEquals(*lhs, *rhs_any, pool, factory), IsOkAndHolds(test_case.equal)) << *lhs << " " << *rhs_any; EXPECT_THAT(MessageEquals(*lhs_any, *rhs_any, pool, factory), IsOkAndHolds(test_case.equal)) << *lhs_any << " " << *rhs_any; } } } INSTANTIATE_TEST_SUITE_P( UnaryMessageEqualsTest, UnaryMessageEqualsTest, ValuesIn<UnaryMessageEqualsTestParam>({ { .name = "NullValue_Equal", .ops = { ParseTextProto<google::protobuf::Value>(R"pb()pb"), ParseTextProto<google::protobuf::Value>( R"pb(null_value: NULL_VALUE)pb"), }, .equal = true, }, { .name = "BoolValue_False_Equal", .ops = { ParseTextProto<google::protobuf::BoolValue>(R"pb()pb"), ParseTextProto<google::protobuf::BoolValue>( R"pb(value: false)pb"), ParseTextProto<google::protobuf::Value>( R"pb(bool_value: false)pb"), }, .equal = true, }, { .name = "BoolValue_True_Equal", .ops = { ParseTextProto<google::protobuf::BoolValue>( R"pb(value: true)pb"), ParseTextProto<google::protobuf::Value>(R"pb(bool_value: true)pb"), }, .equal = true, }, { .name = "StringValue_Empty_Equal", .ops = { ParseTextProto<google::protobuf::StringValue>(R"pb()pb"), ParseTextProto<google::protobuf::StringValue>( R"pb(value: "")pb"), ParseTextProto<google::protobuf::Value>( R"pb(string_value: "")pb"), }, .equal = true, }, { .name = "StringValue_Equal", .ops = { ParseTextProto<google::protobuf::StringValue>( R"pb(value: "foo")pb"), ParseTextProto<google::protobuf::Value>( R"pb(string_value: "foo")pb"), }, .equal = true, }, { .name = "BytesValue_Empty_Equal", .ops = { ParseTextProto<google::protobuf::BytesValue>(R"pb()pb"), ParseTextProto<google::protobuf::BytesValue>( R"pb(value: "")pb"), }, .equal = true, }, { .name = "BytesValue_Equal", .ops = { ParseTextProto<google::protobuf::BytesValue>( R"pb(value: "foo")pb"), ParseTextProto<google::protobuf::BytesValue>( R"pb(value: "foo")pb"), }, .equal = true, }, { .name = "ListValue_Equal", .ops = { ParseTextProto<google::protobuf::Value>( R"pb(list_value: { values { bool_value: true } })pb"), ParseTextProto<google::protobuf::ListValue>( R"pb(values { bool_value: true })pb"), }, .equal = true, }, { .name = "ListValue_NotEqual", .ops = { ParseTextProto<google::protobuf::Value>( R"pb(list_value: { values { number_value: 0.0 } })pb"), ParseTextProto<google::protobuf::ListValue>( R"pb(values { number_value: 1.0 })pb"), ParseTextProto<google::protobuf::Value>( R"pb(list_value: { values { number_value: 2.0 } })pb"), ParseTextProto<google::protobuf::ListValue>( R"pb(values { number_value: 3.0 })pb"), }, .equal = false, }, { .name = "StructValue_Equal", .ops = { ParseTextProto<google::protobuf::Value>( R"pb(struct_value: { fields { key: "foo" value: { bool_value: true } } })pb"), ParseTextProto<google::protobuf::Struct>( R"pb(fields { key: "foo" value: { bool_value: true } })pb"), }, .equal = true, }, { .name = "StructValue_NotEqual", .ops = { ParseTextProto<google::protobuf::Value>( R"pb(struct_value: { fields { key: "foo" value: { number_value: 0.0 } } })pb"), ParseTextProto<google::protobuf::Struct>( R"pb( fields { key: "bar" value: { number_value: 0.0 } })pb"), ParseTextProto<google::protobuf::Value>( R"pb(struct_value: { fields { key: "foo" value: { number_value: 1.0 } } })pb"), ParseTextProto<google::protobuf::Struct>( R"pb( fields { key: "bar" value: { number_value: 1.0 } })pb"), }, .equal = false, }, { .name = "Heterogeneous_Equal", .ops = { ParseTextProto<google::protobuf::Int32Value>(R"pb()pb"), ParseTextProto<google::protobuf::Int64Value>(R"pb()pb"), ParseTextProto<google::protobuf::UInt32Value>(R"pb()pb"), ParseTextProto<google::protobuf::UInt64Value>(R"pb()pb"), ParseTextProto<google::protobuf::FloatValue>(R"pb()pb"), ParseTextProto<google::protobuf::DoubleValue>(R"pb()pb"), ParseTextProto<google::protobuf::Value>(R"pb(number_value: 0.0)pb"), }, .equal = true, }, { .name = "Message_Equals", .ops = { ParseTextProto<TestAllTypesProto3>(R"pb()pb"), ParseTextProto<TestAllTypesProto3>(R"pb()pb"), }, .equal = true, }, { .name = "Heterogeneous_NotEqual", .ops = { ParseTextProto<google::protobuf::BoolValue>( R"pb(value: false)pb"), ParseTextProto<google::protobuf::Int32Value>( R"pb(value: 0)pb"), ParseTextProto<google::protobuf::Int64Value>( R"pb(value: 1)pb"), ParseTextProto<google::protobuf::UInt32Value>( R"pb(value: 2)pb"), ParseTextProto<google::protobuf::UInt64Value>( R"pb(value: 3)pb"), ParseTextProto<google::protobuf::FloatValue>( R"pb(value: 4.0)pb"), ParseTextProto<google::protobuf::DoubleValue>( R"pb(value: 5.0)pb"), ParseTextProto<google::protobuf::Value>(R"pb()pb"), ParseTextProto<google::protobuf::Value>(R"pb(bool_value: true)pb"), ParseTextProto<google::protobuf::Value>(R"pb(number_value: 6.0)pb"), ParseTextProto<google::protobuf::Value>( R"pb(string_value: "bar")pb"), ParseTextProto<google::protobuf::BytesValue>( R"pb(value: "foo")pb"), ParseTextProto<google::protobuf::StringValue>( R"pb(value: "")pb"), ParseTextProto<google::protobuf::StringValue>( R"pb(value: "foo")pb"), ParseTextProto<google::protobuf::Value>( R"pb(list_value: {})pb"), ParseTextProto<google::protobuf::ListValue>( R"pb(values { bool_value: true })pb"), ParseTextProto<google::protobuf::Value>(R"pb(struct_value: {})pb"), ParseTextProto<google::protobuf::Struct>( R"pb(fields { key: "foo" value: { bool_value: false } })pb"), ParseTextProto<google::protobuf::Duration>(R"pb()pb"), ParseTextProto<google::protobuf::Duration>( R"pb(seconds: 1 nanos: 1)pb"), ParseTextProto<google::protobuf::Timestamp>(R"pb()pb"), ParseTextProto<google::protobuf::Timestamp>( R"pb(seconds: 1 nanos: 1)pb"), ParseTextProto<TestAllTypesProto3>(R"pb()pb"), ParseTextProto<TestAllTypesProto3>( R"pb(single_bool: true)pb"), }, .equal = false, }, }), UnaryMessageEqualsTestParamName); struct UnaryMessageFieldEqualsTestParam { std::string name; std::string message; std::vector<std::string> fields; bool equal; }; std::string UnaryMessageFieldEqualsTestParamName( const TestParamInfo<UnaryMessageFieldEqualsTestParam>& param_info) { return param_info.param.name; } using UnaryMessageFieldEqualsTest = TestWithParam<UnaryMessageFieldEqualsTestParam>; void PackMessageTo(const google::protobuf::Message& message, google::protobuf::Message* instance) { auto reflection = *well_known_types::GetAnyReflection(instance->GetDescriptor()); reflection.SetTypeUrl( instance, absl::StrCat("type.googleapis.com/", message.GetTypeName())); absl::Cord value; ABSL_CHECK(message.SerializeToCord(&value)); reflection.SetValue(instance, value); } absl::optional<std::pair<Owned<google::protobuf::Message>, absl::Nonnull<const google::protobuf::FieldDescriptor*>>> PackTestAllTypesProto3Field( const google::protobuf::Message& message, absl::Nonnull<const google::protobuf::FieldDescriptor*> field) { if (field->is_map()) { return absl::nullopt; } if (field->is_repeated() && field->type() == google::protobuf::FieldDescriptor::TYPE_MESSAGE) { const auto* descriptor = message.GetDescriptor(); const auto* any_field = descriptor->FindFieldByName("repeated_any"); auto packed = WrapShared(message.New(), NewDeleteAllocator()); const int size = message.GetReflection()->FieldSize(message, field); for (int i = 0; i < size; ++i) { PackMessageTo( message.GetReflection()->GetRepeatedMessage(message, field, i), packed->GetReflection()->AddMessage(cel::to_address(packed), any_field)); } return std::pair{packed, any_field}; } if (!field->is_repeated() && field->type() == google::protobuf::FieldDescriptor::TYPE_MESSAGE) { const auto* descriptor = message.GetDescriptor(); const auto* any_field = descriptor->FindFieldByName("single_any"); auto packed = WrapShared(message.New(), NewDeleteAllocator()); PackMessageTo(message.GetReflection()->GetMessage(message, field), packed->GetReflection()->MutableMessage( cel::to_address(packed), any_field)); return std::pair{packed, any_field}; } return absl::nullopt; } TEST_P(UnaryMessageFieldEqualsTest, Equals) { const auto* pool = GetTestingDescriptorPool(); auto* factory = GetTestingMessageFactory(); const auto& test_case = GetParam(); auto lhs_message = ParseTextProto<TestAllTypesProto3>(test_case.message); auto rhs_message = ParseTextProto<TestAllTypesProto3>(test_case.message); const auto* descriptor = ABSL_DIE_IF_NULL( pool->FindMessageTypeByName(MessageTypeNameFor<TestAllTypesProto3>())); for (const auto& lhs : test_case.fields) { for (const auto& rhs : test_case.fields) { if (!test_case.equal && lhs == rhs) { continue; } const auto* lhs_field = ABSL_DIE_IF_NULL(descriptor->FindFieldByName(lhs)); const auto* rhs_field = ABSL_DIE_IF_NULL(descriptor->FindFieldByName(rhs)); EXPECT_THAT(MessageFieldEquals(*lhs_message, lhs_field, *rhs_message, rhs_field, pool, factory), IsOkAndHolds(test_case.equal)) << *lhs_message << " " << lhs_field->name() << " " << *rhs_message << " " << rhs_field->name(); EXPECT_THAT(MessageFieldEquals(*rhs_message, rhs_field, *lhs_message, lhs_field, pool, factory), IsOkAndHolds(test_case.equal)) << *lhs_message << " " << lhs_field->name() << " " << *rhs_message << " " << rhs_field->name(); if (!lhs_field->is_repeated() && lhs_field->type() == google::protobuf::FieldDescriptor::TYPE_MESSAGE) { EXPECT_THAT(MessageFieldEquals(lhs_message->GetReflection()->GetMessage( *lhs_message, lhs_field), *rhs_message, rhs_field, pool, factory), IsOkAndHolds(test_case.equal)) << *lhs_message << " " << lhs_field->name() << " " << *rhs_message << " " << rhs_field->name(); EXPECT_THAT(MessageFieldEquals(*rhs_message, rhs_field, lhs_message->GetReflection()->GetMessage( *lhs_message, lhs_field), pool, factory), IsOkAndHolds(test_case.equal)) << *lhs_message << " " << lhs_field->name() << " " << *rhs_message << " " << rhs_field->name(); } if (!rhs_field->is_repeated() && rhs_field->type() == google::protobuf::FieldDescriptor::TYPE_MESSAGE) { EXPECT_THAT(MessageFieldEquals(*lhs_message, lhs_field, rhs_message->GetReflection()->GetMessage( *rhs_message, rhs_field), pool, factory), IsOkAndHolds(test_case.equal)) << *lhs_message << " " << lhs_field->name() << " " << *rhs_message << " " << rhs_field->name(); EXPECT_THAT(MessageFieldEquals(rhs_message->GetReflection()->GetMessage( *rhs_message, rhs_field), *lhs_message, lhs_field, pool, factory), IsOkAndHolds(test_case.equal)) << *lhs_message << " " << lhs_field->name() << " " << *rhs_message << " " << rhs_field->name(); } absl::optional<std::pair<Owned<google::protobuf::Message>, absl::Nonnull<const google::protobuf::FieldDescriptor*>>> lhs_any = PackTestAllTypesProto3Field(*lhs_message, lhs_field); absl::optional<std::pair<Owned<google::protobuf::Message>, absl::Nonnull<const google::protobuf::FieldDescriptor*>>> rhs_any = PackTestAllTypesProto3Field(*rhs_message, rhs_field); if (lhs_any) { EXPECT_THAT(MessageFieldEquals(*lhs_any->first, lhs_any->second, *rhs_message, rhs_field, pool, factory), IsOkAndHolds(test_case.equal)) << *lhs_any->first << " " << *rhs_message; if (!lhs_any->second->is_repeated()) { EXPECT_THAT( MessageFieldEquals(lhs_any->first->GetReflection()->GetMessage( *lhs_any->first, lhs_any->second), *rhs_message, rhs_field, pool, factory), IsOkAndHolds(test_case.equal)) << *lhs_any->first << " " << *rhs_message; } } if (rhs_any) { EXPECT_THAT(MessageFieldEquals(*lhs_message, lhs_field, *rhs_any->first, rhs_any->second, pool, factory), IsOkAndHolds(test_case.equal)) << *lhs_message << " " << *rhs_any->first; if (!rhs_any->second->is_repeated()) { EXPECT_THAT( MessageFieldEquals(*lhs_message, lhs_field, rhs_any->first->GetReflection()->GetMessage( *rhs_any->first, rhs_any->second), pool, factory), IsOkAndHolds(test_case.equal)) << *lhs_message << " " << *rhs_any->first; } } if (lhs_any && rhs_any) { EXPECT_THAT( MessageFieldEquals(*lhs_any->first, lhs_any->second, *rhs_any->first, rhs_any->second, pool, factory), IsOkAndHolds(test_case.equal)) << *lhs_any->first << " " << *rhs_any->second; } } } } INSTANTIATE_TEST_SUITE_P( UnaryMessageFieldEqualsTest, UnaryMessageFieldEqualsTest, ValuesIn<UnaryMessageFieldEqualsTestParam>({ { .name = "Heterogeneous_Single_Equal", .message = R"pb( single_int32: 1 single_int64: 1 single_uint32: 1 single_uint64: 1 single_float: 1 single_double: 1 single_value: { number_value: 1 } single_int32_wrapper: { value: 1 } single_int64_wrapper: { value: 1 } single_uint32_wrapper: { value: 1 } single_uint64_wrapper: { value: 1 } single_float_wrapper: { value: 1 } single_double_wrapper: { value: 1 } standalone_enum: BAR )pb", .fields = { "single_int32", "single_int64", "single_uint32", "single_uint64", "single_float", "single_double", "single_value", "single_int32_wrapper", "single_int64_wrapper", "single_uint32_wrapper", "single_uint64_wrapper", "single_float_wrapper", "single_double_wrapper", "standalone_enum", }, .equal = true, }, { .name = "Heterogeneous_Single_NotEqual", .message = R"pb( null_value: NULL_VALUE single_bool: false single_int32: 2 single_int64: 3 single_uint32: 4 single_uint64: 5 single_float: NaN single_double: NaN single_string: "foo" single_bytes: "foo" single_value: { number_value: 8 } single_int32_wrapper: { value: 9 } single_int64_wrapper: { value: 10 } single_uint32_wrapper: { value: 11 } single_uint64_wrapper: { value: 12 } single_float_wrapper: { value: 13 } single_double_wrapper: { value: 14 } single_string_wrapper: { value: "bar" } single_bytes_wrapper: { value: "bar" } standalone_enum: BAR )pb", .fields = { "null_value", "single_bool", "single_int32", "single_int64", "single_uint32", "single_uint64", "single_float", "single_double", "single_string", "single_bytes", "single_value", "single_int32_wrapper", "single_int64_wrapper", "single_uint32_wrapper", "single_uint64_wrapper", "single_float_wrapper", "single_double_wrapper", "standalone_enum", }, .equal = false, }, { .name = "Heterogeneous_Repeated_Equal", .message = R"pb( repeated_int32: 1 repeated_int64: 1 repeated_uint32: 1 repeated_uint64: 1 repeated_float: 1 repeated_double: 1 repeated_value: { number_value: 1 } repeated_int32_wrapper: { value: 1 } repeated_int64_wrapper: { value: 1 } repeated_uint32_wrapper: { value: 1 } repeated_uint64_wrapper: { value: 1 } repeated_float_wrapper: { value: 1 } repeated_double_wrapper: { value: 1 } repeated_nested_enum: BAR single_value: { list_value: { values { number_value: 1 } } } list_value: { values { number_value: 1 } } )pb", .fields = { "repeated_int32", "repeated_int64", "repeated_uint32", "repeated_uint64", "repeated_float", "repeated_double", "repeated_value", "repeated_int32_wrapper", "repeated_int64_wrapper", "repeated_uint32_wrapper", "repeated_uint64_wrapper", "repeated_float_wrapper", "repeated_double_wrapper", "repeated_nested_enum", "single_value", "list_value", }, .equal = true, }, { .name = "Heterogeneous_Repeated_NotEqual", .message = R"pb( repeated_null_value: NULL_VALUE repeated_bool: false repeated_int32: 2 repeated_int64: 3 repeated_uint32: 4 repeated_uint64: 5 repeated_float: 6 repeated_double: 7 repeated_string: "foo" repeated_bytes: "foo" repeated_value: { number_value: 8 } repeated_int32_wrapper: { value: 9 } repeated_int64_wrapper: { value: 10 } repeated_uint32_wrapper: { value: 11 } repeated_uint64_wrapper: { value: 12 } repeated_float_wrapper: { value: 13 } repeated_double_wrapper: { value: 14 } repeated_string_wrapper: { value: "bar" } repeated_bytes_wrapper: { value: "bar" } repeated_nested_enum: BAR )pb", .fields = { "repeated_null_value", "repeated_bool", "repeated_int32", "repeated_int64", "repeated_uint32", "repeated_uint64", "repeated_float", "repeated_double", "repeated_string", "repeated_bytes", "repeated_value", "repeated_int32_wrapper", "repeated_int64_wrapper", "repeated_uint32_wrapper", "repeated_uint64_wrapper", "repeated_float_wrapper", "repeated_double_wrapper", "repeated_nested_enum", }, .equal = false, }, { .name = "Heterogeneous_Map_Equal", .message = R"pb( map_int32_int32 { key: 1 value: 1 } map_int32_uint32 { key: 1 value: 1 } map_int32_int64 { key: 1 value: 1 } map_int32_uint64 { key: 1 value: 1 } map_int32_float { key: 1 value: 1 } map_int32_double { key: 1 value: 1 } map_int32_enum { key: 1 value: BAR } map_int32_value { key: 1 value: { number_value: 1 } } map_int32_int32_wrapper { key: 1 value: { value: 1 } } map_int32_uint32_wrapper { key: 1 value: { value: 1 } } map_int32_int64_wrapper { key: 1 value: { value: 1 } } map_int32_uint64_wrapper { key: 1 value: { value: 1 } } map_int32_float_wrapper { key: 1 value: { value: 1 } } map_int32_double_wrapper { key: 1 value: { value: 1 } } map_int64_int32 { key: 1 value: 1 } map_int64_uint32 { key: 1 value: 1 } map_int64_int64 { key: 1 value: 1 } map_int64_uint64 { key: 1 value: 1 } map_int64_float { key: 1 value: 1 } map_int64_double { key: 1 value: 1 } map_int64_enum { key: 1 value: BAR } map_int64_value { key: 1 value: { number_value: 1 } } map_int64_int32_wrapper { key: 1 value: { value: 1 } } map_int64_uint32_wrapper { key: 1 value: { value: 1 } } map_int64_int64_wrapper { key: 1 value: { value: 1 } } map_int64_uint64_wrapper { key: 1 value: { value: 1 } } map_int64_float_wrapper { key: 1 value: { value: 1 } } map_int64_double_wrapper { key: 1 value: { value: 1 } } map_uint32_int32 { key: 1 value: 1 } map_uint32_uint32 { key: 1 value: 1 } map_uint32_int64 { key: 1 value: 1 } map_uint32_uint64 { key: 1 value: 1 } map_uint32_float { key: 1 value: 1 } map_uint32_double { key: 1 value: 1 } map_uint32_enum { key: 1 value: BAR } map_uint32_value { key: 1 value: { number_value: 1 } } map_uint32_int32_wrapper { key: 1 value: { value: 1 } } map_uint32_uint32_wrapper { key: 1 value: { value: 1 } } map_uint32_int64_wrapper { key: 1 value: { value: 1 } } map_uint32_uint64_wrapper { key: 1 value: { value: 1 } } map_uint32_float_wrapper { key: 1 value: { value: 1 } } map_uint32_double_wrapper { key: 1 value: { value: 1 } } map_uint64_int32 { key: 1 value: 1 } map_uint64_uint32 { key: 1 value: 1 } map_uint64_int64 { key: 1 value: 1 } map_uint64_uint64 { key: 1 value: 1 } map_uint64_float { key: 1 value: 1 } map_uint64_double { key: 1 value: 1 } map_uint64_enum { key: 1 value: BAR } map_uint64_value { key: 1 value: { number_value: 1 } } map_uint64_int32_wrapper { key: 1 value: { value: 1 } } map_uint64_uint32_wrapper { key: 1 value: { value: 1 } } map_uint64_int64_wrapper { key: 1 value: { value: 1 } } map_uint64_uint64_wrapper { key: 1 value: { value: 1 } } map_uint64_float_wrapper { key: 1 value: { value: 1 } } map_uint64_double_wrapper { key: 1 value: { value: 1 } } )pb", .fields = { "map_int32_int32", "map_int32_uint32", "map_int32_int64", "map_int32_uint64", "map_int32_float", "map_int32_double", "map_int32_enum", "map_int32_value", "map_int32_int32_wrapper", "map_int32_uint32_wrapper", "map_int32_int64_wrapper", "map_int32_uint64_wrapper", "map_int32_float_wrapper", "map_int32_double_wrapper", "map_int64_int32", "map_int64_uint32", "map_int64_int64", "map_int64_uint64", "map_int64_float", "map_int64_double", "map_int64_enum", "map_int64_value", "map_int64_int32_wrapper", "map_int64_uint32_wrapper", "map_int64_int64_wrapper", "map_int64_uint64_wrapper", "map_int64_float_wrapper", "map_int64_double_wrapper", "map_uint32_int32", "map_uint32_uint32", "map_uint32_int64", "map_uint32_uint64", "map_uint32_float", "map_uint32_double", "map_uint32_enum", "map_uint32_value", "map_uint32_int32_wrapper", "map_uint32_uint32_wrapper", "map_uint32_int64_wrapper", "map_uint32_uint64_wrapper", "map_uint32_float_wrapper", "map_uint32_double_wrapper", "map_uint64_int32", "map_uint64_uint32", "map_uint64_int64", "map_uint64_uint64", "map_uint64_float", "map_uint64_double", "map_uint64_enum", "map_uint64_value", "map_uint64_int32_wrapper", "map_uint64_uint32_wrapper", "map_uint64_int64_wrapper", "map_uint64_uint64_wrapper", "map_uint64_float_wrapper", "map_uint64_double_wrapper", }, .equal = true, }, { .name = "Heterogeneous_Map_NotEqual", .message = R"pb( map_bool_bool { key: false value: false } map_bool_int32 { key: false value: 1 } map_bool_uint32 { key: false value: 0 } map_int32_int32 { key: 0x7FFFFFFF value: 1 } map_int64_int64 { key: 0x7FFFFFFFFFFFFFFF value: 1 } map_uint32_uint32 { key: 0xFFFFFFFF value: 1 } map_uint64_uint64 { key: 0xFFFFFFFFFFFFFFFF value: 1 } map_string_string { key: "foo" value: "bar" } map_string_bytes { key: "foo" value: "bar" } map_int32_bytes { key: -2147483648 value: "bar" } map_int64_bytes { key: -9223372036854775808 value: "bar" } map_int32_float { key: -2147483648 value: 1 } map_int64_double { key: -9223372036854775808 value: 1 } map_uint32_string { key: 0xFFFFFFFF value: "bar" } map_uint64_string { key: 0xFFFFFFFF value: "foo" } map_uint32_bytes { key: 0xFFFFFFFF value: "bar" } map_uint64_bytes { key: 0xFFFFFFFF value: "foo" } map_uint32_bool { key: 0xFFFFFFFF value: false } map_uint64_bool { key: 0xFFFFFFFF value: true } single_value: { struct_value: { fields { key: "bar" value: { string_value: "foo" } } } } single_struct: { fields { key: "baz" value: { string_value: "foo" } } } standalone_message: {} )pb", .fields = { "map_bool_bool", "map_bool_int32", "map_bool_uint32", "map_int32_int32", "map_int64_int64", "map_uint32_uint32", "map_uint64_uint64", "map_string_string", "map_string_bytes", "map_int32_bytes", "map_int64_bytes", "map_int32_float", "map_int64_double", "map_uint32_string", "map_uint64_string", "map_uint32_bytes", "map_uint64_bytes", "map_uint32_bool", "map_uint64_bool", "single_value", "single_struct", "standalone_message", }, .equal = false, }, }), UnaryMessageFieldEqualsTestParamName); TEST(MessageEquals, AnyFallback) { const auto* pool = GetTestingDescriptorPool(); auto* factory = GetTestingMessageFactory(); google::protobuf::Arena arena; auto message1 = DynamicParseTextProto<TestAllTypesProto3>( &arena, R"pb(single_any: { type_url: "type.googleapis.com/message.that.does.not.Exist" value: "foo" })pb", pool, factory); auto message2 = DynamicParseTextProto<TestAllTypesProto3>( &arena, R"pb(single_any: { type_url: "type.googleapis.com/message.that.does.not.Exist" value: "foo" })pb", pool, factory); auto message3 = DynamicParseTextProto<TestAllTypesProto3>( &arena, R"pb(single_any: { type_url: "type.googleapis.com/message.that.does.not.Exist" value: "bar" })pb", pool, factory); EXPECT_THAT(MessageEquals(*message1, *message2, pool, factory), IsOkAndHolds(IsTrue())); EXPECT_THAT(MessageEquals(*message2, *message1, pool, factory), IsOkAndHolds(IsTrue())); EXPECT_THAT(MessageEquals(*message1, *message3, pool, factory), IsOkAndHolds(IsFalse())); EXPECT_THAT(MessageEquals(*message3, *message1, pool, factory), IsOkAndHolds(IsFalse())); } TEST(MessageFieldEquals, AnyFallback) { const auto* pool = GetTestingDescriptorPool(); auto* factory = GetTestingMessageFactory(); google::protobuf::Arena arena; auto message1 = DynamicParseTextProto<TestAllTypesProto3>( &arena, R"pb(single_any: { type_url: "type.googleapis.com/message.that.does.not.Exist" value: "foo" })pb", pool, factory); auto message2 = DynamicParseTextProto<TestAllTypesProto3>( &arena, R"pb(single_any: { type_url: "type.googleapis.com/message.that.does.not.Exist" value: "foo" })pb", pool, factory); auto message3 = DynamicParseTextProto<TestAllTypesProto3>( &arena, R"pb(single_any: { type_url: "type.googleapis.com/message.that.does.not.Exist" value: "bar" })pb", pool, factory); EXPECT_THAT(MessageFieldEquals( *message1, ABSL_DIE_IF_NULL( message1->GetDescriptor()->FindFieldByName("single_any")), *message2, ABSL_DIE_IF_NULL( message2->GetDescriptor()->FindFieldByName("single_any")), pool, factory), IsOkAndHolds(IsTrue())); EXPECT_THAT(MessageFieldEquals( *message2, ABSL_DIE_IF_NULL( message2->GetDescriptor()->FindFieldByName("single_any")), *message1, ABSL_DIE_IF_NULL( message1->GetDescriptor()->FindFieldByName("single_any")), pool, factory), IsOkAndHolds(IsTrue())); EXPECT_THAT(MessageFieldEquals( *message1, ABSL_DIE_IF_NULL( message1->GetDescriptor()->FindFieldByName("single_any")), *message3, ABSL_DIE_IF_NULL( message3->GetDescriptor()->FindFieldByName("single_any")), pool, factory), IsOkAndHolds(IsFalse())); EXPECT_THAT(MessageFieldEquals( *message3, ABSL_DIE_IF_NULL( message3->GetDescriptor()->FindFieldByName("single_any")), *message1, ABSL_DIE_IF_NULL( message1->GetDescriptor()->FindFieldByName("single_any")), pool, factory), IsOkAndHolds(IsFalse())); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/message_equality.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/message_equality_test.cc
4552db5798fb0853b131b783d8875794334fae7f
baa990a7-f3e5-4cf9-98a9-9ce6ba0b324b
cpp
google/cel-cpp
testing_descriptor_pool
internal/testing_descriptor_pool.cc
internal/testing_descriptor_pool_test.cc
#include "internal/testing_descriptor_pool.h" #include <cstdint> #include "google/protobuf/descriptor.pb.h" #include "absl/base/attributes.h" #include "absl/base/macros.h" #include "absl/base/nullability.h" #include "absl/log/absl_check.h" #include "google/protobuf/descriptor.h" namespace cel::internal { namespace { ABSL_CONST_INIT const uint8_t kTestingDescriptorSet[] = { #include "internal/testing_descriptor_set_embed.inc" }; } absl::Nonnull<const google::protobuf::DescriptorPool*> GetTestingDescriptorPool() { static absl::Nonnull<const google::protobuf::DescriptorPool* const> pool = []() { google::protobuf::FileDescriptorSet file_desc_set; ABSL_CHECK(file_desc_set.ParseFromArray( kTestingDescriptorSet, ABSL_ARRAYSIZE(kTestingDescriptorSet))); auto* pool = new google::protobuf::DescriptorPool(); for (const auto& file_desc : file_desc_set.file()) { ABSL_CHECK(pool->BuildFile(file_desc) != nullptr); } return pool; }(); return pool; } }
#include "internal/testing_descriptor_pool.h" #include "internal/testing.h" #include "google/protobuf/descriptor.h" namespace cel::internal { namespace { using ::testing::NotNull; TEST(TestingDescriptorPool, NullValue) { ASSERT_THAT(GetTestingDescriptorPool()->FindEnumTypeByName( "google.protobuf.NullValue"), NotNull()); } TEST(TestingDescriptorPool, BoolValue) { const auto* desc = GetTestingDescriptorPool()->FindMessageTypeByName( "google.protobuf.BoolValue"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_BOOLVALUE); } TEST(TestingDescriptorPool, Int32Value) { const auto* desc = GetTestingDescriptorPool()->FindMessageTypeByName( "google.protobuf.Int32Value"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_INT32VALUE); } TEST(TestingDescriptorPool, Int64Value) { const auto* desc = GetTestingDescriptorPool()->FindMessageTypeByName( "google.protobuf.Int64Value"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_INT64VALUE); } TEST(TestingDescriptorPool, UInt32Value) { const auto* desc = GetTestingDescriptorPool()->FindMessageTypeByName( "google.protobuf.UInt32Value"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_UINT32VALUE); } TEST(TestingDescriptorPool, UInt64Value) { const auto* desc = GetTestingDescriptorPool()->FindMessageTypeByName( "google.protobuf.UInt64Value"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_UINT64VALUE); } TEST(TestingDescriptorPool, FloatValue) { const auto* desc = GetTestingDescriptorPool()->FindMessageTypeByName( "google.protobuf.FloatValue"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_FLOATVALUE); } TEST(TestingDescriptorPool, DoubleValue) { const auto* desc = GetTestingDescriptorPool()->FindMessageTypeByName( "google.protobuf.DoubleValue"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_DOUBLEVALUE); } TEST(TestingDescriptorPool, BytesValue) { const auto* desc = GetTestingDescriptorPool()->FindMessageTypeByName( "google.protobuf.BytesValue"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_BYTESVALUE); } TEST(TestingDescriptorPool, StringValue) { const auto* desc = GetTestingDescriptorPool()->FindMessageTypeByName( "google.protobuf.StringValue"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_STRINGVALUE); } TEST(TestingDescriptorPool, Any) { const auto* desc = GetTestingDescriptorPool()->FindMessageTypeByName("google.protobuf.Any"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_ANY); } TEST(TestingDescriptorPool, Duration) { const auto* desc = GetTestingDescriptorPool()->FindMessageTypeByName( "google.protobuf.Duration"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_DURATION); } TEST(TestingDescriptorPool, Timestamp) { const auto* desc = GetTestingDescriptorPool()->FindMessageTypeByName( "google.protobuf.Timestamp"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_TIMESTAMP); } TEST(TestingDescriptorPool, Value) { const auto* desc = GetTestingDescriptorPool()->FindMessageTypeByName( "google.protobuf.Value"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_VALUE); } TEST(TestingDescriptorPool, ListValue) { const auto* desc = GetTestingDescriptorPool()->FindMessageTypeByName( "google.protobuf.ListValue"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_LISTVALUE); } TEST(TestingDescriptorPool, Struct) { const auto* desc = GetTestingDescriptorPool()->FindMessageTypeByName( "google.protobuf.Struct"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_STRUCT); } TEST(TestingDescriptorPool, FieldMask) { const auto* desc = GetTestingDescriptorPool()->FindMessageTypeByName( "google.protobuf.FieldMask"); ASSERT_THAT(desc, NotNull()); EXPECT_EQ(desc->well_known_type(), google::protobuf::Descriptor::WELLKNOWNTYPE_FIELDMASK); } TEST(TestingDescriptorPool, Empty) { const auto* desc = GetTestingDescriptorPool()->FindMessageTypeByName( "google.protobuf.Empty"); ASSERT_THAT(desc, NotNull()); } TEST(TestingDescriptorPool, TestAllTypesProto2) { EXPECT_THAT(GetTestingDescriptorPool()->FindMessageTypeByName( "google.api.expr.test.v1.proto2.TestAllTypes"), NotNull()); } TEST(TestingDescriptorPool, TestAllTypesProto3) { EXPECT_THAT(GetTestingDescriptorPool()->FindMessageTypeByName( "google.api.expr.test.v1.proto3.TestAllTypes"), NotNull()); } } }
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/testing_descriptor_pool.cc
https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/testing_descriptor_pool_test.cc
4552db5798fb0853b131b783d8875794334fae7f