Repository navigation
Expand file tree
/
Copy pathnative_websocket_fixture.cpp
More file actions
172 lines (167 loc) · 8.06 KB
/
Copy pathnative_websocket_fixture.cpp
File metadata and controls
172 lines (167 loc) · 8.06 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
/*
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
*/
#include <algorithm>
#include <stdexcept>
#include <utility>
#include <vector>
#include <atomic>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>
#include <httpserver/server/server.hpp>
#include <httpserver/exchange.hpp>
#include <httpserver/concurrency/resume_signal.hpp>
namespace h = httpserver;
namespace {
std::mutex log_mu;
std::atomic<int> accepted{0}, closed{0};
h::resume_signal send_gate;
h::server::native_server* fixture_server = nullptr;
void event(const std::string& text) { std::lock_guard lock(log_mu); std::cout << text << std::endl; }
h::task<void> route(h::exchange& x) {
h::ws_upgrade_options options;
options.subprotocols = {"chat", "binary"};
options.allowed_origins = {"https://example.com"};
options.allow_absent_origin = true;
options.limits.max_message_bytes = 1048576;
options.limits.incoming_bytes = 1048576;
options.limits.incoming_messages = 1;
options.limits.output_bytes = 1048586;
options.limits.outgoing_messages = 1;
auto result = co_await x.upgrade(options);
if (!result.status.ok()) {
result.rejection_fields.append("Content-Length", "0");
result.rejection_fields.append("Connection", "close");
x.respond(result.rejection_status, result.rejection_fields);
event("REFUSED " + std::to_string(result.rejection_status.code()));
co_return;
}
++accepted; event("ACCEPT " + result.selected_subprotocol);
auto session = std::move(*result.session);
h::resume_signal close_gate;
session.on_close([close_gate](auto info) mutable { ++closed; close_gate.signal(); event("CLOSE " + std::to_string(info.clean) + " " + std::to_string(static_cast<int>(info.status.code()))); });
if (x.head().route_path == "/drain-handler") {
h::server::drain_ticket ticket;
auto begun = fixture_server->begin_drain(std::chrono::milliseconds(500), ticket);
h::server::drain_result report;
if (!begun.ok() || ticket.wait(report).code() != h::http::outcome_code::would_deadlock) throw std::runtime_error("handler drain contract");
event("DRAIN HANDLER would_deadlock");
}
if (x.head().route_path == "/app-close") session.close(1000, "local");
if (x.head().route_path == "/return") co_return;
if (x.head().route_path == "/throw") throw std::runtime_error("upgraded handler failure");
if (x.head().route_path == "/idle") {
event("IDLE");
co_await send_gate.wait_for(std::chrono::seconds(5));
const std::string text = "unsolicited";
session.try_send(h::websocket::message_kind::text,
{reinterpret_cast<const std::byte*>(text.data()), text.size()});
}
if (x.head().route_path == "/flood") {
std::vector<std::byte> payload(1048576);
for (unsigned i = 0; i < 64; ++i) {
std::fill(payload.begin(), payload.end(), std::byte(i));
for (;;) {
auto sent = session.try_send(h::websocket::message_kind::binary, payload);
if (sent.disposition == h::websocket::send_disposition::accepted) break;
if (sent.disposition == h::websocket::send_disposition::closed) {
event("SEND CLOSED"); co_return;
}
event("BLOCKED " + std::to_string(i));
auto room = co_await session.writable();
if (!room.ok()) {
event("WRITABLE CLOSED"); co_return;
}
event("RESUMED " + std::to_string(i));
}
}
event("SENT 64");
}
for (;;) {
auto message = co_await session.receive();
if (!message.value) {
// Retain the owning handle through the peer-close reply.
// Application close callback is separate from transport wake.
co_await close_gate.wait_for(std::chrono::seconds(5));
co_return;
}
auto& incoming = *message.value;
for (;;) {
auto sent = session.try_send(incoming.kind, incoming.data);
if (sent.disposition == h::websocket::send_disposition::accepted) break;
if (sent.disposition != h::websocket::send_disposition::backpressured) co_return;
if (!(co_await session.writable()).ok()) co_return;
}
}
}
} // namespace
int main() {
h::server::server_options options;
h::server::listener_options listener; listener.address = "127.0.0.1";
options.add_listener(listener); options.concurrency().workers = 2;
options.timeouts().header = std::chrono::milliseconds(100);
options.timeouts().ws_close = std::chrono::seconds(2);
if (!options.validate().ok()) return 2;
h::server::native_server server(std::move(options));
h::http::method_set get; get.set(h::http::method_id::get);
fixture_server = &server;
server.route(h::http::method::known(h::http::method_id::get), "/health", [](h::exchange& x) -> h::task<void> {
h::http::fields fields; fields.append("Content-Length", "4"); fields.append("Connection", "close");
x.start_response(h::http::status::from_code(200), fields);
const std::string body = "okay";
co_await x.writer().write({reinterpret_cast<const std::byte*>(body.data()), body.size()});
co_await x.writer().finish();
});
server.route(h::http::method::known(h::http::method_id::get), "/slow", [](h::exchange& x) -> h::task<void> {
h::http::fields fields; fields.append("Content-Length", "7"); fields.append("Connection", "close");
x.start_response(h::http::status::from_code(200), fields);
const std::string first = "old", last = "body";
co_await x.writer().write({reinterpret_cast<const std::byte*>(first.data()), first.size()});
h::resume_signal delay;
co_await delay.wait_for(std::chrono::milliseconds(100));
co_await x.writer().write({reinterpret_cast<const std::byte*>(last.data()), last.size()});
co_await x.writer().finish();
});
server.route_prefix(get, "/", route);
if (!server.listen().ok()) return 2;
event("READY " + std::to_string(server.get_bound_port(0)));
h::server::drain_ticket ticket;
std::string command;
while (std::getline(std::cin, command)) {
if (command == "STOP") break;
if (command == "DRAIN" || command == "DRAIN-DROP" || command == "DRAIN-LATE") {
auto begun = server.begin_drain(std::chrono::milliseconds(250), ticket);
if (!begun.ok()) return 3;
event("DRAIN START");
if (command == "DRAIN-DROP") {
ticket = h::server::drain_ticket{};
continue;
}
if (command == "DRAIN-LATE") std::this_thread::sleep_for(std::chrono::milliseconds(400));
h::server::drain_result result;
if (!ticket.wait(result).ok()) return 3;
event(std::string("DRAIN RESULT ") +
(result.status == h::server::drain_status::completed ? "completed" : "expired") +
" " + std::to_string(result.remaining));
}
if (command == "SEND") send_gate.signal();
if (command == "STATS") event("STATS " + std::to_string(accepted.load()) + " " + std::to_string(closed.load()));
}
server.request_stop(); server.stop(); event("STOPPED");
}