forked from rsocket/rsocket-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKeepaliveTimer.cpp
More file actions
69 lines (58 loc) · 1.67 KB
/
KeepaliveTimer.cpp
File metadata and controls
69 lines (58 loc) · 1.67 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
// Copyright 2004-present Facebook. All Rights Reserved.
#include "rsocket/internal/KeepaliveTimer.h"
namespace rsocket {
KeepaliveTimer::KeepaliveTimer(
std::chrono::milliseconds period,
folly::EventBase& eventBase)
: eventBase_(eventBase),
generation_(std::make_shared<uint32_t>(0)),
period_(period) {}
KeepaliveTimer::~KeepaliveTimer() {
stop();
}
std::chrono::milliseconds KeepaliveTimer::keepaliveTime() {
return period_;
}
void KeepaliveTimer::schedule() {
auto scheduledGeneration = *generation_;
auto generation = generation_;
eventBase_.runAfterDelay(
[this, generation, scheduledGeneration]() {
if (*generation == scheduledGeneration) {
sendKeepalive();
}
},
static_cast<uint32_t>(keepaliveTime().count()));
}
void KeepaliveTimer::sendKeepalive() {
if (pending_) {
// Make sure connection_ is not deleted (via external call to stop)
// while we still mid-operation
auto localPtr = connection_;
stop();
// TODO: we need to use max lifetime from the setup frame for this
localPtr->disconnectOrCloseWithError(
Frame_ERROR::connectionError("no response to keepalive"));
} else {
connection_->sendKeepalive();
pending_ = true;
schedule();
}
}
// must be called from the same thread as start
void KeepaliveTimer::stop() {
*generation_ += 1;
pending_ = false;
connection_ = nullptr;
}
// must be called from the same thread as stop
void KeepaliveTimer::start(const std::shared_ptr<FrameSink>& connection) {
connection_ = connection;
*generation_ += 1;
DCHECK(!pending_);
schedule();
}
void KeepaliveTimer::keepaliveReceived() {
pending_ = false;
}
}