All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.atleon.core.ErrorEmitter Maven / Gradle / Ivy

package io.atleon.core;

import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Sinks;

import java.time.Duration;

/**
 * Utility class wrapping a {@link Sinks.Empty} that allows applying to Publishers and
 * safe, timeout-based error emission.
 *
 * @param  The type of elements emitted in merged Publishers
 */
public final class ErrorEmitter {

    public static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(10L);

    private static final Logger LOGGER = LoggerFactory.getLogger(ErrorEmitter.class);

    private final Duration timeout;

    private final Sinks.Empty sink = Sinks.empty();

    private ErrorEmitter(Duration timeout) {
        this.timeout = timeout;
    }

    public static  ErrorEmitter create() {
        return new ErrorEmitter<>(DEFAULT_TIMEOUT);
    }

    public static  ErrorEmitter create(Duration timeout) {
        return new ErrorEmitter<>(timeout);
    }

    public Flux applyTo(Publisher publisher) {
        return Flux.from(publisher).mergeWith(sink.asMono());
    }

    public void safelyEmit(Throwable error) {
        try {
            sink.emitError(error, Sinks.EmitFailureHandler.busyLooping(timeout));
        } catch (Sinks.EmissionException emissionException) {
            LOGGER.info("Failed to emit error due to reason=" + emissionException.getReason());
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy