Search in sources :

Example 6 with Notification

use of rx.Notification in project Hystrix by Netflix.

the class HystrixObservableCommandTest method testRequestContextOnFailureWithFallback.

private RequestContextTestResults testRequestContextOnFailureWithFallback(ExecutionIsolationStrategy isolation, final Scheduler userScheduler) {
    final RequestContextTestResults results = new RequestContextTestResults();
    TestHystrixObservableCommand<Boolean> command = new TestHystrixObservableCommand<Boolean>(TestHystrixObservableCommand.testPropsBuilder(new TestCircuitBreaker()).setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(isolation))) {

        @Override
        protected Observable<Boolean> construct() {
            return Observable.create(new OnSubscribe<Boolean>() {

                @Override
                public void call(Subscriber<? super Boolean> s) {
                    s.onError(new RuntimeException("onError"));
                }
            }).subscribeOn(userScheduler);
        }

        @Override
        protected Observable<Boolean> resumeWithFallback() {
            return Observable.create(new OnSubscribe<Boolean>() {

                @Override
                public void call(Subscriber<? super Boolean> s) {
                    results.isContextInitialized.set(HystrixRequestContext.isCurrentThreadInitialized());
                    results.originThread.set(Thread.currentThread());
                    s.onNext(false);
                    s.onCompleted();
                }
            }).subscribeOn(userScheduler);
        }
    };
    results.command = command;
    command.toObservable().doOnEach(new Action1<Notification<? super Boolean>>() {

        @Override
        public void call(Notification<? super Boolean> n) {
            results.isContextInitializedObserveOn.set(HystrixRequestContext.isCurrentThreadInitialized());
            results.observeOnThread.set(Thread.currentThread());
        }
    }).subscribe(results.ts);
    results.ts.awaitTerminalEvent();
    System.out.println("Run => Initialized: " + results.isContextInitialized.get() + "  Thread: " + results.originThread.get());
    System.out.println("Observed => Initialized: " + results.isContextInitializedObserveOn.get() + "  Thread: " + results.observeOnThread.get());
    assertEquals(0, results.ts.getOnErrorEvents().size());
    assertEquals(1, results.ts.getOnNextEvents().size());
    assertEquals(false, results.ts.getOnNextEvents().get(0));
    assertTrue(command.getExecutionTimeInMilliseconds() > -1);
    assertFalse(command.isSuccessfulExecution());
    assertTrue(command.isFailedExecution());
    assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
    assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
    assertSaneHystrixRequestLog(1);
    return results;
}
Also used : TestCircuitBreaker(com.netflix.hystrix.HystrixCircuitBreakerTest.TestCircuitBreaker) HystrixRuntimeException(com.netflix.hystrix.exception.HystrixRuntimeException) Action1(rx.functions.Action1) TestSubscriber(rx.observers.TestSubscriber) Subscriber(rx.Subscriber) OnSubscribe(rx.Observable.OnSubscribe) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Notification(rx.Notification)

Example 7 with Notification

use of rx.Notification in project ribbon by Netflix.

the class HttpMetaRequest method convertToRibbonResponse.

private Observable<RibbonResponse<Observable<T>>> convertToRibbonResponse(final HystrixObservableCommandChain<T> commandChain, final Observable<ResultCommandPair<T>> hystrixNotificationObservable) {
    return Observable.create(new OnSubscribe<RibbonResponse<Observable<T>>>() {

        @Override
        public void call(final Subscriber<? super RibbonResponse<Observable<T>>> t1) {
            final Subject<T, T> subject = ReplaySubject.create();
            hystrixNotificationObservable.materialize().subscribe(new Action1<Notification<ResultCommandPair<T>>>() {

                AtomicBoolean first = new AtomicBoolean(true);

                @Override
                public void call(Notification<ResultCommandPair<T>> notification) {
                    if (first.compareAndSet(true, false)) {
                        HystrixObservableCommand<T> command = notification.isOnError() ? commandChain.getLastCommand() : notification.getValue().getCommand();
                        t1.onNext(new ResponseWithSubject<T>(subject, command));
                        t1.onCompleted();
                    }
                    if (notification.isOnNext()) {
                        subject.onNext(notification.getValue().getResult());
                    } else if (notification.isOnCompleted()) {
                        subject.onCompleted();
                    } else {
                        // onError
                        subject.onError(notification.getThrowable());
                    }
                }
            });
        }
    });
}
Also used : Action1(rx.functions.Action1) Observable(rx.Observable) Subject(rx.subjects.Subject) ReplaySubject(rx.subjects.ReplaySubject) Notification(rx.Notification) RibbonResponse(com.netflix.ribbon.RibbonResponse) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ResultCommandPair(com.netflix.ribbon.hystrix.ResultCommandPair)

