-
Notifications
You must be signed in to change notification settings - Fork 31
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
retry_when operator #616
Merged
Merged
retry_when operator #616
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
e661682
retry_when operator
CorentinBT 9b23208
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 4f5f845
Add missing mutables
CorentinBT 883c8a6
Address comments
CorentinBT 003df79
wip
CorentinBT 23514f8
wip
CorentinBT 352d10d
wip
CorentinBT 00c028b
working drain approach
CorentinBT 0b4d9e8
fix ub
CorentinBT 9e3bd72
Add examples
CorentinBT 868a8d6
Merge branch 'v2' of https://github.com/victimsnino/ReactivePlusPlus …
CorentinBT 4939c91
Address ai comment
CorentinBT 31301b6
Address comments
CorentinBT fef5910
Merge branch 'v2' of https://github.com/victimsnino/ReactivePlusPlus …
CorentinBT File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
#include <rpp/rpp.hpp> | ||
|
||
#include <iostream> | ||
#include <string> | ||
|
||
/** | ||
* @example retry_when.cpp | ||
**/ | ||
|
||
int main() | ||
{ | ||
//! [retry_when delay] | ||
size_t retry_count = 0; | ||
rpp::source::create<std::string>([&retry_count](const auto& sub) { | ||
if (++retry_count != 4) | ||
{ | ||
sub.on_error({}); | ||
} | ||
else | ||
{ | ||
sub.on_next(std::string{"success"}); | ||
sub.on_completed(); | ||
} | ||
}) | ||
| rpp::operators::retry_when([](const std::exception_ptr&) { | ||
return rpp::source::timer(std::chrono::seconds{5}, rpp::schedulers::current_thread{}); | ||
}) | ||
| rpp::operators::subscribe([](const std::string& v) { std::cout << v << std::endl; }); | ||
// Source observable is resubscribed after 5 seconds on each error emission | ||
//! [retry_when delay] | ||
|
||
//! [retry_when] | ||
retry_count = 0; | ||
rpp::source::create<std::string>([&retry_count](const auto& sub) { | ||
if (++retry_count != 4) | ||
{ | ||
sub.on_error({}); | ||
} | ||
else | ||
{ | ||
sub.on_next(std::string{"success"}); | ||
sub.on_completed(); | ||
} | ||
}) | ||
| rpp::operators::retry_when([](const std::exception_ptr& ep) { | ||
try | ||
{ | ||
std::rethrow_exception(ep); | ||
} | ||
catch (const std::runtime_error&) | ||
{ | ||
return rpp::source::timer(std::chrono::seconds{5}, rpp::schedulers::current_thread{}); | ||
} | ||
catch (...) | ||
{ | ||
throw; | ||
} | ||
}) | ||
| rpp::operators::subscribe([](const std::string& v) { std::cout << v << std::endl; }); | ||
// Source observable is resubscribed after 5 seconds only on particular error emissions | ||
//! [retry_when] | ||
return 0; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,202 @@ | ||
// ReactivePlusPlus library | ||
// | ||
// Copyright Aleksey Loginov 2023 - present. | ||
// Distributed under the Boost Software License, Version 1.0. | ||
// (See accompanying file LICENSE_1_0.txt or copy at | ||
// https://www.boost.org/LICENSE_1_0.txt) | ||
// | ||
// Project home: https://github.com/victimsnino/ReactivePlusPlus | ||
// | ||
|
||
#pragma once | ||
|
||
#include <rpp/observables/fwd.hpp> | ||
#include <rpp/operators/fwd.hpp> | ||
|
||
#include <rpp/defs.hpp> | ||
#include <rpp/operators/details/strategy.hpp> | ||
#include <rpp/utils/constraints.hpp> | ||
#include <rpp/utils/utils.hpp> | ||
|
||
namespace rpp::operators::details | ||
{ | ||
template<rpp::constraint::observer TObserver, | ||
typename TObservable, | ||
typename TNotifier> | ||
struct retry_when_state final : public rpp::composite_disposable | ||
{ | ||
retry_when_state(TObserver&& observer, const TObservable& observable, const TNotifier& notifier) | ||
: observer(std::move(observer)) | ||
, observable(observable) | ||
, notifier(notifier) | ||
{ | ||
} | ||
|
||
std::atomic_bool is_inside_drain{}; | ||
|
||
RPP_NO_UNIQUE_ADDRESS TObserver observer; | ||
victimsnino marked this conversation as resolved.
Show resolved
Hide resolved
|
||
RPP_NO_UNIQUE_ADDRESS TObservable observable; | ||
RPP_NO_UNIQUE_ADDRESS TNotifier notifier; | ||
victimsnino marked this conversation as resolved.
Show resolved
Hide resolved
|
||
}; | ||
|
||
template<rpp::constraint::observer TObserver, typename TObservable, typename TNotifier> | ||
void drain(const std::shared_ptr<retry_when_state<TObserver, TObservable, TNotifier>>& state); | ||
|
||
template<rpp::constraint::observer TObserver, | ||
typename TObservable, | ||
typename TNotifier> | ||
struct retry_when_impl_inner_strategy | ||
{ | ||
using preferred_disposable_strategy = rpp::details::observers::none_disposable_strategy; | ||
|
||
std::shared_ptr<retry_when_state<TObserver, TObservable, TNotifier>> state; | ||
mutable bool locally_disposed{}; | ||
|
||
template<typename T> | ||
void on_next(T&&) const | ||
{ | ||
locally_disposed = true; | ||
|
||
if (state->is_inside_drain.exchange(false, std::memory_order::seq_cst)) | ||
return; | ||
drain<TObserver, TObservable, TNotifier>(state); | ||
} | ||
|
||
void on_error(const std::exception_ptr& err) const | ||
{ | ||
locally_disposed = true; | ||
state->observer.on_error(err); | ||
} | ||
|
||
void on_completed() const | ||
{ | ||
locally_disposed = true; | ||
state->observer.on_completed(); | ||
} | ||
|
||
void set_upstream(const disposable_wrapper& d) { state->add(d); } | ||
|
||
bool is_disposed() const { return locally_disposed || state->is_disposed(); } | ||
}; | ||
|
||
template<rpp::constraint::observer TObserver, | ||
typename TObservable, | ||
typename TNotifier> | ||
struct retry_when_impl_strategy | ||
{ | ||
using preferred_disposable_strategy = rpp::details::observers::none_disposable_strategy; | ||
|
||
std::shared_ptr<retry_when_state<TObserver, TObservable, TNotifier>> state; | ||
|
||
template<typename T> | ||
void on_next(T&& v) const | ||
{ | ||
state->observer.on_next(std::forward<T>(v)); | ||
} | ||
|
||
void on_error(const std::exception_ptr& err) const | ||
{ | ||
std::optional<std::invoke_result_t<TNotifier, std::exception_ptr>> notifier_obs; | ||
try | ||
{ | ||
notifier_obs.emplace(state->notifier(err)); | ||
} | ||
catch (...) | ||
{ | ||
state->observer.on_error(std::current_exception()); | ||
} | ||
if (notifier_obs.has_value()) | ||
{ | ||
std::move(notifier_obs).value().subscribe(retry_when_impl_inner_strategy<TObserver, TObservable, TNotifier>{state}); | ||
} | ||
} | ||
|
||
void on_completed() const | ||
{ | ||
state->observer.on_completed(); | ||
} | ||
|
||
void set_upstream(const disposable_wrapper& d) { state->add(d); } | ||
|
||
bool is_disposed() const { return state->is_disposed(); } | ||
}; | ||
victimsnino marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
template<rpp::constraint::observer TObserver, typename TObservable, typename TNotifier> | ||
void drain(const std::shared_ptr<retry_when_state<TObserver, TObservable, TNotifier>>& state) | ||
{ | ||
while (!state->is_disposed()) | ||
{ | ||
state->clear(); | ||
state->is_inside_drain.store(true, std::memory_order::seq_cst); | ||
try | ||
{ | ||
using value_type = rpp::utils::extract_observer_type_t<TObserver>; | ||
state->observable.subscribe(rpp::observer<value_type, retry_when_impl_strategy<TObserver, TObservable, TNotifier>>{state}); | ||
|
||
if (state->is_inside_drain.exchange(false, std::memory_order::seq_cst)) | ||
return; | ||
} | ||
catch (...) | ||
{ | ||
state->observer.on_error(std::current_exception()); | ||
return; | ||
} | ||
} | ||
} | ||
victimsnino marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
template<rpp::constraint::decayed_type TNotifier> | ||
struct retry_when_t | ||
{ | ||
RPP_NO_UNIQUE_ADDRESS TNotifier notifier; | ||
|
||
template<rpp::constraint::decayed_type T> | ||
struct operator_traits | ||
{ | ||
using result_type = T; | ||
}; | ||
|
||
template<rpp::details::observables::constraint::disposable_strategy Prev> | ||
using updated_disposable_strategy = rpp::details::observables::fixed_disposable_strategy_selector<1>; | ||
|
||
template<rpp::constraint::observer TObserver, typename TObservable> | ||
void subscribe(TObserver&& observer, TObservable&& observable) const | ||
{ | ||
const auto d = disposable_wrapper_impl<retry_when_state<std::decay_t<TObserver>, std::decay_t<TObservable>, std::decay_t<TNotifier>>>::make(std::forward<TObserver>(observer), std::forward<TObservable>(observable), notifier); | ||
auto ptr = d.lock(); | ||
|
||
ptr->observer.set_upstream(d.as_weak()); | ||
drain(ptr); | ||
} | ||
}; | ||
} // namespace rpp::operators::details | ||
|
||
namespace rpp::operators | ||
{ | ||
/** | ||
* @brief If an error occurs, invoke @p notifier and when returned observable emits a value | ||
* resubscribe to the source observable. If the notifier throws or returns an error/empty | ||
* observable, then error/completed emission is forwarded to original subscription. | ||
* | ||
* @param notifier callable taking a std::exception_ptr and returning observable notifying when to resubscribe | ||
* | ||
* @warning retry_when along with other re-subscribing operators needs to be carefully used with | ||
* hot observables, as re-subscribing to a hot observable can have unwanted behaviors. For example, | ||
* a hot observable behind a replay subject can indefinitely yield an error on each re-subscription | ||
* and using retry_when on it would lead to an infinite execution. | ||
* | ||
* @warning #include <rpp/operators/retry_when.hpp> | ||
* | ||
victimsnino marked this conversation as resolved.
Show resolved
Hide resolved
|
||
* @par Examples: | ||
* @snippet retry_when.cpp retry_when delay | ||
* @snippet retry_when.cpp retry_when | ||
* | ||
* @ingroup error_handling_operators | ||
* @see https://reactivex.io/documentation/operators/retry.html | ||
*/ | ||
template<typename TNotifier> | ||
requires rpp::constraint::observable<std::invoke_result_t<TNotifier, std::exception_ptr>> | ||
auto retry_when(TNotifier&& notifier) | ||
{ | ||
return details::retry_when_t<std::decay_t<TNotifier>>{std::forward<TNotifier>(notifier)}; | ||
} | ||
} // namespace rpp::operators |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
IIUC, the fundamental guarantees of observables are broken in this example:
After
on_error
, no other message must be emitted. This includes the emission ofon_completed
. See the observable contract for reference.I am having difficulty understanding how the semantics of
retry_when
fit into this contract. Operators usually act on the output of an observable. In this example, we have a restart functionality that backpropagates into the generator of a cold observable and acts on the observer itself. I am not happy with that design.Please explain why we need
retry_when
.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actually not due to as required no any other messages emitted from this observable, but they would be emitted from new one (after resubscribe). Any observer obtained on_error wouldn't obtain any new messages.
Actually we have chain like this
observable->observer_inside_retry_when->final_observer
when observable emits error, then only
observer_inside_retry_when
actually obtains error. Instead of forwarding error tofinal_observer
it does attempt to subscribe new observer_inside_retry_when (let's sayobserver_inside_retry_when_2
) observer to new observable_2. so old chain is partially destructedobservable->observer_inside_retry_when->| final_observer
and it becomes like
observable_2->observer_inside_retry_when_2->final_observer
No any guarantees are broken in this case.
Why do we need it? For example, to implement error handling loic with custom delaying. Like this
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That is precisely my problem with this operator. This only works and makes sense for cold observables. What happens if this operator is applied on a hot observable? It would subscribe to an observable that has been completed. Can we obtain a compile-time error to avoid this?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In this case hot observable should be in “error state”. For example, subject caches last error and emits it on new subscriptions. In this case it would be infinite loop, but it is up to user to control it.
Not sure if it is possible to add compile time error. Anyway it can be easily suppressed just via converting observable to dynamic version (and losing all meta info)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Given your arguments, I drop my request for a compile-time error message. Also, I accept your explanation:
The current design means that if the hot observable goes into an error state, you obtain zero emissions on consecutive subscriptions—unless you add a stateful relay like
subject
. This behavior follows the contract.I recommend that the difference in behavior for hot and cold observables is explicitly mentioned and explained by example in the documentation of
retry_when
to avoid people running into a pitfall.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah, sure, thank you!
@CorentinBT , could you please handle this documentation request?