-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathsimulated_socket.cpp
More file actions
92 lines (77 loc) · 2.94 KB
/
Copy pathsimulated_socket.cpp
File metadata and controls
92 lines (77 loc) · 2.94 KB
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
////////////////////////////////////////////////////////////////////////////////
// Distributed under the Boost Software License, Version 1.0. //
// (See accompanying file LICENSE or copy at //
// https://www.boost.org/LICENSE_1_0.txt) //
////////////////////////////////////////////////////////////////////////////////
#include "networking/simulated_socket.h"
#include <chrono>
#include <cstddef>
#include <optional>
#include <random>
#include <thread>
#include "core/context.h"
#include "core/random.h"
#include "jobs/concurrent_queue.h"
#include "jobs/job.h"
#include "jobs/job_system_manager.h"
#include "log/log.h"
using namespace std::chrono_literals;
namespace iris
{
SimulatedSocket::SimulatedSocket(
Context &context,
std::chrono::milliseconds delay,
std::chrono::milliseconds jitter,
float drop_rate,
Socket *socket)
: delay_(delay)
, jitter_(jitter)
, drop_rate_(drop_rate)
, socket_(socket)
{
// in order to facilitate message delay without blocking we have write()
// enqueue data with a time point, this job then grabs them and can wait
// until the delay has passed before sending
context.jobs_manager().add({[this]()
{
for (;;)
{
if (write_queue_.empty())
{
std::this_thread::sleep_for(10ms);
}
else
{
const auto &[buffer, time_point] = write_queue_.dequeue();
// wait until its time to send the data
std::this_thread::sleep_until(time_point);
socket_->write(buffer);
}
}
}});
}
SimulatedSocket::~SimulatedSocket() = default;
std::optional<DataBuffer> SimulatedSocket::try_read(std::size_t count)
{
return socket_->try_read(count);
}
DataBuffer SimulatedSocket::read(std::size_t count)
{
return socket_->read(count);
}
void SimulatedSocket::write(const DataBuffer &buffer)
{
if (!flip_coin(drop_rate_))
{
const auto jitter =
random_int32(static_cast<std::int32_t>(-jitter_.count()), static_cast<std::int32_t>(jitter_.count()));
// stick the data to be sent on the queue (with the delay time) and
const auto delay = delay_ + std::chrono::milliseconds(jitter);
write_queue_.enqueue(buffer, std::chrono::steady_clock::now() + delay);
}
}
void SimulatedSocket::write(const std::byte *data, std::size_t size)
{
write({data, data + size});
}
}