Example 8 with Notification

use of rx.Notification in project nucleus by konmik.

the class DeliverReplay method call.

@Override
public Observable<Delivery<View, T>> call(Observable<T> observable) {
    final ReplaySubject<Notification<T>> subject = ReplaySubject.create();
    final Subscription subscription = observable.materialize().filter(new Func1<Notification<T>, Boolean>() {

        @Override
        public Boolean call(Notification<T> notification) {
            return !notification.isOnCompleted();
        }
    }).subscribe(subject);
    return view.switchMap(new Func1<View, Observable<Delivery<View, T>>>() {

        @Override
        public Observable<Delivery<View, T>> call(final View view) {
            return view == null ? Observable.<Delivery<View, T>>never() : subject.map(new Func1<Notification<T>, Delivery<View, T>>() {

                @Override
                public Delivery<View, T> call(Notification<T> notification) {
                    return new Delivery<>(view, notification);
                }
            });
        }
    }).doOnUnsubscribe(new Action0() {

        @Override
        public void call() {
            subscription.unsubscribe();
        }
    });
}
Also used : Action0(rx.functions.Action0) Subscription(rx.Subscription) Func1(rx.functions.Func1) Notification(rx.Notification)

Example 9 with Notification

use of rx.Notification in project frodo by android10.

the class LogEverythingObservable method get.

@Override
<T> Observable<T> get(T type) throws Throwable {
    final StopWatch stopWatch = new StopWatch();
    final Counter emittedItems = new Counter(joinPoint.getMethodName());
    return ((Observable<T>) joinPoint.proceed()).doOnSubscribe(new Action0() {

        @Override
        public void call() {
            stopWatch.start();
            messageManager.printObservableOnSubscribe(observableInfo);
        }
    }).doOnEach(new Action1<Notification<? super T>>() {

        @Override
        public void call(Notification<? super T> notification) {
            if (!observableInfo.getSubscribeOnThread().isPresent() && (notification.isOnNext() || notification.isOnError())) {
                observableInfo.setSubscribeOnThread(Thread.currentThread().getName());
            }
        }
    }).doOnNext(new Action1<T>() {

        @Override
        public void call(T value) {
            emittedItems.increment();
            messageManager.printObservableOnNextWithValue(observableInfo, value);
        }
    }).doOnError(new Action1<Throwable>() {

        @Override
        public void call(Throwable throwable) {
            messageManager.printObservableOnError(observableInfo, throwable);
        }
    }).doOnCompleted(new Action0() {

        @Override
        public void call() {
            messageManager.printObservableOnCompleted(observableInfo);
        }
    }).doOnTerminate(new Action0() {

        @Override
        public void call() {
            stopWatch.stop();
            observableInfo.setTotalExecutionTime(stopWatch.getTotalTimeMillis());
            observableInfo.setTotalEmittedItems(emittedItems.tally());
            messageManager.printObservableOnTerminate(observableInfo);
            messageManager.printObservableItemTimeInfo(observableInfo);
        }
    }).doOnUnsubscribe(new Action0() {

        @Override
        public void call() {
            if (!observableInfo.getObserveOnThread().isPresent()) {
                observableInfo.setObserveOnThread(Thread.currentThread().getName());
            }
            messageManager.printObservableThreadInfo(observableInfo);
            messageManager.printObservableOnUnsubscribe(observableInfo);
        }
    });
}
Also used : Action0(rx.functions.Action0) Counter(com.fernandocejas.frodo.internal.Counter) Action1(rx.functions.Action1) Observable(rx.Observable) Notification(rx.Notification) StopWatch(com.fernandocejas.frodo.internal.StopWatch)

Example 10 with Notification

use of rx.Notification in project Hystrix by Netflix.

the class AbstractCommand method executeCommandAndObserve.

/**
     * This decorates "Hystrix" functionality around the run() Observable.
     *
     * @return R
     */
