Skip to content
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 14 commits into from
Aug 23, 2024
63 changes: 63 additions & 0 deletions src/examples/rpp/doxygen/retry_when.cpp
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({});
Copy link
Contributor

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 of on_completed. See the observable contract for reference.

OnNext
conveys an item that is emitted by the Observable to the observer
OnCompleted
indicates that the Observable has completed successfully and that it will be emitting no further items
OnError
indicates that the Observable has terminated with a specified error condition and that it will be emitting no further items

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.

Copy link
Owner

@victimsnino victimsnino Aug 21, 2024

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 to final_observer it does attempt to subscribe new observer_inside_retry_when (let's say observer_inside_retry_when_2) observer to new observable_2. so old chain is partially destructed
observable->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

rpp::source::create<int>([](const auto& observer)
{
    // some hard job to construct state
     while(true) {
          observer.on_next(std::rand());
          if (get_current_cpu_temp() > 95) { // emulating some issues
              observer.on_error(.....);
              break;
          }
     }
    // some hard job to destruct state
})
| rpp::operators::retry_when([](const std::exception_ptr&) {
   return rpp::source::timer(std::chrono::seconds{5}, rpp::schedulers::new_thread{}); // kind of "ok, we are obtained error, it is ok, let's wait 5 seconds to make our cpu cooler and try again"
})
| rpp::operators::subscribe(...);

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no any other messages emitted from this observable, but they would be emitted from new one (after resubscribe)

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?

Copy link
Owner

@victimsnino victimsnino Aug 21, 2024

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)

Copy link
Contributor

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.

Copy link
Owner

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?

}
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;
}
1 change: 1 addition & 0 deletions src/rpp/rpp/operators.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,4 @@

#include <rpp/operators/on_error_resume_next.hpp>
#include <rpp/operators/retry.hpp>
#include <rpp/operators/retry_when.hpp>
4 changes: 4 additions & 0 deletions src/rpp/rpp/operators/fwd.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,10 @@ namespace rpp::operators
requires rpp::constraint::observable<std::invoke_result_t<Selector, std::exception_ptr>>
auto on_error_resume_next(Selector&& selector);

template<typename Notifier>
requires rpp::constraint::observable<std::invoke_result_t<Notifier, std::exception_ptr>>
auto retry_when(Notifier&& notifier);

template<typename TSelector, rpp::constraint::observable TObservable, rpp::constraint::observable... TObservables>
requires (!rpp::constraint::observable<TSelector> && (!utils::is_not_template_callable<TSelector> || std::invocable<TSelector, rpp::utils::convertible_to_any, utils::extract_observable_type_t<TObservable>, utils::extract_observable_type_t<TObservables>...>))
auto with_latest_from(TSelector&& selector, TObservable&& observable, TObservables&&... observables);
Expand Down
202 changes: 202 additions & 0 deletions src/rpp/rpp/operators/retry_when.hpp
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;

Check warning on line 142 in src/rpp/rpp/operators/retry_when.hpp

View check run for this annotation

Codecov / codecov/patch

src/rpp/rpp/operators/retry_when.hpp#L141-L142

Added lines #L141 - L142 were not covered by tests
}
}
}
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
Loading
Loading