Knotx / knotx-fragments

Fragments map-reduce processing using Graph flows, supplier and assembler.
https://knotx.io
Apache License 2.0
3 stars 5 forks source link

AsyncFragmentOperation interface for asynchronous actions #185

Closed marcinus closed 4 years ago

marcinus commented 4 years ago

Is your feature request related to a problem? Please describe. Library actions that are asynchronous:

Also, consistent error handling could be enforced - now these things may occur:

Describe the solution you'd like

Create AsyncFragmentOperation interface

package io.knotx.fragments.api;

import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;

public interface AsyncFragmentOperation extends FragmentOperation {

  @Override
  default void apply(FragmentContext fragmentContext, Handler<AsyncResult<FragmentResult>> resultHandler) {
    tryApply(fragmentContext).onComplete(resultHandler);
  }

  default Future<FragmentResult> tryApply(FragmentContext fragmentContext) {
    try {
      Future<FragmentResult> result = apply(fragmentContext);
      if (result != null) {
        return result;
      } else {
        return Future.failedFuture(
            new IllegalStateException("Action " + this.getClass().getName()
                                          + " returned null Future. Created failed Future to pass information to handler.")
        );
      }
    } catch (Throwable t) {
      return Future.failedFuture(t);
    }
  }

  Future<FragmentResult> apply(FragmentContext fragmentContext);

}

With the following semantics:

Unfortunatelly, failed future in this case encapsulates all three cases (failure within action, null result and exception thrown from action). However, each time we're dealing with an exception so I believe this is not an issue and can simplify error handling in the whole knotx-fragments repository.

Describe alternatives you've considered N/A

Additional context Relates to #184

tomaszmichalak commented 4 years ago

Fixed.