private Observable<R> executeCommandAndObserve(final AbstractCommand<R> _cmd) {
    final HystrixRequestContext currentRequestContext = HystrixRequestContext.getContextForCurrentThread();
    final Action1<R> markEmits = new Action1<R>() {

        @Override
        public void call(R r) {
            if (shouldOutputOnNextEvents()) {
                executionResult = executionResult.addEvent(HystrixEventType.EMIT);
                eventNotifier.markEvent(HystrixEventType.EMIT, commandKey);
            }
            if (commandIsScalar()) {
                long latency = System.currentTimeMillis() - executionResult.getStartTimestamp();
                eventNotifier.markCommandExecution(getCommandKey(), properties.executionIsolationStrategy().get(), (int) latency, executionResult.getOrderedList());
                eventNotifier.markEvent(HystrixEventType.SUCCESS, commandKey);
                executionResult = executionResult.addEvent((int) latency, HystrixEventType.SUCCESS);
                circuitBreaker.markSuccess();
            }
        }
    };
    final Action0 markOnCompleted = new Action0() {

        @Override
        public void call() {
            if (!commandIsScalar()) {
                long latency = System.currentTimeMillis() - executionResult.getStartTimestamp();
                eventNotifier.markCommandExecution(getCommandKey(), properties.executionIsolationStrategy().get(), (int) latency, executionResult.getOrderedList());
                eventNotifier.markEvent(HystrixEventType.SUCCESS, commandKey);
                executionResult = executionResult.addEvent((int) latency, HystrixEventType.SUCCESS);
                circuitBreaker.markSuccess();
            }
        }
    };
    final Func1<Throwable, Observable<R>> handleFallback = new Func1<Throwable, Observable<R>>() {

        @Override
        public Observable<R> call(Throwable t) {
            Exception e = getExceptionFromThrowable(t);
            executionResult = executionResult.setExecutionException(e);
            if (e instanceof RejectedExecutionException) {
                return handleThreadPoolRejectionViaFallback(e);
            } else if (t instanceof HystrixTimeoutException) {
                return handleTimeoutViaFallback();
            } else if (t instanceof HystrixBadRequestException) {
                return handleBadRequestByEmittingError(e);
            } else {
                /*
                     * Treat HystrixBadRequestException from ExecutionHook like a plain HystrixBadRequestException.
                     */
                if (e instanceof HystrixBadRequestException) {
                    eventNotifier.markEvent(HystrixEventType.BAD_REQUEST, commandKey);
                    return Observable.error(e);
                }
                return handleFailureViaFallback(e);
            }
        }
    };
    final Action1<Notification<? super R>> setRequestContext = new Action1<Notification<? super R>>() {

        @Override
        public void call(Notification<? super R> rNotification) {
            setRequestContextIfNeeded(currentRequestContext);
        }
    };
    Observable<R> execution;
    if (properties.executionTimeoutEnabled().get()) {
        execution = executeCommandWithSpecifiedIsolation(_cmd).lift(new HystrixObservableTimeoutOperator<R>(_cmd));
    } else {
        execution = executeCommandWithSpecifiedIsolation(_cmd);
    }
    return execution.doOnNext(markEmits).doOnCompleted(markOnCompleted).onErrorResumeNext(handleFallback).doOnEach(setRequestContext);
}
Also used : Action0(rx.functions.Action0) Action1(rx.functions.Action1) HystrixTimeoutException(com.netflix.hystrix.exception.HystrixTimeoutException) TimeoutException(java.util.concurrent.TimeoutException) HystrixRuntimeException(com.netflix.hystrix.exception.HystrixRuntimeException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) HystrixBadRequestException(com.netflix.hystrix.exception.HystrixBadRequestException) HystrixTimeoutException(com.netflix.hystrix.exception.HystrixTimeoutException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) Observable(rx.Observable) Notification(rx.Notification) HystrixBadRequestException(com.netflix.hystrix.exception.HystrixBadRequestException) HystrixRequestContext(com.netflix.hystrix.strategy.concurrency.HystrixRequestContext) Func1(rx.functions.Func1)

Aggregations

Notification (rx.Notification)12 Action1 (rx.functions.Action1)11 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)9 TestCircuitBreaker (com.netflix.hystrix.HystrixCircuitBreakerTest.TestCircuitBreaker)7 HystrixRuntimeException (com.netflix.hystrix.exception.HystrixRuntimeException)7 OnSubscribe (rx.Observable.OnSubscribe)7 Subscriber (rx.Subscriber)7 TestSubscriber (rx.observers.TestSubscriber)7 Observable (rx.Observable)4 Action0 (rx.functions.Action0)4 Func1 (rx.functions.Func1)3 HystrixBadRequestException (com.netflix.hystrix.exception.HystrixBadRequestException)2 HystrixTimeoutException (com.netflix.hystrix.exception.HystrixTimeoutException)2 HystrixRequestContext (com.netflix.hystrix.strategy.concurrency.HystrixRequestContext)2 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)2 TimeoutException (java.util.concurrent.TimeoutException)2 Counter (com.fernandocejas.frodo.internal.Counter)1 StopWatch (com.fernandocejas.frodo.internal.StopWatch)1 HystrixContextScheduler (com.netflix.hystrix.strategy.concurrency.HystrixContextScheduler)1 RibbonResponse (com.netflix.ribbon.RibbonResponse)1