Debian Codegraph @

thirdparty/folly/folly/futures/test/ViaTest.cpp

raw
1 /*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <thread>
18
19 #include <folly/MPMCQueue.h>
20 #include <folly/executors/DrivableExecutor.h>
21 #include <folly/executors/InlineExecutor.h>
22 #include <folly/executors/ManualExecutor.h>
23 #include <folly/futures/Future.h>
24 #include <folly/portability/GTest.h>
25 #include <folly/synchronization/Baton.h>
26
27 using namespace folly;
28
29 struct ManualWaiter : public DrivableExecutor {
30 explicit ManualWaiter(std::shared_ptr<ManualExecutor> ex_) : ex(ex_) {}
31
32 void add(Func f) override { ex->add(std::move(f)); }
33
34 void drive() override {
35 ex->wait();
36 ex->run();
37 }
38
39 std::shared_ptr<ManualExecutor> ex;
40 };
41
42 struct ViaFixture : public testing::Test {
43 ViaFixture()
44 : westExecutor(new ManualExecutor),
45 eastExecutor(new ManualExecutor),
46 waiter(new ManualWaiter(westExecutor)),
47 done(false) {
48 th = std::thread([=] {
49 ManualWaiter eastWaiter(eastExecutor);
50 while (!done) {
51 eastWaiter.drive();
52 }
53 });
54 }
55
56 ~ViaFixture() override {
57 done = true;
58 eastExecutor->add([=]() {});
59 th.join();
60 }
61
62 void addAsync(int a, int b, std::function<void(int&&)>&& cob) {
63 eastExecutor->add([=]() { cob(a + b); });
64 }
65
66 std::shared_ptr<ManualExecutor> westExecutor;
67 std::shared_ptr<ManualExecutor> eastExecutor;
68 std::shared_ptr<ManualWaiter> waiter;
69 InlineExecutor inlineExecutor;
70 std::atomic<bool> done;
71 std::thread th;
72 };
73
74 TEST(Via, exceptionOnLaunch) {
75 auto future = makeFuture<int>(std::runtime_error("E"));
76 EXPECT_THROW(future.value(), std::runtime_error);
77 }
78
79 TEST(Via, thenValue) {
80 auto future = makeFuture(std::move(1)).thenTry([](Try<int>&& t) {
81 return t.value() == 1;
82 });
83
84 EXPECT_TRUE(future.value());
85 }
86
87 TEST(Via, thenFuture) {
88 auto future = makeFuture(1).thenTry(
89 [](Try<int>&& t) { return makeFuture(t.value() == 1); });
90 EXPECT_TRUE(future.value());
91 }
92
93 static Future<std::string> doWorkStatic(Try<std::string>&& t) {
94 return makeFuture(t.value() + ";static");
95 }
96
97 TEST(Via, thenFunction) {
98 struct Worker {
99 Future<std::string> doWork(Try<std::string>&& t) {
100 return makeFuture(t.value() + ";class");
101 }
102 static Future<std::string> doWorkStatic(Try<std::string>&& t) {
103 return makeFuture(t.value() + ";class-static");
104 }
105 } w;
106
107 auto f = makeFuture(std::string("start"))
108 .thenTry(doWorkStatic)
109 .thenTry(Worker::doWorkStatic)
110 .then(&Worker::doWork, &w);
111
112 EXPECT_EQ(f.value(), "start;static;class-static;class");
113 }
114
115 TEST_F(ViaFixture, threadHops) {
116 auto westThreadId = std::this_thread::get_id();
117 auto f = via(eastExecutor.get())
118 .thenTry([=](Try<Unit>&& /* t */) {
119 EXPECT_NE(std::this_thread::get_id(), westThreadId);
120 return makeFuture<int>(1);
121 })
122 .via(westExecutor.get())
123 .thenTry([=](Try<int>&& t) {
124 EXPECT_EQ(std::this_thread::get_id(), westThreadId);
125 return t.value();
126 });
127 EXPECT_EQ(std::move(f).getVia(waiter.get()), 1);
128 }
129
130 TEST_F(ViaFixture, chainVias) {
131 auto westThreadId = std::this_thread::get_id();
132 auto f = via(eastExecutor.get())
133 .thenValue([=](auto&&) {
134 EXPECT_NE(std::this_thread::get_id(), westThreadId);
135 return 1;
136 })
137 .thenValue([=](int val) {
138 return makeFuture(val)
139 .via(westExecutor.get())
140 .thenValue([=](int v) mutable {
141 EXPECT_EQ(std::this_thread::get_id(), westThreadId);
142 return v + 1;
143 });
144 })
145 .thenValue([=](int val) {
146 // even though ultimately the future that triggers this one
147 // executed in the west thread, this thenValue() inherited the
148 // executor from its predecessor, ie the eastExecutor.
149 EXPECT_NE(std::this_thread::get_id(), westThreadId);
150 return val + 1;
151 })
152 .via(westExecutor.get())
153 .thenValue([=](int val) {
154 // go back to west, so we can wait on it
155 EXPECT_EQ(std::this_thread::get_id(), westThreadId);
156 return val + 1;
157 });
158
159 EXPECT_EQ(std::move(f).getVia(waiter.get()), 4);
160 }
161
162 TEST_F(ViaFixture, bareViaAssignment) {
163 auto f = via(eastExecutor.get());
164 }
165 TEST_F(ViaFixture, viaAssignment) {
166 // via()&&
167 auto f = makeFuture().via(eastExecutor.get());
168 // via()&
169 auto f2 = f.via(eastExecutor.get());
170 }
171
172 struct PriorityExecutor : public Executor {
173 void add(Func /* f */) override { count1++; }
174
175 void addWithPriority(Func f, int8_t priority) override {
176 int mid = getNumPriorities() / 2;
177 int p = priority < 0 ? std::max(0, mid + priority)
178 : std::min(getNumPriorities() - 1, mid + priority);
179 EXPECT_LT(p, 3);
180 EXPECT_GE(p, 0);
181 if (p == 0) {
182 count0++;
183 } else if (p == 1) {
184 count1++;
185 } else if (p == 2) {
186 count2++;
187 }
188 f();
189 }
190
191 uint8_t getNumPriorities() const override { return 3; }
192
193 int count0{0};
194 int count1{0};
195 int count2{0};
196 };
197
198 TEST(Via, priority) {
199 PriorityExecutor exe;
200 via(&exe, -1).thenValue([](auto&&) {});
201 via(&exe, 0).thenValue([](auto&&) {});
202 via(&exe, 1).thenValue([](auto&&) {});
203 via(&exe, 42).thenValue([](auto&&) {}); // overflow should go to max priority
204 via(&exe, -42).thenValue(
205 [](auto&&) {}); // underflow should go to min priority
206 via(&exe).thenValue([](auto&&) {}); // default to mid priority
207 via(&exe, Executor::LO_PRI).thenValue([](auto&&) {});
208 via(&exe, Executor::HI_PRI).thenValue([](auto&&) {});
209 EXPECT_EQ(3, exe.count0);
210 EXPECT_EQ(2, exe.count1);
211 EXPECT_EQ(3, exe.count2);
212 }
213
214 TEST(Via, then2) {
215 ManualExecutor x1, x2;
216 bool a = false, b = false, c = false;
217 via(&x1)
218 .thenValue([&](auto&&) { a = true; })
219 .thenValue([&](auto&&) { b = true; })
220 .thenValueInline(folly::makeAsyncTask(&x2, [&](auto&&) { c = true; }));
221
222 EXPECT_FALSE(a);
223 EXPECT_FALSE(b);
224
225 x1.run();
226 EXPECT_TRUE(a);
227 EXPECT_FALSE(b);
228 EXPECT_FALSE(c);
229
230 x1.run();
231 EXPECT_TRUE(b);
232 EXPECT_FALSE(c);
233
234 x2.run();
235 EXPECT_TRUE(c);
236 }
237
238 TEST(Via, allowInline) {
239 ManualExecutor x1, x2;
240 bool a = false, b = false, c = false, d = false, e = false, f = false,
241 g = false, h = false, i = false, j = false, k = false, l = false,
242 m = false, n = false, o = false, p = false, q = false, r = false;
243 via(&x1)
244 .thenValue([&](auto&&) { a = true; })
245 .thenTryInline([&](auto&&) { b = true; })
246 .thenTry([&](auto&&) { c = true; })
247 .via(&x2)
248 .thenTryInline([&](auto&&) { d = true; })
249 .thenValue([&](auto&&) {
250 e = true;
251 return via(&x2).thenValue([&](auto&&) { f = true; });
252 })
253 .thenErrorInline(tag_t<std::exception>{}, [](auto&&) {})
254 .thenValueInline([&](auto&&) { g = true; })
255 .thenValue([&](auto&&) {
256 h = true;
257 return via(&x1).thenValue([&](auto&&) { i = true; });
258 })
259 .thenValueInline([&](auto&&) { j = true; })
260 .semi()
261 .deferValue([&](auto&&) { k = true; })
262 .via(&x2)
263 .thenValueInline([&](auto&&) { l = true; })
264 .semi()
265 .deferValue([&](auto&&) { m = true; })
266 .via(&x1)
267 .thenValue([&](auto&&) { n = true; })
268 .semi()
269 .deferValue([&](auto&&) { o = true; })
270 .deferValue([&](auto&&) { p = true; })
271 .via(&x1)
272 .semi()
273 .deferValue([&](auto&&) { q = true; })
274 .deferValue([&](auto&&) { r = true; })
275 .via(&x2);
276
277 EXPECT_FALSE(a);
278 EXPECT_FALSE(b);
279
280 // Expect b to be satisfied inline with the task x1
281 x1.run();
282 EXPECT_TRUE(a);
283 EXPECT_TRUE(b);
284 EXPECT_FALSE(c);
285
286 x1.run();
287 EXPECT_TRUE(c);
288 EXPECT_FALSE(d);
289
290 // Demonstrate that the executor transition did not allow inline execution
291 x2.run();
292 EXPECT_TRUE(d);
293 EXPECT_FALSE(e);
294
295 x2.run();
296 EXPECT_TRUE(e);
297 EXPECT_FALSE(f);
298 EXPECT_FALSE(g);
299
300 // Completing nested continuation should satisfy inline continuation
301 x2.run();
302 EXPECT_TRUE(f);
303 EXPECT_TRUE(g);
304 EXPECT_FALSE(h);
305
306 x2.run();
307 EXPECT_TRUE(h);
308 EXPECT_FALSE(i);
309 EXPECT_FALSE(j);
310
311 // Nested continuation on different executor should not complete next entry
312 // inline
313 x1.run();
314 EXPECT_TRUE(i);
315 EXPECT_FALSE(j);
316
317 // Defer should run on x1 and therefore not inline
318 // Subsequent deferred work is run on x1 and hence not inlined.
319 x2.run();
320 EXPECT_TRUE(j);
321 EXPECT_TRUE(k);
322 EXPECT_TRUE(l);
323 EXPECT_FALSE(m);
324
325 // Complete the deferred task
326 x1.run();
327 EXPECT_TRUE(m);
328 EXPECT_FALSE(n);
329
330 // Here defer and the above thenValue are both on x1, defer should be
331 // inline
332 x1.run();
333 EXPECT_TRUE(n);
334 EXPECT_TRUE(o);
335 EXPECT_TRUE(p);
336 EXPECT_FALSE(q);
337
338 // Change of executor in deferred executor so now run x2 to complete
339 x2.run();
340 EXPECT_TRUE(q);
341 EXPECT_TRUE(r);
342 }
343
344 #ifndef __APPLE__ // TODO #7372389
345 /// Simple executor that does work in another thread
346 class ThreadExecutor : public Executor {
347 folly::MPMCQueue<Func> funcs;
348 std::atomic<bool> done{false};
349 std::thread worker;
350 folly::Baton<> baton;
351
352 void work() {
353 baton.post();
354 Func fn;
355 while (!done) {
356 while (!funcs.isEmpty()) {
357 funcs.blockingRead(fn);
358 fn();
359 }
360 }
361 }
362
363 public:
364 explicit ThreadExecutor(size_t n = 1024) : funcs(n) {
365 worker = std::thread(std::bind(&ThreadExecutor::work, this));
366 }
367
368 ~ThreadExecutor() override {
369 done = true;
370 funcs.write([] {});
371 worker.join();
372 }
373
374 void add(Func fn) override { funcs.blockingWrite(std::move(fn)); }
375
376 void waitForStartup() { baton.wait(); }
377 };
378
379 TEST(Via, viaThenGetWasRacy) {
380 ThreadExecutor x;
381 std::unique_ptr<int> val =
382 folly::via(&x)
383 .thenValue([](auto&&) { return std::make_unique<int>(42); })
384 .get();
385 ASSERT_TRUE(!!val);
386 EXPECT_EQ(42, *val);
387 }
388
389 TEST(Via, callbackRace) {
390 ThreadExecutor x;
391
392 auto fn = [&x] {
393 auto promises = std::make_shared<std::vector<Promise<Unit>>>(4);
394 std::vector<Future<Unit>> futures;
395
396 for (auto& p : *promises) {
397 futures.emplace_back(p.getFuture().via(&x).thenTry([](Try<Unit>&&) {}));
398 }
399
400 x.waitForStartup();
401 x.add([promises] {
402 for (auto& p : *promises) {
403 p.setValue();
404 }
405 });
406
407 return collectAll(futures);
408 };
409
410 fn().wait();
411 }
412 #endif
413
414 class DummyDrivableExecutor : public DrivableExecutor {
415 public:
416 void add(Func /* f */) override {}
417 void drive() override { ran = true; }
418 bool ran{false};
419 };
420
421 TEST(Via, getVia) {
422 {
423 // non-void
424 ManualExecutor x;
425 auto f = via(&x).thenValue([](auto&&) { return true; });
426 EXPECT_TRUE(std::move(f).getVia(&x));
427 }
428
429 {
430 // void
431 ManualExecutor x;
432 auto f = via(&x).then();
433 std::move(f).getVia(&x);
434 }
435
436 {
437 DummyDrivableExecutor x;
438 auto f = makeFuture(true);
439 EXPECT_TRUE(std::move(f).getVia(&x));
440 EXPECT_FALSE(x.ran);
441 }
442 }
443
444 TEST(Via, SimpleTimedGetVia) {
445 TimedDrivableExecutor e2;
446 Promise<folly::Unit> p;
447 auto f = p.getFuture();
448 EXPECT_THROW(
449 std::move(f).getVia(&e2, std::chrono::seconds(1)), FutureTimeout);
450 }
451
452 TEST(Via, getTryVia) {
453 {
454 // non-void
455 ManualExecutor x;
456 auto f = via(&x).thenValue([](auto&&) { return 23; });
457 EXPECT_FALSE(f.isReady());
458 EXPECT_EQ(23, std::move(f).getTryVia(&x).value());
459 }
460
461 {
462 // void
463 ManualExecutor x;
464 auto f = via(&x).then();
465 EXPECT_FALSE(f.isReady());
466 auto t = std::move(f).getTryVia(&x);
467 EXPECT_TRUE(t.hasValue());
468 }
469
470 {
471 DummyDrivableExecutor x;
472 auto f = makeFuture(23);
473 EXPECT_EQ(23, std::move(f).getTryVia(&x).value());
474 EXPECT_FALSE(x.ran);
475 }
476 }
477
478 TEST(Via, SimpleTimedGetTryVia) {
479 TimedDrivableExecutor e2;
480 Promise<folly::Unit> p;
481 auto f = p.getFuture();
482 EXPECT_THROW(
483 std::move(f).getTryVia(&e2, std::chrono::seconds(1)), FutureTimeout);
484 }
485
486 TEST(Via, waitVia) {
487 {
488 ManualExecutor x;
489 auto f = via(&x).then();
490 EXPECT_FALSE(f.isReady());
491 f.waitVia(&x);
492 EXPECT_TRUE(f.isReady());
493 }
494
495 {
496 // try rvalue as well
497 ManualExecutor x;
498 auto f = via(&x).then().waitVia(&x);
499 EXPECT_TRUE(f.isReady());
500 }
501
502 {
503 DummyDrivableExecutor x;
504 makeFuture(true).waitVia(&x);
505 EXPECT_FALSE(x.ran);
506 }
507 }
508
509 TEST(Via, viaRaces) {
510 ManualExecutor x;
511 Promise<Unit> p;
512 auto tid = std::this_thread::get_id();
513 bool done = false;
514
515 std::thread t1([&] {
516 p.getFuture()
517 .via(&x)
518 .thenTry(
519 [&](Try<Unit>&&) { EXPECT_EQ(tid, std::this_thread::get_id()); })
520 .thenTry(
521 [&](Try<Unit>&&) { EXPECT_EQ(tid, std::this_thread::get_id()); })
522 .thenTry([&](Try<Unit>&&) { done = true; });
523 });
524
525 std::thread t2([&] { p.setValue(); });
526
527 while (!done) {
528 x.run();
529 }
530 t1.join();
531 t2.join();
532 }
533
534 TEST(Via, viaDummyExecutorFutureSetValueFirst) {
535 // The callback object will get destroyed when passed to the executor.
536
537 // A promise will be captured by the callback lambda so we can observe that
538 // it will be destroyed.
539 Promise<Unit> captured_promise;
540 auto captured_promise_future = captured_promise.getFuture();
541
542 DummyDrivableExecutor x;
543 auto future = makeFuture().via(&x).thenValue(
544 [c = std::move(captured_promise)](auto&&) { return 42; });
545
546 EXPECT_THROW(std::move(future).get(std::chrono::seconds(5)), BrokenPromise);
547 EXPECT_THROW(
548 std::move(captured_promise_future).get(std::chrono::seconds(5)),
549 BrokenPromise);
550 }
551
552 TEST(Via, viaDummyExecutorFutureSetCallbackFirst) {
553 // The callback object will get destroyed when passed to the executor.
554
555 // A promise will be captured by the callback lambda so we can observe that
556 // it will be destroyed.
557 Promise<Unit> captured_promise;
558 auto captured_promise_future = captured_promise.getFuture();
559
560 DummyDrivableExecutor x;
561 Promise<Unit> trigger;
562 auto future = trigger.getFuture().via(&x).thenValue(
563 [c = std::move(captured_promise)](auto&&) { return 42; });
564 trigger.setValue();
565
566 EXPECT_THROW(std::move(future).get(std::chrono::seconds(5)), BrokenPromise);
567 EXPECT_THROW(
568 std::move(captured_promise_future).get(std::chrono::seconds(5)),
569 BrokenPromise);
570 }
571
572 TEST(Via, viaExecutorDiscardsTaskFutureSetValueFirst) {
573 // The callback object will get destroyed when the ManualExecutor runs out
574 // of scope.
575
576 // A promise will be captured by the callback lambda so we can observe that
577 // it will be destroyed.
578 Promise<Unit> captured_promise;
579 auto captured_promise_future = captured_promise.getFuture();
580
581 Optional<SemiFuture<int>> future;
582 {
583 ManualExecutor x;
584 future =
585 makeFuture()
586 .via(&x)
587 .thenValue([c = std::move(captured_promise)](auto&&) { return 42; })
588 .semi();
589 x.clear();
590 }
591
592 EXPECT_THROW(std::move(*future).get(std::chrono::seconds(5)), BrokenPromise);
593 EXPECT_THROW(
594 std::move(captured_promise_future).get(std::chrono::seconds(5)),
595 BrokenPromise);
596 }
597
598 TEST(Via, viaExecutorDiscardsTaskFutureSetCallbackFirst) {
599 // The callback object will get destroyed when the ManualExecutor runs out
600 // of scope.
601
602 // A promise will be captured by the callback lambda so we can observe that
603 // it will be destroyed.
604 Promise<Unit> captured_promise;
605 auto captured_promise_future = captured_promise.getFuture();
606
607 Optional<SemiFuture<int>> future;
608 {
609 ManualExecutor x;
610 Promise<Unit> trigger;
611 future =
612 trigger.getFuture()
613 .via(&x)
614 .thenValue([c = std::move(captured_promise)](auto&&) { return 42; })
615 .semi();
616 trigger.setValue();
617 x.clear();
618 }
619
620 EXPECT_THROW(std::move(*future).get(std::chrono::seconds(5)), BrokenPromise);
621 EXPECT_THROW(
622 std::move(captured_promise_future).get(std::chrono::seconds(5)),
623 BrokenPromise);
624 }
625
626 TEST(ViaFunc, liftsVoid) {
627 ManualExecutor x;
628 int count = 0;
629 Future<Unit> f = via(&x, [&] { count++; });
630
631 EXPECT_EQ(0, count);
632 x.run();
633 EXPECT_EQ(1, count);
634 }
635
636 TEST(ViaFunc, value) {
637 ManualExecutor x;
638 EXPECT_EQ(42, via(&x, [] { return 42; }).getVia(&x));
639 }
640
641 TEST(ViaFunc, exception) {
642 ManualExecutor x;
643 EXPECT_THROW(
644 via(&x, []() -> int { throw std::runtime_error("expected"); }).getVia(&x),
645 std::runtime_error);
646 }
647
648 TEST(ViaFunc, future) {
649 ManualExecutor x;
650 EXPECT_EQ(42, via(&x, [] { return makeFuture(42); }).getVia(&x));
651 }
652
653 TEST(ViaFunc, semi_future) {
654 ManualExecutor x;
655 EXPECT_EQ(42, via(&x, [] { return makeSemiFuture(42); }).getVia(&x));
656 }
657
658 TEST(ViaFunc, voidFuture) {
659 ManualExecutor x;
660 int count = 0;
661 via(&x, [&] { count++; }).getVia(&x);
662 EXPECT_EQ(1, count);
663 }
664
665 TEST(ViaFunc, isSticky) {
666 ManualExecutor x;
667 int count = 0;
668
669 auto f = via(&x, [&] { count++; });
670 x.run();
671
672 std::move(f).thenValue([&](auto&&) { count++; });
673 EXPECT_EQ(1, count);
674 x.run();
675 EXPECT_EQ(2, count);
676 }
677
678 TEST(ViaFunc, moveOnly) {
679 ManualExecutor x;
680 auto intp = std::make_unique<int>(42);
681
682 EXPECT_EQ(42, via(&x, [intp = std::move(intp)] { return *intp; }).getVia(&x));
683 }
684
685 TEST(ViaFunc, valueKeepAlive) {
686 ManualExecutor x;
687 EXPECT_EQ(42, via(getKeepAliveToken(&x), [] { return 42; }).getVia(&x));
688 }
689
690 TEST(ViaFunc, thenValueKeepAlive) {
691 ManualExecutor x;
692 EXPECT_EQ(
693 42,
694 via(getKeepAliveToken(&x))
695 .thenValue([](auto&&) { return 42; })
696 .getVia(&x));
697 }