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

libbitcoin / libbitcoin-network / 44447581389

19 Nov 2026 02:53AM UTC coverage: 94.065% (-0.002%) from 94.067%
44447581389

push

github

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

Hold small socket writes while more are queued, written as one.

103 of 112 new or added lines in 13 files covered. (91.96%)

1 existing line in 1 file now uncovered.

16104 of 17120 relevant lines covered (94.07%)

2221.01 hits per line

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

95.4
/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
48 ✔
49
{
50
    BC_ASSERT(stranded());
48 ✔
51

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

54
    const auto idle = queue_.empty() && deferred_.empty();
48 ✔
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() << "]");
1 ✔
62
            write_.handler(error::message_dropped, zero);
1 ✔
63
            return false;
1 ✔
64
        }
65

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

71
    backlog_ = system::ceilinged_add(backlog_, write_.cost);
46 ✔
72
    return true;
46 ✔
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
488 ✔
77
{
78
    BC_ASSERT(stranded());
488 ✔
79

80
    if (stopped())
488 ✔
81
    {
82
        // Does not queue new work or invoke handler after stop.
83
        LOGQ("Payload write abort [" << endpoint() << "]");
1 ✔
84
        return;
1 ✔
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)
487 ✔
90
    {
91
        if (!charge(write_))
47 ✔
92
            return;
93
    }
94
    else
95
    {
96
        write_.cost = zero;
440 ✔
97
    }
98

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

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

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

113
    // Invokes oldest writer on the queue, completion invokes handle_write.
114
    // Its writes are held for the next writer while another is queued.
115
    writing_ = true;
485 ✔
116
    socket_->hold(queue_.size() > one);
485 ✔
117
    queue_.front().call();
485 ✔
118
}
119

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

126
    // The last queued writer releases any writes that remain held.
127
    if (!stopped() && is_one(queue_.size()) && socket_->holding())
485 ✔
128
    {
NEW
129
        socket_->release(std::bind(&proxy::handle_write,
×
NEW
130
            shared_from_this(), ec, bytes));
×
NEW
131
        return;
×
132
    }
133

134
    // Handler precedes pop so that a handler send does not start a second
135
    // write loop (a non-empty queue defers the start to the pop below).
136
    const auto handler = std::move(queue_.front().handler);
485 ✔
137
    handler(ec, bytes);
485 ✔
138
    backlog_ = system::floored_subtract(backlog_, queue_.front().cost);
485 ✔
139
    queue_.pop_front();
485 ✔
140

141
    // All handlers must be invoked unless stopped, so continue despite code.
142
    if (!stopped())
485 ✔
143
        write();
424 ✔
144
}
485 ✔
145

146
// Throttle (sent bytes are allocated time at the configured rate).
147
// ----------------------------------------------------------------------------
148
// private
149
// Applied to every send, so the deferral delays the next queued write.
150

151
// Nanoseconds allocated to the transmission of bytes at the given rate.
152
inline steady_clock::duration to_allocation(size_t bytes,
4 ✔
153
    uint32_t rate) NOEXCEPT
154
{
155
    using namespace system;
156
    constexpr auto nanos = 1'000'000'000_u64;
157

158
    // Overflow implies an unusable rate/size, saturated at the type maximum.
159
    const auto span = ceilinged_multiply<uint64_t>(bytes, nanos) / rate;
4 ✔
160
    return nanoseconds{ limit<nanoseconds::rep>(span) };
4 ✔
161
}
162

163
count_handler proxy::counted(count_handler&& handler) NOEXCEPT
391 ✔
164
{
165
    return std::bind(&proxy::handle_counted,
782 ✔
166
        shared_from_this(), _1, _2, std::move(handler));
1,173 ✔
167
}
168

169
void proxy::count_received(size_t bytes) NOEXCEPT
557 ✔
170
{
171
    received_ = system::ceilinged_add(received_.load(), bytes);
557 ✔
172
}
557 ✔
173

174
void proxy::handle_counted(const code& ec, size_t bytes,
391 ✔
175
    const count_handler& handler) NOEXCEPT
176
{
177
    count_received(bytes);
391 ✔
178
    handler(ec, bytes);
391 ✔
179
}
391 ✔
180

181
count_handler proxy::metered(count_handler&& handler) NOEXCEPT
490 ✔
182
{
183
    // Stamped at issue, so that only transmission time is credited against
184
    // the allocation. Time spent idle between sends earns nothing.
185
    return std::bind(&proxy::handle_metered,
980 ✔
186
        shared_from_this(), _1, _2, steady_clock::now(), std::move(handler));
1,470 ✔
187
}
188

189
steady_clock::duration proxy::unconsumed(size_t bytes,
495 ✔
190
    const steady_clock::time_point& start) const NOEXCEPT
191
{
192
    BC_ASSERT(stranded());
495 ✔
193

194
    // Stop is never deferred, and a null throttle implies no rate limit.
195
    if (!throttle_ || stopped())
495 ✔
196
        return {};
491 ✔
197

198
    const auto allocated = to_allocation(bytes, rate_limit_);
4 ✔
199
    const auto consumed = steady_clock::now() - start;
4 ✔
200
    return consumed < allocated ? allocated - consumed :
4 ✔
201
        steady_clock::duration{};
1 ✔
202
}
203

204
void proxy::handle_metered(const code& ec, size_t bytes,
490 ✔
205
    const steady_clock::time_point& start,
206
    const count_handler& handler) NOEXCEPT
207
{
208
    BC_ASSERT(stranded());
490 ✔
209
    sent_ = system::ceilinged_add(sent_.load(), bytes);
980 ✔
210
    writing();
490 ✔
211
    writing_ = false;
490 ✔
212

213
    // A send that consumed its full allocation is not deferred.
214
    const auto delay = unconsumed(bytes, start);
490 ✔
215
    if (is_zero(delay.count()))
490 ✔
216
    {
217
        handler(ec, bytes);
489 ✔
218
        return;
489 ✔
219
    }
220

221
    // Handler is posted to the strand, and fired by stop (canceled).
222
    throttle_->start(std::bind(&proxy::handle_charge,
1 ✔
223
        shared_from_this(), _1, ec, bytes, handler), delay);
2 ✔
224
}
225

226
void proxy::handle_charge(const code&, const code& ec, size_t bytes,
1 ✔
227
    const count_handler& handler) NOEXCEPT
228
{
229
    BC_ASSERT(stranded());
1 ✔
230

231
    // The timer code is discarded, as the send result is what is reported.
232
    handler(ec, bytes);
1 ✔
233
}
1 ✔
234

235
BC_POP_WARNING()
236
BC_POP_WARNING()
237
BC_POP_WARNING()
238

239
} // namespace network
240
} // 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