1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
|
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/signaling/ftl_message_reception_channel.h"
#include <algorithm>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/weak_ptr.h"
#include "base/notreached.h"
#include "base/run_loop.h"
#include "base/task/sequenced_task_runner.h"
#include "base/test/bind.h"
#include "base/test/mock_callback.h"
#include "base/test/task_environment.h"
#include "base/time/time.h"
#include "remoting/base/http_status.h"
#include "remoting/base/scoped_protobuf_http_request.h"
#include "remoting/proto/ftl/v1/ftl_messages.pb.h"
#include "remoting/signaling/ftl_services_context.h"
#include "remoting/signaling/signaling_tracker.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace remoting {
namespace {
using ::testing::_;
using ::testing::Expectation;
using ::testing::Invoke;
using ::testing::Property;
using ::testing::Return;
using ReceiveMessagesResponseCallback = base::RepeatingCallback<void(
std::unique_ptr<ftl::ReceiveMessagesResponse>)>;
using StatusCallback = base::OnceCallback<void(const HttpStatus&)>;
class MockSignalingTracker : public SignalingTracker {
public:
MOCK_METHOD0(OnSignalingActive, void());
};
// Fake stream implementation to allow probing if a stream is closed by client.
class FakeScopedProtobufHttpRequest : public ScopedProtobufHttpRequest {
public:
FakeScopedProtobufHttpRequest()
: ScopedProtobufHttpRequest(base::DoNothing()) {}
FakeScopedProtobufHttpRequest(const FakeScopedProtobufHttpRequest&) = delete;
FakeScopedProtobufHttpRequest& operator=(
const FakeScopedProtobufHttpRequest&) = delete;
~FakeScopedProtobufHttpRequest() override = default;
base::WeakPtr<FakeScopedProtobufHttpRequest> GetWeakPtr() {
return weak_factory_.GetWeakPtr();
}
private:
base::WeakPtrFactory<FakeScopedProtobufHttpRequest> weak_factory_{this};
};
std::unique_ptr<FakeScopedProtobufHttpRequest> CreateFakeServerStream() {
return std::make_unique<FakeScopedProtobufHttpRequest>();
}
// Creates a gmock EXPECT_CALL action that:
// 1. Creates a fake server stream and returns it as the start stream result
// 2. Posts a task to call |on_stream_opened| at the end of current sequence
// 3. Writes the WeakPtr to the fake server stream to |optional_out_stream|
// if it is provided.
template <typename OnStreamOpenedLambda>
decltype(auto) StartStream(OnStreamOpenedLambda on_stream_opened,
base::WeakPtr<FakeScopedProtobufHttpRequest>*
optional_out_stream = nullptr) {
return [=](base::OnceClosure on_channel_ready,
const ReceiveMessagesResponseCallback& on_incoming_msg,
StatusCallback on_channel_closed) {
auto fake_stream = CreateFakeServerStream();
if (optional_out_stream) {
*optional_out_stream = fake_stream->GetWeakPtr();
}
auto on_stream_opened_cb = base::BindLambdaForTesting(on_stream_opened);
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(on_stream_opened_cb, std::move(on_channel_ready),
on_incoming_msg, std::move(on_channel_closed)));
return fake_stream;
};
}
base::OnceClosure NotReachedClosure() {
return base::BindOnce([]() { NOTREACHED(); });
}
base::RepeatingCallback<void(const HttpStatus&)> NotReachedStatusCallback(
const base::Location& location) {
return base::BindLambdaForTesting([=](const HttpStatus& status) {
NOTREACHED() << "Location: " << location.ToString()
<< ", status code: " << static_cast<int>(status.error_code());
});
}
base::OnceCallback<void(const HttpStatus&)> CheckStatusThenQuitRunLoopCallback(
const base::Location& from_here,
HttpStatus::Code expected_status_code,
base::RunLoop* run_loop) {
return base::BindLambdaForTesting([=](const HttpStatus& status) {
ASSERT_EQ(expected_status_code, status.error_code())
<< "Incorrect status code. Location: " << from_here.ToString();
run_loop->QuitWhenIdle();
});
}
} // namespace
class FtlMessageReceptionChannelTest : public testing::Test {
public:
void SetUp() override;
void TearDown() override;
protected:
base::TimeDelta GetTimeUntilRetry() const;
int GetRetryFailureCount() const;
base::test::TaskEnvironment task_environment_{
base::test::TaskEnvironment::TimeSource::MOCK_TIME};
std::unique_ptr<FtlMessageReceptionChannel> channel_;
base::MockCallback<FtlMessageReceptionChannel::StreamOpener>
mock_stream_opener_;
base::MockCallback<base::RepeatingCallback<void(const ftl::InboxMessage&)>>
mock_on_incoming_msg_;
MockSignalingTracker mock_signaling_tracker_;
};
void FtlMessageReceptionChannelTest::SetUp() {
channel_ =
std::make_unique<FtlMessageReceptionChannel>(&mock_signaling_tracker_);
channel_->Initialize(mock_stream_opener_.Get(), mock_on_incoming_msg_.Get());
}
void FtlMessageReceptionChannelTest::TearDown() {
channel_.reset();
task_environment_.FastForwardUntilNoTasksRemain();
}
base::TimeDelta FtlMessageReceptionChannelTest::GetTimeUntilRetry() const {
return channel_->GetReconnectRetryBackoffEntryForTesting()
.GetTimeUntilRelease();
}
int FtlMessageReceptionChannelTest::GetRetryFailureCount() const {
return channel_->GetReconnectRetryBackoffEntryForTesting().failure_count();
}
TEST_F(FtlMessageReceptionChannelTest,
TestStartReceivingMessages_StoppedImmediately) {
base::RunLoop run_loop;
EXPECT_CALL(mock_stream_opener_, Run(_, _, _))
.WillOnce(StartStream(
[&](base::OnceClosure on_channel_ready,
const ReceiveMessagesResponseCallback& on_incoming_msg,
StatusCallback on_channel_closed) {
channel_->StopReceivingMessages();
run_loop.Quit();
}));
channel_->StartReceivingMessages(NotReachedClosure(),
NotReachedStatusCallback(FROM_HERE));
run_loop.Run();
}
TEST_F(FtlMessageReceptionChannelTest,
TestStartReceivingMessages_NotAuthenticated) {
base::RunLoop run_loop;
EXPECT_CALL(mock_stream_opener_, Run(_, _, _))
.WillOnce(StartStream(
[&](base::OnceClosure on_channel_ready,
const ReceiveMessagesResponseCallback& on_incoming_msg,
StatusCallback on_channel_closed) {
std::move(on_channel_closed)
.Run(HttpStatus(HttpStatus::Code::UNAUTHENTICATED, ""));
}));
channel_->StartReceivingMessages(
NotReachedClosure(),
CheckStatusThenQuitRunLoopCallback(
FROM_HERE, HttpStatus::Code::UNAUTHENTICATED, &run_loop));
run_loop.Run();
}
TEST_F(FtlMessageReceptionChannelTest,
TestStartReceivingMessages_StreamStarted) {
base::RunLoop run_loop;
EXPECT_CALL(mock_stream_opener_, Run(_, _, _))
.WillOnce(StartStream(
[&](base::OnceClosure on_channel_ready,
const ReceiveMessagesResponseCallback& on_incoming_msg,
StatusCallback on_channel_closed) {
std::move(on_channel_ready).Run();
}));
channel_->StartReceivingMessages(run_loop.QuitClosure(),
NotReachedStatusCallback(FROM_HERE));
run_loop.Run();
}
TEST_F(FtlMessageReceptionChannelTest,
TestStartReceivingMessages_RecoverableStreamError) {
base::RunLoop run_loop;
base::WeakPtr<FakeScopedProtobufHttpRequest> old_stream;
EXPECT_CALL(mock_stream_opener_, Run(_, _, _))
.WillOnce(StartStream(
[&](base::OnceClosure on_channel_ready,
const ReceiveMessagesResponseCallback& on_incoming_msg,
StatusCallback on_channel_closed) {
// The first open stream attempt fails with UNAVAILABLE error.
ASSERT_EQ(0, GetRetryFailureCount());
std::move(on_channel_closed)
.Run(HttpStatus(HttpStatus::Code::UNAVAILABLE, ""));
ASSERT_EQ(1, GetRetryFailureCount());
ASSERT_NEAR(FtlServicesContext::kBackoffInitialDelay.InSecondsF(),
GetTimeUntilRetry().InSecondsF(), 0.5);
// This will make the channel reopen the stream.
task_environment_.FastForwardBy(GetTimeUntilRetry());
},
&old_stream))
.WillOnce(StartStream(
[&](base::OnceClosure on_channel_ready,
const ReceiveMessagesResponseCallback& on_incoming_msg,
StatusCallback on_channel_closed) {
// Second open stream attempt succeeds.
// Assert old stream closed.
ASSERT_FALSE(old_stream);
std::move(on_channel_ready).Run();
ASSERT_EQ(0, GetRetryFailureCount());
}));
channel_->StartReceivingMessages(run_loop.QuitClosure(),
NotReachedStatusCallback(FROM_HERE));
run_loop.Run();
}
TEST_F(FtlMessageReceptionChannelTest,
TestStartReceivingMessages_MultipleCalls) {
base::RunLoop run_loop;
base::MockCallback<base::OnceClosure> stream_ready_callback;
// Exits the run loop iff the callback is called three times with OK.
EXPECT_CALL(stream_ready_callback, Run())
.WillOnce(Return())
.WillOnce(Return())
.WillOnce([&]() { run_loop.Quit(); });
EXPECT_CALL(mock_stream_opener_, Run(_, _, _))
.WillOnce(StartStream(
[&](base::OnceClosure on_channel_ready,
const ReceiveMessagesResponseCallback& on_incoming_msg,
StatusCallback on_channel_closed) {
std::move(on_channel_ready).Run();
}));
channel_->StartReceivingMessages(stream_ready_callback.Get(),
NotReachedStatusCallback(FROM_HERE));
channel_->StartReceivingMessages(stream_ready_callback.Get(),
NotReachedStatusCallback(FROM_HERE));
channel_->StartReceivingMessages(stream_ready_callback.Get(),
NotReachedStatusCallback(FROM_HERE));
run_loop.Run();
}
TEST_F(FtlMessageReceptionChannelTest, StreamsTwoMessages) {
base::RunLoop run_loop;
constexpr char kMessage1Id[] = "msg_1";
constexpr char kMessage2Id[] = "msg_2";
ftl::InboxMessage message_1;
message_1.set_message_id(kMessage1Id);
ftl::InboxMessage message_2;
message_2.set_message_id(kMessage2Id);
EXPECT_CALL(mock_on_incoming_msg_,
Run(Property(&ftl::InboxMessage::message_id, kMessage1Id)))
.WillOnce(Return());
EXPECT_CALL(mock_on_incoming_msg_,
Run(Property(&ftl::InboxMessage::message_id, kMessage2Id)))
.WillOnce(Invoke([&](const ftl::InboxMessage&) { run_loop.Quit(); }));
EXPECT_CALL(mock_stream_opener_, Run(_, _, _))
.WillOnce(StartStream(
[&](base::OnceClosure on_channel_ready,
const ReceiveMessagesResponseCallback& on_incoming_msg,
StatusCallback on_channel_closed) {
std::move(on_channel_ready).Run();
auto response = std::make_unique<ftl::ReceiveMessagesResponse>();
*response->mutable_inbox_message() = message_1;
on_incoming_msg.Run(std::move(response));
response = std::make_unique<ftl::ReceiveMessagesResponse>();
*response->mutable_inbox_message() = message_2;
on_incoming_msg.Run(std::move(response));
const HttpStatus kCancel(HttpStatus::Code::CANCELLED, "Cancelled");
std::move(on_channel_closed).Run(kCancel);
}));
channel_->StartReceivingMessages(
base::DoNothing(),
CheckStatusThenQuitRunLoopCallback(
FROM_HERE, HttpStatus::HttpStatus::Code::CANCELLED, &run_loop));
run_loop.Run();
}
TEST_F(FtlMessageReceptionChannelTest, ReceivedOnePong_OnSignalingActiveTwice) {
base::RunLoop run_loop;
base::MockCallback<base::OnceClosure> stream_ready_callback;
EXPECT_CALL(mock_signaling_tracker_, OnSignalingActive())
.WillOnce(Return())
.WillOnce([&]() { run_loop.Quit(); });
EXPECT_CALL(mock_stream_opener_, Run(_, _, _))
.WillOnce(StartStream(
[&](base::OnceClosure on_channel_ready,
const ReceiveMessagesResponseCallback& on_incoming_msg,
StatusCallback on_channel_closed) {
std::move(on_channel_ready).Run();
auto response = std::make_unique<ftl::ReceiveMessagesResponse>();
response->mutable_pong();
on_incoming_msg.Run(std::move(response));
}));
channel_->StartReceivingMessages(base::DoNothing(),
NotReachedStatusCallback(FROM_HERE));
run_loop.Run();
}
TEST_F(FtlMessageReceptionChannelTest, NoPongWithinTimeout_ResetsStream) {
base::RunLoop run_loop;
base::WeakPtr<FakeScopedProtobufHttpRequest> old_stream;
EXPECT_CALL(mock_stream_opener_, Run(_, _, _))
.WillOnce(StartStream(
[&](base::OnceClosure on_channel_ready,
const ReceiveMessagesResponseCallback& on_incoming_msg,
StatusCallback on_channel_closed) {
std::move(on_channel_ready).Run();
task_environment_.FastForwardBy(
FtlMessageReceptionChannel::kPongTimeout);
ASSERT_EQ(1, GetRetryFailureCount());
ASSERT_NEAR(FtlServicesContext::kBackoffInitialDelay.InSecondsF(),
GetTimeUntilRetry().InSecondsF(), 0.5);
// This will make the channel reopen the stream.
task_environment_.FastForwardBy(GetTimeUntilRetry());
},
&old_stream))
.WillOnce(StartStream(
[&](base::OnceClosure on_channel_ready,
const ReceiveMessagesResponseCallback& on_incoming_msg,
StatusCallback on_channel_closed) {
// Stream is reopened.
// Assert old stream closed.
ASSERT_FALSE(old_stream);
std::move(on_channel_ready).Run();
ASSERT_EQ(0, GetRetryFailureCount());
run_loop.Quit();
}));
channel_->StartReceivingMessages(base::DoNothing(),
NotReachedStatusCallback(FROM_HERE));
run_loop.Run();
}
TEST_F(FtlMessageReceptionChannelTest, ServerClosesStream_ResetsStream) {
base::RunLoop run_loop;
base::WeakPtr<FakeScopedProtobufHttpRequest> old_stream;
EXPECT_CALL(mock_stream_opener_, Run(_, _, _))
.WillOnce(StartStream(
[&](base::OnceClosure on_channel_ready,
const ReceiveMessagesResponseCallback& on_incoming_msg,
StatusCallback on_channel_closed) {
auto fake_server_stream = CreateFakeServerStream();
std::move(on_channel_ready).Run();
// Close the stream with OK.
std::move(on_channel_closed).Run(HttpStatus::OK());
},
&old_stream))
.WillOnce(StartStream(
[&](base::OnceClosure on_channel_ready,
const ReceiveMessagesResponseCallback& on_incoming_msg,
StatusCallback on_channel_closed) {
ASSERT_FALSE(old_stream);
std::move(on_channel_ready).Run();
ASSERT_EQ(0, GetRetryFailureCount());
run_loop.Quit();
}));
channel_->StartReceivingMessages(base::DoNothing(),
NotReachedStatusCallback(FROM_HERE));
run_loop.Run();
}
TEST_F(FtlMessageReceptionChannelTest, TimeoutIncreasesToMaximum) {
base::RunLoop run_loop;
int failure_count = 0;
int hitting_max_delay_count = 0;
EXPECT_CALL(mock_stream_opener_, Run(_, _, _))
.WillRepeatedly(StartStream(
[&](base::OnceClosure on_channel_ready,
const ReceiveMessagesResponseCallback& on_incoming_msg,
StatusCallback on_channel_closed) {
// Quit if delay is ~kBackoffMaxDelay three times.
if (hitting_max_delay_count == 3) {
std::move(on_channel_ready).Run();
ASSERT_EQ(0, GetRetryFailureCount());
run_loop.Quit();
return;
}
// Otherwise send UNAVAILABLE to reset the stream.
std::move(on_channel_closed)
.Run(HttpStatus(HttpStatus::HttpStatus::Code::UNAVAILABLE, ""));
int new_failure_count = GetRetryFailureCount();
ASSERT_LT(failure_count, new_failure_count);
failure_count = new_failure_count;
base::TimeDelta time_until_retry = GetTimeUntilRetry();
base::TimeDelta max_delay_diff =
time_until_retry - FtlServicesContext::kBackoffMaxDelay;
// Adjust for fuzziness.
if (max_delay_diff.magnitude() < base::Milliseconds(500)) {
hitting_max_delay_count++;
}
// This will tail-recursively call the stream opener.
task_environment_.FastForwardBy(time_until_retry);
}));
channel_->StartReceivingMessages(base::DoNothing(),
NotReachedStatusCallback(FROM_HERE));
run_loop.Run();
}
TEST_F(FtlMessageReceptionChannelTest,
StartStreamFailsWithUnRecoverableErrorAndRetry_TimeoutApplied) {
base::RunLoop run_loop;
base::WeakPtr<FakeScopedProtobufHttpRequest> old_stream;
EXPECT_CALL(mock_stream_opener_, Run(_, _, _))
.WillOnce(StartStream(
[&](base::OnceClosure on_channel_ready,
const ReceiveMessagesResponseCallback& on_incoming_msg,
StatusCallback on_channel_closed) {
// The first open stream attempt fails with UNAUTHENTICATED error.
ASSERT_EQ(0, GetRetryFailureCount());
std::move(on_channel_closed)
.Run(HttpStatus(HttpStatus::HttpStatus::Code::UNAUTHENTICATED,
""));
ASSERT_EQ(1, GetRetryFailureCount());
ASSERT_NEAR(FtlServicesContext::kBackoffInitialDelay.InSecondsF(),
GetTimeUntilRetry().InSecondsF(), 0.5);
},
&old_stream))
.WillOnce(StartStream(
[&](base::OnceClosure on_channel_ready,
const ReceiveMessagesResponseCallback& on_incoming_msg,
StatusCallback on_channel_closed) {
// Second open stream attempt succeeds.
// Assert old stream closed.
ASSERT_FALSE(old_stream);
ASSERT_EQ(1, GetRetryFailureCount());
std::move(on_channel_ready).Run();
ASSERT_EQ(0, GetRetryFailureCount());
}));
channel_->StartReceivingMessages(
base::DoNothing(),
base::BindLambdaForTesting([&](const HttpStatus& status) {
ASSERT_EQ(HttpStatus::HttpStatus::Code::UNAUTHENTICATED,
status.error_code());
channel_->StartReceivingMessages(run_loop.QuitClosure(),
NotReachedStatusCallback(FROM_HERE));
}));
run_loop.Run();
}
} // namespace remoting
|