-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSyncEngine.cpp
More file actions
100 lines (88 loc) · 2.19 KB
/
Copy pathSyncEngine.cpp
File metadata and controls
100 lines (88 loc) · 2.19 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
93
94
95
96
97
98
99
100
/**
*
* @file SyncEngine.cpp
* @author Gaspard Kirira
*
* Copyright 2025, Gaspard Kirira. All rights reserved.
* https://github.com/vixcpp/vix
* Use of this source code is governed by a MIT license
* that can be found in the License file.
*
* Vix.cpp
*
*/
#include <vix/sync/engine/SyncEngine.hpp>
#include <chrono>
namespace vix::sync::engine
{
static std::int64_t now_ms()
{
using namespace std::chrono;
return duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
}
SyncEngine::SyncEngine(
Config cfg,
std::shared_ptr<vix::sync::outbox::Outbox> outbox,
std::shared_ptr<vix::net::NetworkProbe> probe,
std::shared_ptr<ISyncTransport> transport)
: cfg_(cfg),
outbox_(std::move(outbox)),
probe_(std::move(probe)),
transport_(std::move(transport))
{
workers_.reserve(cfg_.worker_count);
for (std::size_t i = 0; i < cfg_.worker_count; ++i)
{
SyncWorker::Config wc;
wc.batch_limit = cfg_.batch_limit;
wc.idle_sleep_ms = cfg_.idle_sleep_ms;
wc.offline_sleep_ms = cfg_.offline_sleep_ms;
wc.inflight_timeout_ms = cfg_.inflight_timeout_ms;
workers_.push_back(std::make_unique<SyncWorker>(wc, outbox_, probe_, transport_));
}
}
SyncEngine::~SyncEngine()
{
stop();
}
std::size_t SyncEngine::tick(std::int64_t t_ms)
{
std::size_t total = 0;
for (auto &w : workers_)
{
total += w->tick(t_ms);
}
return total;
}
void SyncEngine::start()
{
if (running_.exchange(true))
return;
thread_ = std::thread([this]
{ run_loop_(); });
}
void SyncEngine::stop()
{
if (!running_.exchange(false))
return;
if (thread_.joinable())
thread_.join();
}
void SyncEngine::run_loop_()
{
while (running_.load())
{
const auto t = now_ms();
const auto processed = tick(t);
const auto sleep_ms = (processed == 0) ? cfg_.idle_sleep_ms : 0;
if (sleep_ms > 0)
{
std::this_thread::sleep_for(std::chrono::milliseconds(sleep_ms));
}
else
{
std::this_thread::yield();
}
}
}
} // namespace vix::sync::engine