| 784 | typename Control = typename std::invoke_result_t<Iterate>::ValueType, |
| 785 | typename BreakValueType = typename Control::value_type> |
| 786 | Future<BreakValueType> Loop(Iterate iterate) { |
| 787 | struct Callback { |
| 788 | bool CheckForTermination(const Result<Control>& control_res) { |
| 789 | if (!control_res.ok()) { |
| 790 | break_fut.MarkFinished(control_res.status()); |
| 791 | return true; |
| 792 | } |
| 793 | if (control_res->has_value()) { |
| 794 | break_fut.MarkFinished(**control_res); |
| 795 | return true; |
| 796 | } |
| 797 | return false; |
| 798 | } |
| 799 | |
| 800 | void operator()(const Result<Control>& maybe_control) && { |
| 801 | if (CheckForTermination(maybe_control)) return; |
| 802 | |
| 803 | auto control_fut = iterate(); |
| 804 | while (true) { |
| 805 | if (control_fut.TryAddCallback([this]() { return *this; })) { |
| 806 | // Adding a callback succeeded; control_fut was not finished |
| 807 | // and we must wait to CheckForTermination. |
| 808 | return; |
| 809 | } |
| 810 | // Adding a callback failed; control_fut was finished and we |
| 811 | // can CheckForTermination immediately. This also avoids recursion and potential |
| 812 | // stack overflow. |
| 813 | if (CheckForTermination(control_fut.result())) return; |
| 814 | |
| 815 | control_fut = iterate(); |
| 816 | } |
| 817 | } |
| 818 | |
| 819 | Iterate iterate; |
| 820 | |
| 821 | // If the future returned by control_fut is never completed then we will be hanging on |
| 822 | // to break_fut forever even if the listener has given up listening on it. Instead we |
| 823 | // rely on the fact that a producer (the caller of Future<>::Make) is always |
| 824 | // responsible for completing the futures they create. |
| 825 | // TODO: Could avoid this kind of situation with "future abandonment" similar to mesos |
| 826 | Future<BreakValueType> break_fut; |
| 827 | }; |
| 828 | |
| 829 | auto break_fut = Future<BreakValueType>::Make(); |
| 830 | auto control_fut = iterate(); |
| 831 | control_fut.AddCallback(Callback{std::move(iterate), break_fut}); |
| 832 | |
| 833 | return break_fut; |
| 834 | } |
| 835 | |
| 836 | inline Future<> ToFuture(Status status) { |
| 837 | return Future<>::MakeFinished(std::move(status)); |