bolshakov / stoplight

:traffic_light: Traffic control for code.
http://bolshakov.github.io/stoplight/
MIT License
380 stars 40 forks source link

Have a class macro for traffic control #72

Closed madejejej closed 9 years ago

madejejej commented 9 years ago

Stoplight is good at wrapping whole Rails controllers actions, though sometimes you just want a small piece of the action to be controlled - like integrating with a remote service from which you can recover with good user experience when the service fails. A good example - lets say you want to pull a user's data from a few services. If one of them doesn't respond it's still OK to show the partial data and say "Sorry, this one is out".

For such a use case I'd love to have a class macro that has sensible defaults I can override easily. An example:

class RemoteService
  include Stoplight::TrafficControl

  def remote_call
    # whatever 
  end

  controlls_traffic_on :remote_call, 
    allow_errors: [SomeError], # optional
    threshold: 10, # optional
    timeout: 120, # optional
    name: 'ServiceName', # optional
    on_red: :do_something_different #optional

  def do_something_different
    # whatever
  end
end

I'd love to open a PR for this. Just wanted to hear what you think.

tfausak commented 9 years ago

This is an interesting idea. Do you think that the existing Stoplight method is not well suited to solving this problem? For example, I would wrap remote_call in a stoplight like so:

class RemoteService
  def remote_call
    Stoplight('ServiceName') { remote_call_without_stoplight }
      .with_allowed_errors([SomeError]) # optional
      .with_threshold(10) # optional
      .with_timeout(120) # optional
      .with_fallback { |e| do_something_different } # optional
      .run
  end

  def remote_call_without_stoplight
    # whatever 
  end

  def do_something_different
    # whatever
  end
end

The controls_traffic_on method you are describing would basically be calling Stoplight like that, plus aliasing a few methods.

tfausak commented 9 years ago

What do you think, @s1mplex? Does the existing Stoplight method work for you?

madejejej commented 9 years ago

@tfausak Yeah it works! What I wanted to achieve was to simplify settings things up even more but maybe that'd overcomplicate things too much rather than making it easier.

tfausak commented 9 years ago

In my opinion, it would add too much complexity. I prefer being explicit, especially when it isn't that much more verbose.

Thank you for the suggestion, though!