-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
397 lines (342 loc) · 17.5 KB
/
main.cpp
File metadata and controls
397 lines (342 loc) · 17.5 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
#include "ManapiHttp.hpp"
#include "include/ManapiFetch2.hpp"
// #include "ext/pq/AsyncPostgreClient.hpp"
#ifdef _WIN32
# define FOLDER ".\\data\\"
# define FOLDER2 ".\\data\\"
#else
#define FOLDER "/home/Timur/Downloads/anime-main/"
#define FOLDER2 "/home/Timur/Documents/http2priorities/"
#endif
#include <cstring>
#include "handlers.hpp"
#include "crypto/ManapiAEAD.hpp"
#include "hash/ManapiSHA256.hpp"
#include "ManapiInitTools.hpp"
#include "ManapiMath.hpp"
#include "ManapiProcess.hpp"
#include "ManapiString.hpp"
#include "std/ManapiAsyncTimer.hpp"
#include "std/ManapiEasyCancellation.hpp"
#include "ext/ManapiMustache.hpp"
#include "protobuf/helloworld.grpc.pb.h"
#include "ManapiGrpc.hpp"
#include "include/std/ManapiFunction.hpp"
//
#include "ext/pq/AsyncPostgreClient.hpp"
#include "std/ManapiRef.hpp"
static std::atomic<std::size_t> bbbb = 0;
// Logic and data behind the server's behavior.
class GreeterServiceImpl final : public helloworld::Greeter::CallbackService {
grpc::ServerUnaryReactor *SayHello(grpc::CallbackServerContext* context, const helloworld::HelloRequest* request,
helloworld::HelloReply* reply) override {
grpc::ServerUnaryReactor* reactor = context->DefaultReactor();
manapi::async::run ([reactor, reply, request] () -> manapi::future<> {
manapi::ctoken check_timeout;
check_timeout.cancel_callback([] () -> void {
std::cout << (size_t)bbbb << " IS TOO SLOW\n";
});
check_timeout.timeout(7000);
try {
bbbb.fetch_add(1);
auto status = co_await manapi::net::fetch2::fetch ("https://localhost:8887/stat",{
{"http", "1.1"},
{"verify_peer", false},
{"verify_host", false}
}, manapi::ctokens::timeout(2000));
if (status.ok()) {
auto response = status.unwrap();
if (response->ok()) {
reply->set_message(std::format("Hello, {}! Fact: {}", request->name(), (co_await response->text()).unwrap()));
}
else {
reply->set_message(std::format("Hello, {}! Something gets wrong. status: {}", request->name(), response->status()));
}
}
else {
reply->set_message(std::format("Hello, {}! Something gets wrong. status: {}", request->name(), status.message()));
}
}
catch (std::exception const &e) {
reply->set_message(std::format("Hello, {}! Something gets wrong: {}", request->name(), e.what()));
}
bbbb.fetch_sub(1);
check_timeout.disable();
reactor->Finish(grpc::Status::OK);
});
return reactor;
}
};
class GreeterClient {
public:
GreeterClient(std::shared_ptr<grpc::Channel> channel)
: stub_(helloworld::Greeter::NewStub(channel)) {}
// Assembles the client's payload, sends it and presents the response back
// from the server.
manapi::future<manapi::status_or<std::string>> SayHello(const std::string& user) {
typedef manapi::async::promise_sync<manapi::status_or<std::string>> promise;
// Data we are sending to the server.
helloworld::HelloRequest request;
request.set_name(user);
// Container for the data we expect from the server.
helloworld::HelloReply reply;
// Context for the client. It could be used to convey extra information to
// the server and/or tweak certain RPC behaviors.
grpc::ClientContext context;
co_return co_await promise ([&] (promise::resolve_t resolve) -> void {
try {
this->stub_->async()->SayHello(&context, &request, &reply, [ctx = manapi::async::current(), &reply, resolve = std::move(resolve)] (grpc::Status status) mutable {
if (manapi::async::internal::current_() == ctx) {
if (status.ok()) {
resolve(reply.message());
return;
}
auto msg = status.error_message();
manapi_log_debug("grpc client failed due to %s", msg.data());
resolve(manapi::status_internal("grpc client: something gets wrong"));
}
else {
ctx->eventloop()->custom_callback([resolve = std::move(resolve), status = std::move(status), &reply] (manapi::event_loop *ev) -> void {
if (status.ok()) {
resolve(reply.message());
return;
}
auto msg = status.error_message();
manapi_log_debug("grpc client failed due to %s", msg.data());
resolve(manapi::status_internal("grpc client: something gets wrong"));
}).unwrap();
}
});
}
catch (std::exception const &e) {
manapi_log_error(e.what());
resolve(manapi::status_internal("sayhello failed"));
}
});
}
private:
std::unique_ptr<helloworld::Greeter::Stub> stub_;
};
int main () {
manapi::init_tools::log_name_enable("manapihttp", true);
manapi::init_tools::log_name_enable("manapihttp::fs", true);
int logtrace = 4;
try { logtrace = std::stoi(manapi::process::get_env("MANAPIHTTP_LOGTRACE").unwrap()); }
catch (...) { }
manapi::init_tools::log_trace_init((manapi::debug::trace_level)logtrace);
int threads = 4;
try { threads = std::stoi(manapi::process::get_env("MANAPIHTTP_THREADS").unwrap()); }
catch (...) { }
manapi::async::context::threadpoolfs(threads);
manapi::async::context::gbs(manapi::async::context::blockedsignals());
int loops = 0;
try { loops = std::stoi(manapi::process::get_env("MANAPIHTTP_LOOPS").unwrap()); }
catch (...) { }
auto ctx = manapi::async::context::create(loops + 1).unwrap();
std::atomic<int> a = 0;
std::atomic<int> thrcnt = 0;
auto grpc_server_ctx = manapi::net::wgrpc::server_ctx::create().unwrap();
auto server_ctx = manapi::net::http::server_ctx::create().unwrap();
grpc_server_ctx->enable_threadpool(true);
grpc::EnableDefaultHealthCheckService(true);
grpc::reflection::InitProtoReflectionServerBuilderPlugin();
ctx->run(loops, [&thrcnt, &a, server_ctx,grpc_server_ctx] (const std::function<void()> &bind) -> void {
using http = manapi::net::http::server;
// auto db = manapi::ext::pq::connection::create().unwrap();
// /**
// * grpc
// */
//
// auto thrcntind = thrcnt.fetch_add(1);
//
// auto service = std::make_shared<GreeterServiceImpl>();
//
// auto grpc_server = manapi::net::wgrpc::server::create (grpc_server_ctx).unwrap();
// manapi::async::run([grpc_server, service, thrcntind] () mutable -> manapi::future<> {
// auto res = co_await grpc_server.config("/home/Timur/Desktop/WorkSpace/ManapiHTTP/cmake-build-debug/grpc.json");
//
// res.log();
//
// res = co_await grpc_server.start([&] (grpc::ServerBuilder &builder) -> manapi::status {
// builder.RegisterService(service.get());
// return manapi::status_ok();
// });
//
// res.log();
// assert(res.ok());
// if (res.ok()) {
// auto creds = co_await manapi::net::wgrpc::secure_channel_credentials("/home/Timur/Documents/ssl/quic/cert.crt");
// if (!creds.ok()) {
// creds.err().log();
// co_return;
// }
// auto greeter = std::make_shared<GreeterClient>(grpc::CreateChannel("localhost:8080", creds.unwrap()));
// manapi::async::current()->timerpool()->append_interval_async(100, [greeter] (const manapi::timer &t) -> manapi::future<> {
// std::string user = "Xiadnoring Client #1";
// auto res = co_await greeter->SayHello(user);
// if (res.ok())
// std::cout << "Xiadnoring Client#1 =" << res.unwrap() << "\n";
// else
// res.err().log();
// });
// manapi::async::current()->timerpool()->append_interval_async(100, [greeter] (const manapi::timer &t) -> manapi::future<> {
// std::string user = "Xiadnoring Client #2";
// auto res = co_await greeter->SayHello(user);
// if (res.ok())
// std::cout << "Xiadnoring Client #2=" << res.unwrap() << "\n";
// else
// res.err().log();
// });
// manapi::async::current()->timerpool()->append_interval_async(100, [greeter] (const manapi::timer &t) -> manapi::future<> {
// std::string user = "Xiadnoring Client #3";
// auto res = co_await greeter->SayHello(user);
// if (res.ok())
// std::cout << "Xiadnoring Client #3=" << res.unwrap() << "\n";
// else
// res.err().log();
// });
// manapi::async::current()->timerpool()->append_interval_async(100, [greeter] (const manapi::timer &t) -> manapi::future<> {
// std::string user = "Xiadnoring Client #4";
// auto res = co_await greeter->SayHello(user);
// if (res.ok())
// std::cout << "Xiadnoring Client #4=" << res.unwrap() << "\n";
// else
// res.err().log();
// });
// manapi::async::current()->timerpool()->append_interval_async(100, [greeter] (const manapi::timer &t) -> manapi::future<> {
// std::string user = "Xiadnoring Client #5";
// auto res = co_await greeter->SayHello(user);
// if (res.ok())
// std::cout << "Xiadnoring Client #5=" << res.unwrap() << "\n";
// else
// res.err().log();
// });
// manapi::async::current()->timerpool()->append_interval_async(100, [greeter] (const manapi::timer &t) -> manapi::future<> {
// std::string user = "Xiadnoring Client #6";
// auto res = co_await greeter->SayHello(user);
// if (res.ok())
// std::cout << "Xiadnoring Client #6=" << res.unwrap() << "\n";
// else
// res.err().log();
// });
// }
//
// }, [] (std::exception_ptr err) -> void {
// if (err)
// std::rethrow_exception(err);
// });
/**
* http
*/
auto folder_env = manapi::process::get_env("MANAPIHTTP_FOLDER");
std::string const folder = folder_env ? FOLDER : FOLDER2;
auto router = manapi::net::http::server::create (server_ctx).unwrap();
router->GET("/+layer", [] (http::req &req, http::uresp resp) -> void {
resp->header(std::string{"alt-svc"}, R"(h3=":8888"; ma=86400)");
resp.finish();
}).unwrap();
router->GET("/stat", [server_ctx, &a] (http::req &req, http::resp &resp) mutable -> manapi::future<> {
co_return resp.text(std::format("ip: {} port: {} online: {} requests: {}",
req.ip_data().ip,
req.ip_data().port,
server_ctx->storage().as<manapi::net::http::server_ctx::worker_data_t>()->count.load(),
a.load())).unwrap();
}).unwrap();
router->GET("/timeout/[sec]", [] (http::req &req, http::resp &resp) mutable -> manapi::future<> {
auto tmsec = std::atoi(req.param("sec").unwrap().data());
co_await manapi::async::delay (tmsec * 1000, req.cancellation().sub());
co_return resp.text(std::format("Wait {} seconds", tmsec)).unwrap();
}).unwrap();
router->GET ("/main", [&a] (manapi::net::http::request &req, manapi::net::http::uresponse resp)
-> void {
a.fetch_add(1);
resp->text("");
resp.finish();
}).unwrap();
router->POST("/trailer", [] (http::req &req, http::resp &resp) -> manapi::future<void> {
auto data = (co_await req.text()).unwrap();
auto trailers = (co_await req.trailers()).unwrap();
for (auto &trailer : trailers)
printf("%.*s\n", trailer.second.size(), trailer.second.data());
resp.text("hello");
}, {
{"trailers", manapi::json::array({"test", "HMMM"})},
{"trailers_size", 500}
});
router->GET ("/fetch/+custom", [&a] (manapi::net::http::request &req, manapi::net::http::response &resp)
-> manapi::future<> {
auto path = std::vector<std::string> (std::next(req.path().begin()), req.path().end());
std::string url = "";
for (auto &p : path) {
url += '/';
url += p;
}
auto response = (co_await manapi::net::fetch2::fetch(std::format("https://localhost:8885/{}", url), {
{"verify_peer", false},
{"verify_host", false},
{"verbose", true},
{"http", "2"},
{"headers", {
{"user-agent", R"(Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36)"}
}}
}, req.cancellation().sub().tm(3000))).unwrap();
if (!response->ok()) {
co_return resp.text(std::string{manapi::net::http::status_to_string(response->status()).unwrap()}).unwrap();
}
co_return resp.text((co_await response->text()).unwrap()).unwrap();
}).unwrap();
router->GET ("/stop", [] (http::req &req, manapi::net::http::uresponse resp) mutable -> void {
resp->text("OK");
manapi::async::run (manapi::async::current()->stop());
resp.finish();
}).unwrap();
router->GET ("/timer", [&a] (manapi::net::http::request &req, manapi::net::http::uresponse resp)
-> void {
manapi::async::current()->timerpool()->append_timer_sync(1500,
[resp = std::move(resp)] (manapi::timer t) mutable -> void {
resp.finish();
}).unwrap();
}).unwrap();
// router->GET("/pq/[id]", [db](manapi::net::http::request& req, manapi::net::http::response& resp) mutable -> manapi::future<> {
// auto msg = req.param("id").unwrap();
// char *end;
// auto res1 = co_await db.exec("INSERT INTO for_test (id, str_col) VALUES ($2, $1);","no way", std::strtoll(msg.data(), &end, 10));
// if (!res1) {
// if (res1.sqlcode() != manapi::ext::pq::SQL_STATE_UNIQUE_VIOLATION)
// res1.err().log();
// }
//
// auto res = co_await db.exec("SELECT * FROM for_test;");
// if (res) {
// std::string content = "b";
// for (const auto &row: res.unwrap()) {
// content += std::to_string(row["id"].as<int>()) + " - " + row["str_col"].as<std::string>() + "<hr/>";
// }
//
// co_return resp.text(std::move(content)).unwrap();
// }
//
// co_return resp.text(std::string{res.is_sqlerr() ? res.sqlmsg() : res.message()}).unwrap();
// }).unwrap();
router->GET ("/free", [&a] (manapi::net::http::request &req, manapi::net::http::response &resp)
-> manapi::future<> {
manapi::init_tools::ev_library_init();
manapi::async::current()->memory_fabric().clear();
resp.compress_enabled(false);
co_return resp.text(std::format("requests: {}; active: {}", a.load(),
resp.connection_data()->worker->worker_data()->as<manapi::net::http::server_ctx::worker_data_t>()->count.load())).unwrap();
}).unwrap();
init_http_server (router, folder);
manapi::async::run([router/*, db*/] () mutable -> manapi::future<> {
//(co_await db.connect("127.0.0.1", "7879", "development", "rv8FY--PHz_QV<wvT4=n_Ru+cUJE}>KCqmBj9&#M3\\\"Gb.tx", "workflow-main")).unwrap();
(co_await router->config("/home/Timur/Desktop/WorkSpace/ManapiHTTP/cmake-build-debug/config.json")).unwrap();
(co_await router->start()).unwrap();
manapi_log_trace(manapi::debug::LOG_TRACE_HIGH, "http server has been started");
});
bind();
}).unwrap();
manapi::clear_tools::curl_library_clear();
manapi::clear_tools::ev_library_clear();
manapi::clear_tools::ssl_library_clear();
return 0;
}