Debian Codegraph @

src/unittest/coro.cpp

raw symbols SCIP
1 #include <thread>
2 #include <atomic>
3 #include <algorithm>
4
5 #include "test.h"
6
7 #ifndef DPP_NO_CORO
8
9 namespace {
10
11 namespace std_coroutine = dpp::detail::std_coroutine;
12
13 template <size_t N>
14 struct test_exception : std::exception {
15 };
16
17 std::atomic<int> exceptions_caught = 0;
18
19 std::array<std::atomic<int>, 10> job_data;
20 std::array<std::atomic<int>, 10> task_data;
21
22
23 struct simple_awaitable {
24 test_t &test_for;
25 volatile int value{};
26 int result{};
27
28 bool await_ready() const noexcept {
29 return false;
30 }
31
32 template <typename T>
33 void await_suspend(std_coroutine::coroutine_handle<T> handle) {
34 std::thread th([this, handle]() mutable {
35 auto *test = &test_for;
36 std::this_thread::sleep_for(std::chrono::seconds(5));
37 result = value;
38 try {
39 handle.resume();
40 } catch (const std::exception &) {
41 /* no exception should be caught */
42 set_status(*test, ts_failed, "unexpected exception during resume");
43 }
44 });
45 th.detach();
46 }
47
48 int await_resume() const noexcept {
49 return result;
50 }
51 };
52
53 void sync_awaitable_fun(std::function<void(int)> callback) {
54 callback(42);
55 }
56
57 void sync_awaitable_throw(std::function<void(int)> callback) {
58 throw test_exception<0>{};
59 }
60
61 void async_awaitable_wait5(std::function<void(int)> callback) {
62 std::thread th([cc = std::move(callback)]() noexcept {
63 std::this_thread::sleep_for(std::chrono::seconds(5));
64 cc(69);
65 });
66 th.detach();
67 }
68
69 struct job_awaitable {
70 volatile int value{};
71 int result{};
72
73 bool await_ready() const noexcept {
74 return false;
75 }
76
77 template <typename T>
78 void await_suspend(std_coroutine::coroutine_handle<T> handle) {
79 std::thread th([this, handle]() mutable {
80 std::this_thread::sleep_for(std::chrono::seconds(5));
81 result = value;
82 try {
83 handle.resume();
84 } catch (const test_exception<42> &) {
85 /* intended exception to catch. we should have 2, one for the job_data test, one for the top-level job test */
86 int exceptions = ++exceptions_caught;
87 if (exceptions == 2) {
88 set_status(CORO_JOB_OFFLINE, ts_success);
89 } else if (exceptions > 2) {
90 set_status(CORO_JOB_OFFLINE, ts_failed, "resume() threw more than expected");
91 }
92 } catch (const std::exception &) {
93 /* anything else should not be caught */
94 set_status(CORO_JOB_OFFLINE, ts_failed, "resume() threw an exception it shouldn't have");
95 }
96 });
97 th.detach();
98 }
99
100 int await_resume() const noexcept {
101 return result;
102 }
103 };
104
105 dpp::job job_offline_test() {
106 if (int ret = co_await job_awaitable{42}; ret != 42) {
107 set_status(CORO_JOB_OFFLINE, ts_failed, "failed simple awaitable");
108 }
109 std::array<dpp::job, 10> jobs;
110 for (int i = 0; i < 10; ++i) {
111 jobs[i] = [](int i) -> dpp::job {
112 static std::atomic<bool> passed = false;
113 if (int ret = co_await job_awaitable{i}; ret != i) {
114 set_status(CORO_JOB_OFFLINE, ts_failed, "failed in-loop awaitable");
115 }
116 job_data[i] = i;
117 for (int j = 0; j < 10; ++j) {
118 if (job_data[j] != j) {
119 co_return;
120 }
121 }
122 if (passed.exchange(true) == true) { // another thread came here and already passed this check, skip the exception
123 co_return;
124 }
125 throw test_exception<42>(); // should be caught by simple_awaitable (since this is after resume)
126 }(i);
127 }
128 if (std::find_if(job_data.begin(), job_data.end(), [](int i){ return i > 0; }) != job_data.end()) {
129 set_status(CORO_JOB_OFFLINE, ts_failed, "job should not have modified the data at this point");
130 }
131
132 // verify that exceptions work as expected (dpp::job throws uncaught exceptions immediately to the caller / resumer)
133 try {
134 []() -> dpp::job {
135 throw test_exception<1>{};
136 }();
137 } catch (const test_exception<1> &) {
138 throw test_exception<42>{}; // should be caught by simple_awaitable (since this is after resume)
139 }
140 }
141
142 dpp::task<void> task_offline_test() {
143 namespace time = std::chrono;
144 using clock = time::system_clock;
145 static auto &test = CORO_TASK_OFFLINE;
146
147 if (int ret = co_await simple_awaitable{test, 42}; ret != 42) {
148 set_status(test, ts_failed, "failed simple awaitable");
149 }
150
151 if (int ret = co_await []() -> dpp::task<int> { co_return 42; }(); ret != 42) {
152 set_status(test, ts_failed, "failed simple task");
153 }
154
155 std::array<dpp::task<int>, 10> tasks;
156 auto start = clock::now();
157 for (int i = 0; i < 10; ++i) {
158 tasks[i] = [](int i) -> dpp::task<int> {
159 if (int ret = co_await simple_awaitable{test, i}; ret != i) {
160 set_status(test, ts_failed, "failed in-loop awaitable");
161 }
162 job_data[i] = i;
163 co_return i;
164 }(i);
165 }
166 for (int i = 0; i < 10; ++i) {
167 if (co_await tasks[i] != i) {
168 set_status(test, ts_failed, "failed to co_await expected value");
169 }
170 }
171 auto diff = clock::now() - start;
172 if (diff > time::seconds(10)) { // task is async so 10 parallel tasks should all take 5 seconds + some overhead
173 set_status(test, ts_failed, "parallel tasks took longer than expected");
174 }
175
176 // verify that exceptions work as expected (dpp::task throws uncaught exceptions to co_await-er)
177 dpp::task task1;
178 dpp::task task2;
179 try {
180 task1 = []() -> dpp::task<void> { // throws after co_await
181 if (int ret = co_await simple_awaitable{test, 69}; ret != 69) {
182 set_status(test, ts_failed, "nested failed simple awaitable");
183 }
184 dpp::task task2 = []() -> dpp::task<void> {
185 co_await std_coroutine::suspend_never{}; // needed to make sure the task is initialized properly
186 throw test_exception<1>{};
187 }();
188 co_await task2;
189 }();
190 task2 = []() -> dpp::task<void> { // throws immediately
191 co_await std_coroutine::suspend_never{}; // needed to make sure the task is initialized properly
192 throw test_exception<2>{};
193 }();
194 } catch (const std::exception &e) {
195 /* SHOULD NOT throw. exceptions are sent when resuming from co_await */
196 set_status(test, ts_failed, "task threw in constructor");
197 }
198
199 bool success = false;
200 // test throw after co_await
201 try {
202 co_await task1;
203 } catch (const test_exception<1> &) {
204 success = true;
205 }
206 if (!success) {
207 set_status(CORO_TASK_OFFLINE, ts_failed, "task failed to throw expected test_exception<1>");
208 }
209 success = false;
210 // test throw without suspending
211 try {
212 co_await task2;
213 }
214 catch (const test_exception<2> &) {
215 success = true;
216 }
217 if (!success) {
218 set_status(CORO_TASK_OFFLINE, ts_failed, "task failed to throw expected test_exception<2>");
219 }
220 // test cancel (throws dpp::task_cancelled_exception)
221 auto task3 = []() -> dpp::task<void> {
222 auto make_task = []() -> dpp::task<void> {
223 for (int i = 0; i < 5; ++i) {
224 co_await dpp::async<int>(&async_awaitable_wait5);
225 }
226 set_status(CORO_TASK_OFFLINE, ts_failed, "failed to cancel nested task");
227 };
228 std::array<dpp::task<void>, 3> tasks;
229
230 // test cancel and catch {
231 auto start_time = clock::now();
232 int exceptions = 0;
233 std::generate(tasks.begin(), tasks.end(), make_task);
234 for (auto &task : tasks) {
235 task.cancel();
236 }
237 for (auto &task : tasks) {
238 try {
239 co_await task;
240 }
241 catch (const dpp::task_cancelled_exception &) {
242 ++exceptions;
243 }
244 }
245 if (exceptions < 3 || !(clock::now() - start_time < std::chrono::seconds(10))) {
246 set_status(CORO_TASK_OFFLINE, ts_failed, "failed to cancel 3 nested tasks in time");
247 }
248
249 // test cancel and propagate {
250 std::generate(tasks.begin(), tasks.end(), make_task);
251 tasks[0].cancel();
252 for (auto &task : tasks) {
253 co_await task; // tasks[0] should throw
254 }
255 // unreachable normally
256 set_status(CORO_TASK_OFFLINE, ts_failed, "failed to exit the scope after expected dpp::task_cancelled_exception");
257 // }
258 }();
259 try {
260 co_await task3;
261 }
262 catch (const dpp::task_cancelled_exception &) {
263 success = true;
264 }
265 if (!success) {
266 set_status(CORO_TASK_OFFLINE, ts_failed, "failed to propagate dpp::task_cancelled_exception to caller");
267 }
268 throw test_exception<0>{};
269 }
270
271 dpp::coroutine<void> coroutine_offline_test() {
272 static auto &test = CORO_COROUTINE_OFFLINE;
273 std::array<int, 3> data;
274 int num = 0;
275
276 auto factory = [&data](int &i) -> dpp::coroutine<int> {
277 if (int ret = co_await simple_awaitable{test, 42}; ret != 42) {
278 set_status(test, ts_failed, "failed simple awaitable");
279 }
280 data[i] = i;
281 co_return i++;
282 };
283 if (int ret = co_await factory(num); ret != 0) {
284 set_status(test, ts_failed, "coroutine 1 to set expected values");
285 }
286 if (int ret = co_await factory(num); ret != 1) {
287 set_status(test, ts_failed, "coroutine 2 to set expected values");
288 }
289 if (int ret = co_await factory(num); ret != 2) {
290 set_status(test, ts_failed, "coroutine 3 to set expected values");
291 }
292 if (data != std::to_array<int>({0, 1, 2})) {
293 set_status(test, ts_failed, "unexpected test data");
294 }
295
296 // verify that exceptions work as expected (dpp::coroutine throws uncaught exceptions to co_await-er)
297 co_await []() -> dpp::coroutine<void> {
298 dpp::coroutine<void> nested1;
299 dpp::coroutine<void> nested2;
300 try {
301 nested1 = []() -> dpp::coroutine<void> {
302 int n = rand();
303 if (int ret = co_await simple_awaitable{test, n}; ret != n) {
304 set_status(test, ts_failed, "nested failed simple awaitable");
305 }
306 throw test_exception<1>{};
307 }();
308 nested2 = []() -> dpp::coroutine<void> {
309 co_await std_coroutine::suspend_never{};
310 throw test_exception<2>{};
311 }();
312 } catch (const std::exception &e) {
313 /* SHOULD NOT throw. exceptions are sent when resuming from co_await */
314 set_status(test, ts_failed, "threw before co_await");
315 }
316 bool success1 = false;
317 bool success2 = false;
318 try {
319 co_await nested1;
320 } catch (const test_exception<1> &) {
321 success1 = true;
322 }
323 try {
324 co_await nested2;
325 } catch (const test_exception<2> &) {
326 success2 = true;
327 }
328 if (success1 && success2) {
329 throw test_exception<0>{};
330 } else {
331 set_status(test, ts_failed, "failed to throw at co_await");
332 }
333 }(); // test_exception<0> escapes
334 }
335
336 dpp::job async_test() {
337 namespace time = std::chrono;
338 using clock = time::system_clock;
339 test_t &test = CORO_ASYNC_OFFLINE;
340 try {
341 std::array<dpp::async<int>, 10> arr;
342
343 std::generate(arr.begin(), arr.end(), [] { return dpp::async<int>{&sync_awaitable_fun}; });
344 for (auto &async : arr) {
345 if (int ret = co_await async; ret != 42) {
346 set_status(test, ts_failed, "failed to sync resume with expected value");
347 }
348 }
349 bool success = false;
350 try {
351 dpp::async<int> throws{&sync_awaitable_throw};
352 } catch (const test_exception<0> &) {
353 success = true;
354 }
355 if (!success) {
356 set_status(test, ts_failed, "failed to propagate exception");
357 }
358 auto now = clock::now();
359 std::generate(arr.begin(), arr.end(), [] { return dpp::async<int>{&async_awaitable_wait5}; });
360 for (auto &async : arr) {
361 if (int ret = co_await async; ret != 69) {
362 set_status(test, ts_failed, "failed to async resume with expected value");
363 }
364 }
365 auto diff = clock::now() - now;
366 if (diff > time::seconds(10)) {
367 // async executes asynchronously so we should be waiting 5 seconds + some overhead
368 set_status(test, ts_failed, "parallel asyncs took more time than expected");
369 }
370 set_status(test, ts_success);
371 } catch (const std::exception &e) {
372 /* no exception should be caught here */
373 set_status(test, ts_failed, std::string{"unknown exception thrown: "} + e.what());
374 }
375 }
376
377 dpp::job coro_awaitable_test() {
378 try {
379 {
380 dpp::promise<int> test;
381
382 test.set_value(42);
383 if (int res = co_await test.get_awaitable(); res != 42) {
384 set_status(CORO_AWAITABLE_OFFLINE, ts_failed, "could not retrieve value set before co_await");
385 }
386 }
387 {
388 dpp::promise<int> test;
389
390 test.set_value(420);
391 if (int res = test.get_awaitable().sync_wait(); res != 420) {
392 set_status(CORO_AWAITABLE_OFFLINE, ts_failed, "could not retrieve value set before sync_wait");
393 }
394 }
395 {
396 dpp::promise<int> test;
397 dpp::awaitable<int> awaitable;
398
399 awaitable = test.get_awaitable();
400 test.set_value(420);
401 if (std::optional<int> res = awaitable.sync_wait_for(std::chrono::seconds(5)); !res || *res != 420) {
402 set_status(CORO_AWAITABLE_OFFLINE, ts_failed, "could not retrieve value set before sync_wait_for");
403 }
404 }
405 {
406 dpp::promise<void> test;
407 dpp::awaitable awaitable{test.get_awaitable()};
408
409 if (bool res = awaitable.sync_wait_for(std::chrono::seconds(5)); res) {
410 set_status(CORO_AWAITABLE_OFFLINE, ts_failed, "could not retrieve time out with sync_wait_for");
411 }
412 }
413 {
414 dpp::promise<int> test;
415 dpp::awaitable awaitable{test.get_awaitable()};
416 std::thread th{[&test]() mutable {
417 std::this_thread::sleep_for(std::chrono::seconds(2));
418 test.set_value(69);
419 }};
420 th.detach();
421 if (std::optional<int> res = awaitable.sync_wait_for(std::chrono::seconds(5)); !res || *res != 69) {
422 set_status(CORO_AWAITABLE_OFFLINE, ts_failed, "could not retrieve value set after sync_wait_for");
423 }
424 }
425 {
426 dpp::promise<int> test;
427 dpp::awaitable awaitable{test.get_awaitable()};
428 std::thread th{[p = std::move(test)]() mutable {
429 std::this_thread::sleep_for(std::chrono::seconds(2));
430 p.set_value(69420);
431 }};
432 th.detach();
433 if (int res = co_await awaitable; res != 69420) {
434 set_status(CORO_AWAITABLE_OFFLINE, ts_failed, "could not retrieve value set after co_await");
435 }
436 }
437 {
438 dpp::promise<void> test;
439 dpp::awaitable awaitable{test.get_awaitable()};
440 std::thread th{[p = std::move(test)]() mutable {
441 std::this_thread::sleep_for(std::chrono::seconds(2));
442 p.set_exception(std::make_exception_ptr(dpp::voice_exception("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")));
443 }};
444 th.detach();
445 bool success = false;
446 try {
447 co_await awaitable;
448 } catch (const dpp::voice_exception &) {
449 success = true;
450 }
451 if (!success) {
452 set_status(CORO_AWAITABLE_OFFLINE, ts_failed, "retrieval of an exception with co_await failed");
453 }
454 }
455 {
456 dpp::promise<void> test;
457 dpp::awaitable awaitable{test.get_awaitable()};
458 std::thread th{[&test]() mutable {
459 std::this_thread::sleep_for(std::chrono::seconds(2));
460 test.set_exception(std::make_exception_ptr(dpp::voice_exception("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")));
461 }};
462 th.detach();
463 bool success = false;
464 try {
465 awaitable.sync_wait();
466 } catch (const dpp::voice_exception &) {
467 success = true;
468 }
469 if (!success) {
470 set_status(CORO_AWAITABLE_OFFLINE, ts_failed, "retrieval of an exception with co_await failed");
471 }
472 }
473 set_status(CORO_AWAITABLE_OFFLINE, ts_success);
474 } catch (const std::exception &e) {
475 // no exception should reach this point
476 set_status(CORO_AWAITABLE_OFFLINE, ts_failed, std::string{"unknown exception thrown: "} + e.what());
477 }
478 }
479
480 }
481
482 void coro_offline_tests()
483 {
484 start_test(CORO_JOB_OFFLINE);
485 // Initialize all job data to -1
486 std::fill(job_data.begin(), job_data.end(), -1);
487 job_offline_test();
488
489 start_test(CORO_AWAITABLE_OFFLINE);
490 coro_awaitable_test();
491
492 start_test(CORO_TASK_OFFLINE);
493 std::fill(task_data.begin(), task_data.end(), -1);
494 []() -> dpp::job {
495 dpp::task task = task_offline_test();
496
497 try {
498 co_await dpp::task{std::move(task)};
499 } catch (const test_exception<0> &) { // exception thrown at the end of the task test
500 set_status(CORO_TASK_OFFLINE, ts_success);
501 } catch (const std::exception &e) { // anything else should not escape
502 set_status(CORO_TASK_OFFLINE, ts_failed, std::string{"unknown exception thrown: "} + e.what());
503 }
504 }();
505
506 start_test(CORO_COROUTINE_OFFLINE);
507 []() -> dpp::job {
508 dpp::coroutine task = coroutine_offline_test();
509
510 try {
511 co_await dpp::coroutine{std::move(task)};
512 } catch (const test_exception<0> &) {
513 set_status(CORO_COROUTINE_OFFLINE, ts_success);
514 } catch (const std::exception &e) { // anything else should not escape
515 set_status(CORO_COROUTINE_OFFLINE, ts_failed, std::string{"unknown exception thrown: "} + e.what());
516 }
517 }();
518
519 start_test(CORO_ASYNC_OFFLINE);
520 async_test();
521 }
522
523 void event_handler_test(dpp::cluster *bot) {
524 bot->on_message_create([](dpp::message_create_t event) -> dpp::task<void> {
525 if (event.msg.content == "coro test") {
526 dpp::cluster *bot = event.owner;
527
528 set_status(CORO_EVENT_HANDLER, ts_success);
529 start_test(CORO_API_CALLS);
530 dpp::confirmation_callback_t result = co_await bot->co_message_edit(dpp::message{event.msg}.set_content("coro 👍"));
531 dpp::message *confirm = std::get_if<dpp::message>(&(result.value));
532 set_status(CORO_API_CALLS, (confirm == nullptr || confirm->content != "coro 👍") ? ts_failed : ts_success);
533
534 if (extended) {
535 start_test(CORO_MUMBO_JUMBO);
536 std::array<dpp::task<dpp::snowflake>, 3> tasks;
537 for (int i = 0; i < 3; ++i) {
538 tasks[i] = [](dpp::cluster *bot, dpp::snowflake channel, int i) -> dpp::task<dpp::snowflake> {
539 using user_member = std::pair<std::optional<dpp::user>, std::optional<dpp::guild_member>>;
540 constexpr auto get_member_user = [](dpp::cluster *bot) -> dpp::task<user_member> {
541 std::pair<std::optional<dpp::user>, std::optional<dpp::guild_member>> ret{};
542 dpp::confirmation_callback_t result;
543
544 try {
545 ret.second = dpp::find_guild_member(TEST_GUILD_ID, TEST_USER_ID);
546 } catch (const dpp::cache_exception &e) {}
547 if (!ret.second.has_value()) {
548 result = co_await bot->co_guild_get_member(TEST_GUILD_ID, TEST_USER_ID);
549 if (!result.is_error()) {
550 ret.second = std::get<dpp::guild_member>(std::move(result).value);
551 }
552 }
553 result = co_await bot->co_user_get_cached(TEST_USER_ID);
554 if (!result.is_error()) {
555 ret.first = std::get<dpp::user_identified>(std::move(result).value);
556 }
557 co_return ret;
558 };
559 auto get_member_task = get_member_user(bot);
560 std::string content = "coro " + std::to_string(i);
561 dpp::confirmation_callback_t result = co_await bot->co_message_create(dpp::message{channel, content});
562
563 if (result.is_error()) {
564 co_return {};
565 }
566 dpp::message msg = std::get<dpp::message>(std::move(result).value);
567 if (msg.content != content) {
568 co_return {};
569 }
570 user_member pair = co_await get_member_task;
571 if (!pair.first.has_value()) {
572 co_return {};
573 }
574 const std::string& member_nick = pair.second.has_value() ? pair.second->get_nickname() : "";
575 const std::string& user_nick = pair.first->username;
576 result = co_await bot->co_message_edit(msg.set_content("coro " + (member_nick.empty() ? user_nick : member_nick) + " " + std::to_string(i)));
577 co_return result.is_error() ? dpp::snowflake{} : std::get<dpp::message>(result.value).id;
578 }(bot, event.msg.channel_id, i);
579 }
580 std::array<dpp::snowflake, 3> msg_ids;
581 std::array<dpp::async<dpp::confirmation_callback_t>, 3> reacts;
582 for (int i = 0; i < 3; ++i) {
583 try {
584 msg_ids[i] = co_await tasks[i];
585
586 if (msg_ids[i] == dpp::snowflake{}) {
587 set_status(CORO_MUMBO_JUMBO, ts_failed, "failed to post message");
588 reacts[i] = dpp::async{[](auto &&cc) { cc(dpp::confirmation_callback_t{}); }};
589 } else {
590 reacts[i] = bot->co_message_add_reaction(msg_ids[i], event.msg.channel_id, "✅");
591 }
592 } catch (const std::exception &e) {
593 set_status(CORO_MUMBO_JUMBO, ts_failed, "message task threw " + std::string{e.what()});
594 reacts[i] = dpp::async{[](auto &&cc) { cc(dpp::confirmation_callback_t{}); }};
595 }
596 }
597 for (int i = 0; i < 3; ++i) {
598 try {
599 dpp::confirmation_callback_t result = co_await reacts[i];
600 } catch (const std::exception &e) {
601 set_status(CORO_MUMBO_JUMBO, ts_failed, "react task threw " + std::string{e.what()});
602 }
603 }
604 for (int i = 0; i < 3; ++i) {
605 bot->message_delete(msg_ids[i], event.msg.channel_id);
606 }
607 set_status(CORO_MUMBO_JUMBO, ts_success);
608 }
609 }
610 co_return;
611 });
612 bot->message_create(dpp::message{"coro test"}.set_channel_id(TEST_TEXT_CHANNEL_ID));
613 }
614
615 void coro_online_tests(dpp::cluster *bot) {
616 start_test(CORO_EVENT_HANDLER);
617 event_handler_test(bot);
618 }
619
620 #else
621
622 void coro_offline_tests() {}
623 void coro_online_tests(dpp::cluster *bot) {}
624
625 #endif