Polly icon indicating copy to clipboard operation
Polly copied to clipboard

Cannot combine ContextualPolicy and Policy; [DONE: document nesting Polly statements]

Open penderi opened this issue 10 years ago • 4 comments

Hi,

I've just battled through a rather complex policy statement. I think it would help as an example on the readme and/or samples project. Moreover I think I've found a gap in the API or rather something rather non-obvious that would be worth helping either via a new method/extension.

In particular we have a need to wrap Policy statements - a retryforever (that logs error) wrapping a retry and backoff (that logs warning). An extra complexity is that somethimes we want that behaviour and sometimes we want another policy. I know.

So our policy:

private Polly.Policy SetRetryPolicy(int retries, int retryWaitInMilliseconds, bool isFromApi)
{
    if (!isFromApi)
    {   
        return
            Polly
                .Policy
                .Handle<Exception>()
                .RetryForever(exception =>
                {
                    _log.ErrorFormat("An erros with Exception detail " + exception);
                })
                .Execute(() =>
                    Polly
                        .Policy
                        .Handle<Exception>()
                        .WaitAndRetry(
                            retries,
                            retryAttempt => TimeSpan.FromMilliseconds(retryWaitInMilliseconds*Math.Pow(2, retryAttempt)),
                            (exception, timeSpan) =>
                            {
                                _log.WarnFormat("An erros with Exception detail " + exception);
                            }));
    }
    return
        Polly
            .Policy
            .Handle<AggregateException>()
            .Retry(retryWaitInMilliseconds, (exception, i) =>
            {
                _connectionSingleton.Stop();
                _log.ErrorFormat("An erros with Exception detail " + exception);
            });
}

The issue I'd like to point attention to is I was passing to the WaitAndRetry method above the following:

(exception, timeSpan, *context*) => ...

.... this has the effect of creating a ContextualPolicy, whereas the second Policy was a Polly.Policy.

  • There is no way to combine a ContextualPolicy and Policy
  • It's very easy to miss this in amongst the various overloads.

I love how Polly works but the lack of examples covering wrapping policies really stymied me. Any help / guidance for others could help.

penderi avatar Dec 08 '15 12:12 penderi

@penderi This is excellent! I had come to the same conclusion about Polly being powerful, but difficult for newcomers to fully grock without great examples. Because of this, I, along with some of the App vNext team members, created a starter project named Polly-Samples.

It would be great if you could fork that project and add in your example. You'll see the start of how the project is laid out, with an web API service (PollyTestApp) to test against via http://pollytestapp.azurewebsites.net, and the PollyTestClient, which is a console app containing the Polly examples.

The current flow, in its infant state, is to add your example to the appropriate class underneath the Samples folder, or to create a new one named after a policy or function, if not tied to a specific policy type. Then, each Polly sample the user wants to run is launched from PollyTestClient\Program.cs.

We're definitely open to suggestions as how to better organize and execute the examples.

By the way, I did add a link to Polly-Samples on the bottom of Polly's readme file. I'm afraid that it probably gets lost in the weeds for experienced users, but hopefully is easily found by someone reading it for the first time.

joelhulen avatar Dec 08 '15 14:12 joelhulen

@penderi Re ContextualPolicy and Policy not being possible to combine, if I have understood, the problem is that because they have no common ancestor or interface, you cannot choose a return type for SetRetryPolicy(...) which would encompass both: is that it? If so, agree, and have noted similar in comments to #63. The proposal in #63 was fairly rapidly thought through (might want refinement), but hopefully, with the introduction of common abstract base classes or interfaces, this situation could be resolved for you. eg the results of your original calls (currently returning non-combinable ContextualPolicy and Policy) might return classes which both fulfil some new interface IRetryPolicy, giving a minimum baseline of some common Execute(...) overloads you could call from either return result.

reisenberger avatar Dec 08 '15 19:12 reisenberger

Agreed that what's really needed is an interface with underlying concrete classes that contain the desired elements, a la IRetryPolicy (like that name, by the way). Perhaps this would be a good addition to the 3.0 milestone.

joelhulen avatar Dec 08 '15 20:12 joelhulen

@penderi Regarding combining policies, yes, this is the way we have done it too. For example, in a microservices environment publishing messages to a message broker like RabbitMQ, we are nesting retry and circuit-breaker with something like:

public Task TransientFaultProtectedPublishAsync(Func<IMessage, Task> publishAction, IMessage message)
{
    var retryPolicy = ... 
    var circuitBreakerPolicy = ...
    Task messagePublishTask = retryPolicy.ExecuteAsync(() =>
        {
            circuitBreakerPolicy.ExecuteAsync(() =>
            {
                publishAction.Invoke(message);
            });
        });
    return messagePublishTask;
}

(In reality it's decorated with a bunch of .ContinueWith(...) for error-tracking, and our policy instances are initialised/defined elsewhere, but this gives a clearer idea of structure)

reisenberger avatar Dec 08 '15 20:12 reisenberger