Repository navigation
Expand file tree
/
Copy pathconnection_engine.cpp
More file actions
837 lines (782 loc) · 32.7 KB
/
Copy pathconnection_engine.cpp
File metadata and controls
837 lines (782 loc) · 32.7 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
/*
This file is part of libhttpserver
Copyright (C) 2011-2026 Sebastiano Merlino
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the file
LICENSE in the distribution; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA
*/
// Connection-engine lifecycle, coordination, and the transport loops
// (reader, writer). The route loop and the exchange sinks live in
// connection_engine_request.cpp. See connection_engine.hpp for the
// design contract.
#include "config.h"
#include <httpserver/detail/connection_engine.hpp>
#include <httpserver/detail/http2_tcp_owner.hpp>
#ifdef NATIVE_V3_TLS
#include <httpserver/detail/tls_socket_backend.hpp>
#endif
#include <algorithm>
#include <array>
#include <memory>
#include <string>
#include <utility>
#include <httpserver/detail/drain_scope.hpp>
#include <httpserver/detail/diagnostics_access.hpp>
#include <httpserver/http/outcome.hpp>
namespace httpserver {
namespace detail {
connection_engine::connection_engine(io_socket_backend& backend, worker_pool& pool,
const server::route_registry& routes,
const server::hook_bus& hooks,
const server::resource_budget& budget,
drain_scope& scope,
connection_engine_config config,
std::uint64_t id,
stopped_callback on_stopped,
net::peer_address peer,
const server::peer_policy* peers,
std::shared_ptr<io_socket_backend> transport,
connection_admission admission)
: admission_(std::move(admission)),
transport_(std::move(transport)),
backend_(transport_ ? *transport_ : backend),
handshaking_(static_cast<bool>(transport_)),
precounted_(admission_.seat && admission_.seat->owns()),
pool_(pool),
routes_(routes),
hooks_(hooks),
owner_(pool),
budget_(budget),
tail_charge_(budget, server::resource::body_buffer_bytes),
scope_(scope),
config_(std::move(config)),
id_(id),
on_stopped_(std::move(on_stopped)),
peer_(peer),
peers_(peers),
parser_(config_.head, budget),
outbox_(config_.outbox, budget) {
if (config_.pages == nullptr) {
// The v2 default pages serve when the options carried no
// custom factories.
config_.pages = std::make_shared<const error_page_factories>();
}
if (precounted_ && !admission_.retirement) scope_.enter();
}
connection_engine::~connection_engine() {
if (precounted_ && !started_ && !admission_.retirement) scope_.leave();
}
void connection_engine::observe(server::diagnostic_kind kind, std::uint64_t stream, http::outcome_code code, server::diagnostic_reason reason, std::optional<http::protocol> protocol) const noexcept {
server::diagnostic_event event{kind, reason, code};
event.protocol = protocol;
event.connection_id = id_;
event.stream_id = stream;
diagnostics_access::record(config_.diagnostics, event);
}
void connection_engine::observe_stream_end(const exchange& routed, std::uint64_t sequence) const noexcept {
if (routed.disconnected()) {
observe(server::diagnostic_kind::stream_cancelled, sequence, routed.disconnect_reason().code(), server::diagnostic_reason::local_stop, routed.head().request_protocol);
} else {
observe(server::diagnostic_kind::stream_completed, sequence, http::outcome_code::ok, server::diagnostic_reason::none, routed.head().request_protocol);
}
}
void connection_engine::observe_failure(http::outcome_code code, server::resource kind) noexcept {
if (diagnostic_failure_recorded_.exchange(true)) return;
server::diagnostic_event event{
code == http::outcome_code::limit_exceeded ? server::diagnostic_kind::resource_refused : server::diagnostic_kind::protocol_failure,
code == http::outcome_code::limit_exceeded ? server::diagnostic_reason::capacity : server::diagnostic_reason::malformed_input, code};
event.connection_id = id_;
event.resource_kind = kind;
diagnostics_access::record(config_.diagnostics, event);
}
void connection_engine::start() {
{
std::lock_guard<std::mutex> lock(mu_);
if (started_) return;
started_ = true;
live_loops_ = handshaking_ ? 1 : 4;
}
if (!precounted_ && !budget_.reserve(server::resource::connections, 1, seat_).ok()) {
observe(server::diagnostic_kind::connection_rejected, 0, http::outcome_code::limit_exceeded, server::diagnostic_reason::capacity);
// Budget exhaustion: no response (the accept path closes the
// transport); report the stop so the record is erased.
backend_.release_connection(id_);
stopped_callback done;
{
std::lock_guard<std::mutex> lock(mu_);
live_loops_ = 0;
done = std::move(on_stopped_);
}
if (done) done();
return;
}
// The engine's counted unit spans its whole live window; the drain
// completion condition rides on it (finalize drops it only after
// every loop finished and the writer flushed).
observe(server::diagnostic_kind::connection_accepted);
if (!precounted_) scope_.enter();
if (handshaking_) {
auto self = shared_from_this();
spawn(pool_, handshake_loop(self), [self](task_result<void>) { self->loop_finished(); });
return;
}
start_http1();
}
void connection_engine::start_http1() {
std::shared_ptr<connection_engine> self = shared_from_this();
spawn(pool_, reader_loop(self),
[self](task_result<void>) { self->loop_finished(); });
spawn(pool_, writer_loop(self),
[self](task_result<void>) { self->loop_finished(); });
spawn(pool_, route_loop(self),
[self](task_result<void>) { self->loop_finished(); });
spawn(pool_, watchdog_loop(self),
[self](task_result<void>) { self->loop_finished(); });
}
task<void> connection_engine::handshake_loop(std::shared_ptr<connection_engine> self) {
#ifdef NATIVE_V3_TLS
tls_handshake_operation operation(self->owner_, self->id_,
std::chrono::steady_clock::now() + self->config_.timeouts.handshake);
operation.submit(self->backend_);
const auto result = co_await operation;
auto& transport = static_cast<tls_socket_backend&>(self->backend_);
const auto protocol = transport.negotiated_protocol();
if (result.code != http::outcome_code::ok
|| (protocol != tls_negotiated_protocol::none && protocol != tls_negotiated_protocol::http1 && protocol != tls_negotiated_protocol::h2)) {
self->shutdown(result.code == http::outcome_code::ok ? http::outcome_code::not_supported : result.code);
co_return;
}
if (protocol == tls_negotiated_protocol::h2) {
std::shared_ptr<http2_tcp_owner> h2;
{
std::lock_guard lock(self->mu_);
if (self->shutdown_ || self->quiescing_) co_return;
self->tls_peer_ = transport.peer_metadata();
self->handshaking_ = false;
++self->live_loops_;
h2 = std::make_shared<http2_tcp_owner>(self->backend_, self->pool_, self->routes_, self->budget_, self->config_,
self->id_, self->peer_, self->peers_, self->hooks_, self->tls_peer_, [self] { self->loop_finished(); });
self->http2_ = h2;
}
h2->start();
co_return;
}
{
std::lock_guard lock(self->mu_);
if (self->shutdown_ || self->quiescing_) co_return;
self->tls_peer_ = transport.peer_metadata();
self->handshaking_ = false;
self->live_loops_ += 4;
}
self->start_http1();
#else
self->shutdown(http::outcome_code::not_supported);
#endif
co_return;
}
void connection_engine::shutdown(http::outcome_code reason) noexcept {
std::shared_ptr<http2_tcp_owner> h2;
{
std::lock_guard<std::mutex> lock(mu_);
if (shutdown_) return;
shutdown_ = true;
h2 = http2_;
}
if (h2) {
h2->stop(reason);
return;
}
fail_websocket({reason, reason == http::outcome_code::timeout
? "WebSocket drain deadline" : "WebSocket server stop"});
disconnect_current(http::outcome_code::connection_closed,
"http1 connection engine: server stop");
outbox_.abandon();
backend_.release_connection(id_);
wake_loops();
}
void connection_engine::quiesce(std::chrono::steady_clock::time_point server_deadline) noexcept {
std::shared_ptr<websocket_driver> driver;
std::shared_ptr<http2_tcp_owner> h2;
bool cancel_handshake = false;
{
std::lock_guard<std::mutex> lock(mu_);
if (shutdown_ || quiescing_) return;
quiescing_ = true;
cancel_handshake = handshaking_;
if (server_deadline != std::chrono::steady_clock::time_point::max()) server_drain_deadline_ = server_deadline;
driver = websocket_;
h2 = http2_;
if (!driver && !h2 && current_ == nullptr) close_after_drain_ = true;
}
if (h2) {
h2->drain(server_deadline);
return;
}
if (cancel_handshake) {
shutdown();
return;
}
if (driver) static_cast<void>(driver->begin_close(1001, "server drain"));
wake_loops();
rearm_watchdog();
}
bool connection_engine::running() const noexcept {
std::lock_guard<std::mutex> lock(mu_);
return live_loops_ > 0;
}
void connection_engine::wake_loops() noexcept {
static_cast<void>(backend_.wake());
}
void connection_engine::wake_loops_ordered() {
std::lock_guard<std::mutex> lock(mu_);
wake_loops();
}
void connection_engine::disconnect_current(http::outcome_code reason,
std::string detail) noexcept {
http1_body_source* body = nullptr;
{
std::lock_guard<std::mutex> lock(mu_);
if (current_ == nullptr) return;
static_cast<void>(current_->disconnect(reason, std::move(detail)));
// Only the admitted state can hold parked body reads (the
// decoder is unfed until admission).
if (gate_ == body_gate::admitted) body = body_.get();
}
// Second half of the body wake pairing (http1_body_source): the
// exchange's stop is sticky now, so a read parked before this
// moment wakes here and one parking later fails at its own gate.
if (body != nullptr) body->cancel_parked();
}
void connection_engine::request_close() noexcept {
{
std::lock_guard<std::mutex> lock(mu_);
close_after_drain_ = true;
}
wake_loops();
}
// -- reader side ------------------------------------------------------------
void connection_engine::absorb(std::string_view data) {
bool body_failed = false;
bool quota_failed = false;
bool drain_done = false;
note_transport_activity();
{
std::lock_guard<std::mutex> lock(mu_);
if (shutdown_) return;
const bool parking = !websocket_input_charge_.owns() && (phase_ != stream_phase::http || gate_ == body_gate::pending ||
gate_ == body_gate::admitted || head_routed_ || parser_.state() == http1_head_state::complete || !pending_tail_.empty());
quota_failed = parking && !tail_charge_.grow(3 * data.size());
if (quota_failed) {
close_after_drain_ = true;
} else if (phase_ != stream_phase::http) {
pending_tail_.append(data);
} else {
switch (gate_) {
case body_gate::none:
absorb_head_locked(data);
break;
case body_gate::pending:
absorb_pending_locked(data);
break;
case body_gate::admitted:
body_failed = absorb_admitted_locked(data);
break;
case body_gate::draining:
drain_done = absorb_drain_locked(data);
break;
}
}
release_tail_charge_locked();
}
if (quota_failed) {
disconnect_current(http::outcome_code::limit_exceeded, "shared HTTP/1 receive storage exhausted");
fail_websocket({http::outcome_code::limit_exceeded, "shared WebSocket transport storage exhausted"});
wake_loops();
}
if (drain_done) {
// The route loop's drain await re-checks, and the drain
// candidate leaves the watchdog's inventory.
wake_loops();
rearm_watchdog();
}
if (body_failed) {
observe_failure(http::outcome_code::protocol_error);
// A framing failure poisons the byte stream: unwind the live
// exchange and close per the decoder's posture.
disconnect_current(http::outcome_code::protocol_error,
"http1 connection engine: request body framing"
" failed");
request_close();
}
}
void connection_engine::emit_error(std::uint16_t code) {
stop_source cancel;
const std::uint64_t sequence = [this] {
std::lock_guard<std::mutex> lock(mu_);
return next_sequence_++;
}();
http1_response_sink& slot = outbox_.open(sequence, cancel.get_token());
http::request_head request;
request.request_protocol = http::protocol::http_1_1;
request.request_method = http::method::known(http::method_id::get);
request.raw_target = "/";
request.route_path = "/";
request.head_fields.append("Connection", "close");
http::fields fields;
fields.append("Content-Length", "0");
static_cast<void>(slot.start(request, http::status::from_code(code),
fields, config_.clock));
static_cast<void>(slot.push_end(http::fields()));
wake_loops_ordered();
request_close();
}
std::uint16_t connection_engine::error_code_for(
http::outcome_code code) noexcept {
if (code == http::outcome_code::limit_exceeded) return 431;
if (code == http::outcome_code::not_supported) return 501;
return 400;
}
bool connection_engine::stage_body(const http1_body_mode& mode) {
{
std::lock_guard<std::mutex> lock(mu_);
const auto needed = 3 * pending_tail_.size();
if (needed > tail_charge_.units() && !tail_charge_.grow(needed - tail_charge_.units())) return false;
body_ = std::make_unique<http1_body_source>(mode, config_.body, [weak = weak_from_this()] {
if (auto engine = weak.lock()) engine->wake_loops_ordered();
}, budget_);
gate_ = body_gate::pending;
// Include every reader byte received since head preparation. The
// owner and gate change together, so later absorbs append in order.
early_bytes_ = std::move(pending_tail_);
std::string().swap(pending_tail_);
}
// The reader may already be gated on the early cap (or becomes so
// now), and the watchdog's candidate set changed.
wake_loops();
rearm_watchdog();
return true;
}
bool connection_engine::admit_early_body() {
bool seed_failed = false;
{
std::lock_guard<std::mutex> lock(mu_);
// gate_ == none covers a bodyless request (no decoder exists);
// the transition runs exactly once per exchange.
if (gate_ != body_gate::pending) return true;
std::string seed = std::move(early_bytes_);
std::string().swap(early_bytes_);
if (body_ != nullptr && !seed.empty()) {
// Fed under mu_: the admitted absorb path holds the same
// lock, so socket bytes can never overtake the seed.
const std::size_t consumed = body_->feed(seed);
pending_tail_.assign(seed, consumed, seed.size() - consumed);
seed_failed = body_->failed();
}
gate_ = body_gate::admitted;
release_tail_charge_locked();
}
// The gated reader resumes, and body_idle may be nearer than
// whatever is armed.
wake_loops();
rearm_watchdog();
if (seed_failed) {
disconnect_current(http::outcome_code::protocol_error,
"http1 connection engine: request body framing"
" failed");
request_close();
return false;
}
return true;
}
void connection_engine::absorb_head_locked(std::string_view data) {
// A complete untaken head accepts nothing: park the bytes for the
// route loop (they are the body seed or the next head).
if (head_routed_ || parser_.state() == http1_head_state::complete) {
pending_tail_.append(data);
return;
}
if (!pending_tail_.empty()) {
std::string queued = std::move(pending_tail_);
pending_tail_.clear();
parser_.feed(queued);
if (parser_.state() == http1_head_state::complete) {
pending_tail_.append(data);
return;
}
}
parser_.feed(data);
}
void connection_engine::absorb_pending_locked(std::string_view data) {
// Never discard pre-admission bytes: they are this exchange's body
// prefix. The reader gate bounds the buffer at the staging cap
// (plus at most one read buffer of overshoot).
early_bytes_.append(data);
}
bool connection_engine::absorb_admitted_locked(std::string_view data) {
if (body_ == nullptr || body_->message_complete()) {
absorb_head_locked(data);
return false;
}
// The decoder keeps the unconsumed tail (its backpressure
// semantic); the reader re-feeds it ahead of every later chunk.
std::string combined;
combined.reserve(pending_tail_.size() + data.size());
combined.append(pending_tail_).append(data);
pending_tail_.clear();
const std::size_t consumed = body_->feed(combined);
pending_tail_.assign(combined, consumed, combined.size() - consumed);
return body_->failed();
}
bool connection_engine::absorb_drain_locked(std::string_view data) {
const std::size_t discard = static_cast<std::size_t>(
std::min<std::uint64_t>(drain_remaining_, data.size()));
drain_remaining_ -= discard;
data.remove_prefix(discard);
if (drain_remaining_ > 0) return false; // more counted bytes due
// The counted remainder is gone: anything past it is a pipelined
// next head, and the route loop's drain await observes the gate
// flip.
gate_ = body_gate::none;
drain_anchor_.reset();
if (!data.empty()) absorb_head_locked(data);
return true;
}
void connection_engine::release_tail_charge_locked() {
if (pending_tail_.empty()) std::string().swap(pending_tail_);
if (early_bytes_.empty()) std::string().swap(early_bytes_);
const auto retained = websocket_input_charge_.owns() ? 0 :
std::max(3 * (pending_tail_.size() + early_bytes_.size()),
(pending_tail_.empty() ? 0 : pending_tail_.capacity()) + (early_bytes_.empty() ? 0 : early_bytes_.capacity()));
if (tail_charge_.units() > retained) tail_charge_.shrink(tail_charge_.units() - retained);
}
bool connection_engine::reader_may_read_locked() const {
if (websocket_) {
return websocket_->snapshot().input_ready;
}
if (head_routed_ && gate_ == body_gate::none)
return pending_tail_.size() < config_.body.max_staged_bytes;
switch (gate_) {
case body_gate::none:
// A complete, untaken head plus no live exchange: parked
// pipelined bytes wait for the route loop, bounded at the
// same cap.
if (parser_.state() == http1_head_state::complete
&& current_ == nullptr) {
return pending_tail_.size() < config_.body.max_staged_bytes;
}
return true;
case body_gate::pending:
return early_bytes_.size() < config_.body.max_staged_bytes;
case body_gate::admitted:
return admitted_body_may_read_locked();
case body_gate::draining:
return true;
}
return true;
}
bool connection_engine::admitted_body_may_read_locked() const {
if (body_ == nullptr || body_->message_complete())
return pending_tail_.size() < config_.body.max_staged_bytes;
return pending_tail_.empty() && body_->staged_bytes() < config_.body.max_staged_bytes;
}
bool connection_engine::body_tail_ready_locked() const {
return gate_ == body_gate::admitted && body_ && !body_->message_complete()
&& !pending_tail_.empty() && body_->staged_bytes() < config_.body.max_staged_bytes;
}
void connection_engine::feed_body_tail() {
bool failed = false;
{
std::lock_guard<std::mutex> lock(mu_);
if (!shutdown_ && body_tail_ready_locked()) {
failed = absorb_admitted_locked({});
release_tail_charge_locked();
}
}
if (failed) {
disconnect_current(http::outcome_code::protocol_error, "request body framing failed");
request_close();
}
}
task<void> connection_engine::reader_loop(
std::shared_ptr<connection_engine> self) {
std::array<std::byte, k_read_buffer_bytes> buffer;
for (;;) {
self->feed_body_tail();
self->feed_websocket_tail();
wake_operation gate_op(self->owner_, self->id_);
const auto posture = self->reader_posture(gate_op);
if (posture == io_posture::stop) co_return;
if (posture == io_posture::retry) continue;
if (posture == io_posture::park) {
const io_result r = co_await std::move(gate_op);
if (r.code != http::outcome_code::ok) co_return;
continue;
}
read_operation op(self->owner_, self->id_, buffer);
if (!self->submit_read(op)) continue;
const io_result r = co_await std::move(op);
if (self->read_completed(r)) continue;
if (r.code == http::outcome_code::ok) {
self->absorb(std::string_view(
reinterpret_cast<const char*>(buffer.data()), r.transferred));
self->wake_loops();
continue;
}
self->handle_read_failure(r);
co_return;
}
}
// -- writer side ------------------------------------------------------------
bool connection_engine::outbox_drained() const {
return outbox_.empty() || outbox_.front_failed();
}
task<void> connection_engine::writer_loop(
std::shared_ptr<connection_engine> self) {
// The engine drives the socket writes itself (copy_front /
// write_operation / consume_front) so every completed write is
// visible as transport activity for the write-idle deadline.
std::array<std::byte, k_write_buffer_bytes> buffer;
for (;;) {
std::shared_ptr<websocket_driver> driver;
const std::size_t buffered = self->copy_transport_output(buffer, driver);
if (buffered == 0) {
wake_operation op(self->owner_, self->id_);
const auto posture = self->writer_posture(driver, op);
if (posture == io_posture::stop) co_return;
if (posture == io_posture::retry) continue;
const io_result r = co_await std::move(op);
if (r.code != http::outcome_code::ok) co_return;
continue;
}
write_operation op(self->owner_, self->id_,
std::span<const std::byte>(buffer.data(), buffered));
{
std::lock_guard lock(self->mu_);
if (self->shutdown_) co_return;
op.submit(self->backend_);
}
const io_result r = co_await std::move(op);
if (r.code != http::outcome_code::ok) {
self->fail_websocket({http::outcome_code::connection_closed, "WebSocket transport write failed"});
self->shutdown();
co_return;
}
// Publish write progress before consume_output delivers its observer,
// so a concurrent watchdog never sees an expired pre-write anchor.
self->note_transport_activity(true);
if (driver) static_cast<void>(driver->consume_output(r.transferred));
else self->outbox_.consume_front(r.transferred);
}
}
// -- coordination -----------------------------------------------------------
// -- watchdog ---------------------------------------------------------------
// True while the engine is decoding this exchange's body and the
// message boundary has not been reached (the body_idle candidate).
bool connection_engine::body_decode_pending_locked() const {
return gate_ == body_gate::admitted && body_ != nullptr
&& !body_->message_complete();
}
// The suspension candidate, anchored at first sight of the suspended
// exchange so the deadline cannot slide on later activity (TASK-109).
// A disconnected exchange arms nothing -- its handler is already
// unwinding, so no second enforcement window opens.
std::optional<std::chrono::steady_clock::time_point>
connection_engine::suspension_deadline_locked() {
if (phase_ != stream_phase::http || current_ == nullptr || !current_->suspended()
|| current_->disconnected()) {
suspension_anchor_.reset();
return std::nullopt;
}
if (!suspension_anchor_.has_value()) {
suspension_anchor_ = std::chrono::steady_clock::now();
}
return *suspension_anchor_ + config_.timeouts.suspension;
}
std::optional<std::chrono::steady_clock::time_point>
connection_engine::drain_deadline_locked() const {
if (gate_ != body_gate::draining || drain_remaining_ == 0
|| !drain_anchor_.has_value()) {
return std::nullopt;
}
return *drain_anchor_ + config_.timeouts.drain;
}
connection_engine::watchdog_plan connection_engine::plan_watchdog_locked() {
watchdog_plan plan;
if (watchdog_terminal_locked()) {
plan.exit = true;
return plan;
}
// Nearest-deadline order, as the contract promises: collect every
// candidate the current state offers and arm the minimum. A
// trickling body slides body_idle but never the suspension or
// drain anchors, so a suspended exchange and a stalled rejection
// drain both reach their deadlines; the sliding candidates still
// win whenever they are genuinely nearer. While an exchange is
// routed and no candidate applies, the plan defers -- the drain
// ticket's deadline (or a stop) bounds that window instead
// (TASK-110).
std::chrono::steady_clock::time_point candidates[7];
std::size_t candidate_count = 0;
if (body_decode_pending_locked()) {
candidates[candidate_count++] =
last_activity_ + config_.timeouts.body_idle;
}
if (phase_ == stream_phase::websocket) {
// Read admission identity and pending state atomically. A new interval
// survives drain/requeue even when neither observer saw empty output.
update_websocket_write_anchor_locked(websocket_->snapshot());
if (websocket_write_anchor_) {
candidates[candidate_count++] = *websocket_write_anchor_ + config_.timeouts.write_idle;
}
} else if (transport_output_pending_locked()) {
candidates[candidate_count++] = last_activity_ + config_.timeouts.write_idle;
} else {
websocket_write_anchor_.reset();
}
if (const std::optional<std::chrono::steady_clock::time_point>
suspended_until = suspension_deadline_locked()) {
candidates[candidate_count++] = *suspended_until;
}
if (const std::optional<std::chrono::steady_clock::time_point>
drain_until = drain_deadline_locked()) {
candidates[candidate_count++] = *drain_until;
}
add_protocol_deadlines_locked(candidates, candidate_count);
if (candidate_count == 0) {
if (head_routed_) {
plan.defer = true;
return plan;
}
plan.deadline = last_activity_ + config_.timeouts.header;
return plan;
}
plan.deadline = *std::min_element(candidates,
candidates + candidate_count);
return plan;
}
bool connection_engine::watchdog_due(
std::chrono::steady_clock::time_point deadline) {
std::lock_guard<std::mutex> lock(mu_);
const watchdog_plan plan = plan_watchdog_locked();
return !plan.exit && !plan.defer && plan.deadline == deadline
&& std::chrono::steady_clock::now() >= deadline;
}
void connection_engine::rearm_watchdog() noexcept {
std::shared_ptr<op_state> pending;
{
std::lock_guard<std::mutex> lock(mu_);
pending = pending_timer_;
}
if (pending != nullptr) {
static_cast<void>(backend_.request_cancel(*pending));
}
}
void connection_engine::note_transport_activity(bool written) {
{
std::lock_guard<std::mutex> lock(mu_);
last_activity_ = std::chrono::steady_clock::now();
if (written && phase_ == stream_phase::websocket) websocket_write_anchor_ = last_activity_;
}
rearm_watchdog();
}
void connection_engine::enforce_timeout(std::chrono::steady_clock::time_point deadline) noexcept {
bool global_expiry = false, close_expiry = false;
{
std::lock_guard<std::mutex> lock(mu_);
global_expiry = server_drain_deadline_ && *server_drain_deadline_ <= deadline;
if (websocket_) {
auto progress = websocket_->snapshot();
close_expiry = !progress.terminal && progress.closing_since &&
*progress.closing_since + config_.timeouts.ws_close <= deadline;
}
}
if (global_expiry && scope_.expire_if_due(std::chrono::steady_clock::now())) return;
// A fired deadline means the peer or the exchange will not
// progress. Disconnect the live exchange (its parked handler
// unwinds through run_route), mark the close, and release the
// transport so every parked loop terminal-completes. No response
// is synthesized: a timed-out peer is not reading one.
fail_websocket({http::outcome_code::timeout, close_expiry
? "WebSocket Close timeout" : "WebSocket watchdog timeout"});
disconnect_current(http::outcome_code::timeout,
"http1 connection engine: watchdog timeout");
{
std::lock_guard<std::mutex> lock(mu_);
close_after_drain_ = true;
}
backend_.release_connection(id_);
wake_loops();
}
task<void> connection_engine::watchdog_loop(
std::shared_ptr<connection_engine> self) {
for (;;) {
watchdog_plan plan;
{
std::lock_guard<std::mutex> lock(self->mu_);
plan = self->plan_watchdog_locked();
}
if (plan.exit) co_return;
const auto deadline = plan.defer
? std::chrono::steady_clock::now() + k_watchdog_tick
: plan.deadline;
timer_operation op(self->owner_, self->id_, deadline);
if (!self->arm_watchdog(op, plan)) continue;
const io_result r = co_await std::move(op);
{
std::lock_guard<std::mutex> lock(self->mu_);
self->pending_timer_.reset();
}
// A released transport ends the watchdog with the connection.
if (r.code == http::outcome_code::connection_closed) co_return;
// A cancellation (state moved) and a deferred re-check tick
// both re-plan with fresh eyes.
if (r.code != http::outcome_code::ok || plan.defer) continue;
// Fired: enforce only when the deadline still governs the
// current state (activity moved it -- re-arm).
if (!self->watchdog_due(deadline)) continue;
self->enforce_timeout(deadline);
co_return;
}
}
void connection_engine::loop_finished() {
{
std::lock_guard<std::mutex> lock(mu_);
if (live_loops_ > 0) --live_loops_;
if (live_loops_ > 0) return;
}
finalize();
}
void connection_engine::finalize() {
// The engine's counted unit drops first: by the time the listener
// erases its record, a drain waiting on the scope observes
// completion with every loop finished and the writer flushed.
{
std::lock_guard<std::mutex> lock(mu_);
body_.reset(); parser_ = http1_head_parser(config_.head);
std::string().swap(pending_tail_); std::string().swap(early_bytes_);
tail_charge_.shrink(tail_charge_.units());
websocket_input_charge_.release(); websocket_output_charge_.release(); websocket_message_charge_.release();
seat_.release(); outbox_.retire();
}
observe(server::diagnostic_kind::connection_closed);
if (!admission_.retirement) scope_.leave();
backend_.release_connection(id_);
stopped_callback done;
{
std::lock_guard<std::mutex> lock(mu_);
done = std::move(on_stopped_);
}
if (done) done();
}
} // namespace detail
} // namespace httpserver