• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

libbitcoin / libbitcoin-network / 35674182343

22 Sep 2026 01:00AM UTC coverage: 48.562% (+0.06%) from 48.498%
35674182343

push

github

web-flow
Merge pull request #910 from evoskuil/master

Queue all response writes and drop the gate from channel sends, refactor.

54 of 131 new or added lines in 5 files covered. (41.22%)

262 existing lines in 13 files now uncovered.

28079 of 57821 relevant lines covered (48.56%)

163480.57 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

90.91
/src/net/proxy_queue.cpp
1
/**
2
 * Copyright (c) 2011-2026 libbitcoin developers
3
 *
4
 * This file is part of libbitcoin.
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU Affero General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU Affero General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Affero General Public License
17
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
 */
19
#include <bitcoin/network/net/proxy.hpp>
20

21
#include <bitcoin/network/define.hpp>
22
#include <bitcoin/network/log/log.hpp>
23

24
// stackoverflow.com/questions/7754695/boost-asio-async-write-how-to-not-
25
// interleaving-async-write-calls
26

27
namespace libbitcoin {
28
namespace network {
29

30
// Shared pointers required in handler parameters so closures control lifetime.
31
BC_PUSH_WARNING(NO_VALUE_OR_CONST_REF_SHARED_PTR)
32
BC_PUSH_WARNING(SMART_PTR_NOT_NEEDED)
33
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
34

35
using namespace std::placeholders;
36

37
// Send cycle (send continues until queue is empty).
38
// ----------------------------------------------------------------------------
39
// private
40

41
// The memory of a queue entry apart from its payload: the writer closure with
42
// its bound pointers, the queue slot, control blocks and the message object.
43
// This bounds queue depth implicitly, as a flood of small messages is charged
44
// its estimated cost, not its smaller wire size.
45
constexpr size_t entry_size = 256;
46

47
// Charges the entry against the backlog, false if refused.
48
bool proxy::charge(pending& write_) NOEXCEPT
13 ✔
49
{
50
    BC_ASSERT(stranded());
13 ✔
51

52
    write_.cost = system::ceilinged_add(write_.cost, entry_size);
26 ✔
53

54
    const auto idle = queue_.empty() && deferred_.empty();
13 ✔
55
    if (!idle && system::ceilinged_add(backlog_, write_.cost) >
3 ✔
56
        maximum_backlog_)
3 ✔
57
    {
58
        // zeromq messages are seuqenced, so drops are acceptable.
59
        if (socket_->zeromq())
2 ✔
60
        {
61
            LOGS("Dropped message on congested channel [" << endpoint() << "]");
3 ✔
62
            write_.handler(error::message_dropped, zero);
1 ✔
63
            return false;
1 ✔
64
        }
65

66
        LOGS("Stopping congested channel [" << endpoint() << "]");
3 ✔
67
        stop(error::channel_backlog);
1 ✔
68
        return false;
1 ✔
69
    }
70

71
    backlog_ = system::ceilinged_add(backlog_, write_.cost);
11 ✔
72
    return true;
11 ✔
73
}
74

75
// A bound entry is an lvalue, moved to the queue from its binding.
76
void proxy::do_write(pending& write_, bool notification) NOEXCEPT
31 ✔
77
{
78
    BC_ASSERT(stranded());
31 ✔
79

80
    if (stopped())
31 ✔
81
    {
82
        // Does not queue new work or invoke handler after stop.
83
        LOGQ("Payload write abort [" << endpoint() << "]");
15 ✔
84
        return;
5 ✔
85
    }
86

87
    // A solicited write (response) is paced by the request that provoked it.
88
    // A notification must be charged as recipient can force accumulation.
89
    if (notification)
26 ✔
90
    {
91
        if (!charge(write_))
13 ✔
92
            return;
93
    }
94
    else
95
    {
96
        write_.cost = zero;
13 ✔
97
    }
98

99
    const auto started = !queue_.empty();
100
    queue_.push_back(std::move(write_));
24 ✔
101

102
    // Start the asynchronous loop if it wasn't already started.
103
    if (!started)
24 ✔
104
        write();
23 ✔
105
}
106

107
void proxy::write() NOEXCEPT
40 ✔
108
{
109
    BC_ASSERT(stranded());
40 ✔
110
    if (queue_.empty())
40 ✔
111
        return;
112

113
    // Invokes oldest writer on the queue, completion invokes handle_write.
114
    writing_ = true;
23 ✔
115
    queue_.front().call();
23 ✔
116
}
117

118
void proxy::handle_write(const code& ec, size_t bytes) NOEXCEPT
23 ✔
119
{
120
    BC_ASSERT(stranded());
23 ✔
121
    if (queue_.empty())
23 ✔
UNCOV
122
        return;
×
123

124
    // Handler precedes pop so that a handler send does not start a second
125
    // write loop (a non-empty queue defers the start to the pop below).
126
    const auto handler = std::move(queue_.front().handler);
23 ✔
127
    handler(ec, bytes);
23 ✔
128
    backlog_ = system::floored_subtract(backlog_, queue_.front().cost);
23 ✔
129
    queue_.pop_front();
23 ✔
130

131
    // All handlers must be invoked unless stopped, so continue despite code.
132
    if (!stopped())
23 ✔
133
        write();
17 ✔
134
}
135

136
// Throttle (sent bytes are allocated time at the configured rate).
137
// ----------------------------------------------------------------------------
138
// private
139
// Applied to every send, queued or not, so that the deferral is imposed
140
// without imposing the queue (http is half duplex, so it is not queued).
141

142
// Nanoseconds allocated to the transmission of bytes at the given rate.
143
inline steady_clock::duration to_allocation(size_t bytes,
144
    uint32_t rate) NOEXCEPT
145
{
146
    using namespace system;
147
    constexpr auto nanos = 1'000'000'000_u64;
148

149
    // Overflow implies an unusable rate/size, saturated at the type maximum.
150
    const auto span = ceilinged_multiply<uint64_t>(bytes, nanos) / rate;
3 ✔
151
    return nanoseconds{ limit<nanoseconds::rep>(span) };
3 ✔
152
}
153

154
count_handler proxy::counted(count_handler&& handler) NOEXCEPT
20 ✔
155
{
156
    return std::bind(&proxy::handle_counted,
40 ✔
157
        shared_from_this(), _1, _2, std::move(handler));
40 ✔
158
}
159

160
void proxy::count_received(size_t bytes) NOEXCEPT
30 ✔
161
{
162
    received_ = system::ceilinged_add(received_.load(), bytes);
163
}
30 ✔
164

165
void proxy::handle_counted(const code& ec, size_t bytes,
20 ✔
166
    const count_handler& handler) NOEXCEPT
167
{
168
    count_received(bytes);
20 ✔
169
    handler(ec, bytes);
20 ✔
170
}
20 ✔
171

172
count_handler proxy::metered(count_handler&& handler) NOEXCEPT
23 ✔
173
{
174
    // Stamped at issue, so that only transmission time is credited against
175
    // the allocation. Time spent idle between sends earns nothing.
176
    return std::bind(&proxy::handle_metered,
46 ✔
177
        shared_from_this(), _1, _2, steady_clock::now(), std::move(handler));
69 ✔
178
}
179

180
steady_clock::duration proxy::unconsumed(size_t bytes,
28 ✔
181
    const steady_clock::time_point& start) const NOEXCEPT
182
{
183
    BC_ASSERT(stranded());
28 ✔
184

185
    // Stop is never deferred, and a null throttle implies no rate limit.
186
    if (!throttle_ || stopped())
28 ✔
187
        return {};
25 ✔
188

189
    const auto allocated = to_allocation(bytes, rate_limit_);
3 ✔
190
    const auto consumed = steady_clock::now() - start;
3 ✔
191
    return consumed < allocated ? allocated - consumed :
3 ✔
192
        steady_clock::duration{};
1 ✔
193
}
194

195
void proxy::handle_metered(const code& ec, size_t bytes,
23 ✔
196
    const steady_clock::time_point& start,
197
    const count_handler& handler) NOEXCEPT
198
{
199
    BC_ASSERT(stranded());
23 ✔
200
    sent_ = system::ceilinged_add(sent_.load(), bytes);
201
    writing();
23 ✔
202
    writing_ = false;
23 ✔
203

204
    // A send that consumed its full allocation is not deferred.
205
    const auto delay = unconsumed(bytes, start);
23 ✔
206
    if (is_zero(delay.count()))
23 ✔
207
    {
208
        handler(ec, bytes);
23 ✔
209
        return;
23 ✔
210
    }
211

212
    // Handler is posted to the strand, and fired by stop (canceled).
UNCOV
213
    throttle_->start(std::bind(&proxy::handle_charge,
×
UNCOV
214
        shared_from_this(), _1, ec, bytes, handler), delay);
×
215
}
216

UNCOV
217
void proxy::handle_charge(const code&, const code& ec, size_t bytes,
×
218
    const count_handler& handler) NOEXCEPT
219
{
UNCOV
220
    BC_ASSERT(stranded());
×
221

222
    // The timer code is discarded, as the send result is what is reported.
UNCOV
223
    handler(ec, bytes);
×
UNCOV
224
}
×
225

226
BC_POP_WARNING()
227
BC_POP_WARNING()
228
BC_POP_WARNING()
229

230
} // namespace network
231
} // namespace libbitcoin
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc