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

com.github.tonivade.purefun.effect.RIO Maven / Gradle / Ivy

/*
 * Copyright (c) 2018-2022, Antonio Gabriel Muñoz Conejo 
 * Distributed under the terms of the MIT License
 */
package com.github.tonivade.purefun.effect;

import static com.github.tonivade.purefun.Function1.identity;
import static com.github.tonivade.purefun.Function2.first;
import static com.github.tonivade.purefun.Function2.second;
import static com.github.tonivade.purefun.Precondition.checkNonNull;
import static com.github.tonivade.purefun.Producer.cons;
import java.time.Duration;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeoutException;
import com.github.tonivade.purefun.CheckedRunnable;
import com.github.tonivade.purefun.Consumer1;
import com.github.tonivade.purefun.Consumer2;
import com.github.tonivade.purefun.Effect;
import com.github.tonivade.purefun.Function1;
import com.github.tonivade.purefun.Function2;
import com.github.tonivade.purefun.HigherKind;
import com.github.tonivade.purefun.Kind;
import com.github.tonivade.purefun.Nothing;
import com.github.tonivade.purefun.Producer;
import com.github.tonivade.purefun.Recoverable;
import com.github.tonivade.purefun.Tuple;
import com.github.tonivade.purefun.Tuple2;
import com.github.tonivade.purefun.Unit;
import com.github.tonivade.purefun.concurrent.Future;
import com.github.tonivade.purefun.data.ImmutableList;
import com.github.tonivade.purefun.data.Sequence;
import com.github.tonivade.purefun.type.Either;
import com.github.tonivade.purefun.type.Option;
import com.github.tonivade.purefun.type.Try;
import com.github.tonivade.purefun.typeclasses.Fiber;
import com.github.tonivade.purefun.typeclasses.FunctionK;

@HigherKind
public final class RIO implements RIOOf, Effect, A>, Recoverable {

  private static final RIO UNIT = new RIO<>(PureIO.unit());

  private final PureIO instance;

  RIO(PureIO value) {
    this.instance = checkNonNull(value);
  }

  public Try safeRunSync(R env) {
    return Try.fromEither(instance.provide(env));
  }

  public PureIO toPureIO() {
    return instance;
  }

  @SuppressWarnings("unchecked")
  public  EIO toEIO() {
    return new EIO<>((PureIO) instance);
  }
  
  public URIO toURIO() {
    return recover(this::sneakyThrow);
  }

  public Future runAsync(R env) {
    return instance.runAsync(env).flatMap(e -> e.fold(Future::failure, Future::success));
  }

  public Future runAsync(R env, Executor executor) {
    return RIO.forked(executor).andThen(this).runAsync(env);
  }

  public void safeRunAsync(R env, Consumer1> callback) {
    instance.provideAsync(env, result -> callback.accept(result.flatMap(Try::fromEither)));
  }

  @Override
  public  RIO map(Function1 map) {
    return new RIO<>(instance.map(map));
  }

  @Override
  public  RIO flatMap(Function1, ? extends B>> map) {
    return new RIO<>(instance.flatMap(x -> {
      RIO apply = map.andThen(RIOOf::narrowK).apply(x);
      return apply.instance;
    }));
  }

  @Override
  public  RIO andThen(Kind, ? extends B> next) {
    return new RIO<>(instance.andThen(next.fix(RIOOf.toRIO()).instance));
  }

  @Override
  public  RIO ap(Kind, Function1> apply) {
    return new RIO<>(instance.ap(apply.fix(RIOOf.toRIO()).instance));
  }

  public URIO recover(Function1 mapError) {
    return fold(mapError, identity());
  }

  @SuppressWarnings("unchecked")
  public  URIO recoverWith(Class type, Function1 function) {
    return recover(cause -> {
      if (type.isAssignableFrom(cause.getClass())) {
        return function.apply((X) cause);
      }
      return sneakyThrow(cause);
    });
  }

  public  URIO fold(
      Function1 mapError, Function1 map) {
    return new URIO<>(instance.foldM(mapError.andThen(PureIO::pure), map.andThen(PureIO::pure)));
  }

  public  RIO foldM(
      Function1, ? extends B>> mapError, 
      Function1, ? extends B>> map) {
    return new RIO<>(instance.foldM(
        error -> mapError.andThen(RIOOf::narrowK).apply(error).instance, 
        value -> map.andThen(RIOOf::narrowK).apply(value).instance));
  }

  public RIO orElse(Kind, ? extends A> other) {
    return foldM(Function1.cons(other), Function1.cons(this));
  }
  
  @Override
  public  RIO> zip(Kind, ? extends B> other) {
    return zipWith(other, Tuple::of);
  }
  
  @Override
  public  RIO zipLeft(Kind, ? extends B> other) {
    return zipWith(other, first());
  }
  
  @Override
  public  RIO zipRight(Kind, ? extends B> other) {
    return zipWith(other, second());
  }
  
  @Override
  public  RIO zipWith(Kind, ? extends B> other, 
      Function2 mapper) {
    return parMap2(this, other.fix(RIOOf.toRIO()), mapper);
  }
  
  public RIO, A>> fork() {
    return new RIO<>(instance.fork().map(f -> f.mapK(new FunctionK, Throwable>, Kind>() {
      @Override
      public  RIO apply(Kind, Throwable>, ? extends T> from) {
        return new RIO<>(from.fix(PureIOOf::narrowK));
      }
    })));
  }

  public RIO timeout(Duration duration) {
    return timeout(Future.DEFAULT_EXECUTOR, duration);
  }
  
  public RIO timeout(Executor executor, Duration duration) {
    return racePair(executor, this, sleep(duration)).flatMap(either -> either.fold(
        ta -> ta.get2().cancel().fix(RIOOf.toRIO()).map(x -> ta.get1()),
        tb -> tb.get1().cancel().fix(RIOOf.toRIO()).flatMap(x -> RIO.raiseError(new TimeoutException()))));
  }

  @Override
  public RIO repeat() {
    return repeat(1);
  }

  @Override
  public RIO repeat(int times) {
    return new RIO<>(instance.repeat(times));
  }

  @Override
  public RIO repeat(Duration delay) {
    return repeat(delay, 1);
  }

  @Override
  public RIO repeat(Duration delay, int times) {
    return new RIO<>(instance.repeat(delay, times));
  }
  
  public  RIO repeat(Schedule schedule) {
    return new RIO<>(instance.repeat(schedule));
  }

  @Override
  public RIO retry() {
    return retry(1);
  }

  @Override
  public RIO retry(int maxRetries) {
    return retry(Schedule.recurs(maxRetries));
  }

  @Override
  public RIO retry(Duration delay) {
    return retry(delay, 1);
  }

  @Override
  public RIO retry(Duration delay, int maxRetries) {
    return retry(Schedule.recursSpaced(delay, maxRetries));
  }
  
  public  RIO retry(Schedule schedule) {
    return new RIO<>(instance.retry(schedule));
  }

  @Override
  public RIO> timed() {
    return new RIO<>(instance.timed());
  }
  
  public static  RIO forked(Executor executor) {
    return async((env, callback) -> executor.execute(() -> callback.accept(Try.success(Unit.unit()))));
  }

  public static  RIO accessM(Function1> map) {
    return new RIO<>(PureIO.accessM(map.andThen(RIO::toPureIO)));
  }

  public static  RIO access(Function1 map) {
    return accessM(map.andThen(RIO::pure));
  }

  public static  RIO env() {
    return access(identity());
  }

  public static  RIO absorb(RIO> value) {
    return new RIO<>(PureIO.absorb(value.instance));
  }

  public static  RIO parMap2(Kind, ? extends A> za, Kind, ? extends B> zb, 
      Function2 mapper) {
    return parMap2(Future.DEFAULT_EXECUTOR, za, zb, mapper);
  }

  public static  RIO parMap2(Executor executor, Kind, ? extends A> za, Kind, ? extends B> zb, 
      Function2 mapper) {
    return new RIO<>(PureIO.parMap2(executor, za.fix(RIOOf::narrowK).instance, zb.fix(RIOOf::narrowK).instance, mapper));
  }
  
  public static  RIO> race(Kind, ? extends A> fa, Kind, ? extends B> fb) {
    return race(Future.DEFAULT_EXECUTOR, fa, fb);
  }
  
  public static  RIO> race(Executor executor, Kind, ? extends A> fa, Kind, ? extends B> fb) {
    return racePair(executor, fa, fb).flatMap(either -> either.fold(
        ta -> ta.get2().cancel().fix(RIOOf.toRIO()).map(x -> Either.left(ta.get1())),
        tb -> tb.get1().cancel().fix(RIOOf.toRIO()).map(x -> Either.right(tb.get2()))));
  }
  
  public static  RIO, B>>, Tuple2, A>, B>>> 
      racePair(Executor executor, Kind, ? extends A> fa, Kind, ? extends B> fb) {
    PureIO instance1 = fa.fix(RIOOf.toRIO()).instance.fix(PureIOOf::narrowK);
    PureIO instance2 = fb.fix(RIOOf.toRIO()).instance.fix(PureIOOf::narrowK);
    return new RIO<>(PureIO.racePair(executor, instance1, instance2).map(
      either -> either.bimap(a -> a.map2(f -> f.mapK(new FunctionK, Throwable>, Kind>() {
        @Override
        public  RIO apply(Kind, Throwable>, ? extends T> from) {
          return new RIO<>(from.fix(PureIOOf::narrowK));
        }
      })), b -> b.map1(f -> f.mapK(new FunctionK, Throwable>, Kind>() {
        @Override
        public  RIO apply(Kind, Throwable>, ? extends T> from) {
          return new RIO<>(from.fix(PureIOOf::narrowK));
        }
      })))));
  }

  public static  RIO sleep(Duration delay) {
    return sleep(Future.DEFAULT_EXECUTOR, delay);
  }

  public static  RIO sleep(Executor executor, Duration delay) {
    return new RIO<>(PureIO.sleep(executor, delay));
  }

  public static  Function1> lift(Function1 function) {
    return value -> task(() -> function.apply(value));
  }

  public static  Function1> liftOption(Function1> function) {
    return value -> fromOption(function.apply(value));
  }

  public static  Function1> liftTry(Function1> function) {
    return value -> fromTry(function.apply(value));
  }

  public static  Function1> liftEither(Function1> function) {
    return value -> fromEither(function.apply(value));
  }

  public static  RIO fromOption(Option task) {
    return fromOption(cons(task));
  }

  public static  RIO fromOption(Producer> task) {
    return fromEither(task.andThen(Option::toEither));
  }

  public static  RIO fromTry(Try task) {
    return fromTry(cons(task));
  }

  public static  RIO fromTry(Producer> task) {
    return new RIO<>(PureIO.fromTry(task));
  }

  public static  RIO fromEither(Either task) {
    return fromEither(cons(task));
  }

  public static  RIO fromEither(Producer> task) {
    return new RIO<>(PureIO.fromEither(task));
  }

  public static  RIO exec(CheckedRunnable task) {
    return new RIO<>(PureIO.exec(task));
  }

  public static  RIO pure(A value) {
    return new RIO<>(PureIO.pure(value));
  }

  public static  RIO raiseError(Throwable throwable) {
    return new RIO<>(PureIO.raiseError(throwable));
  }

  public static  RIO defer(Producer, ? extends A>> lazy) {
    return new RIO<>(PureIO.defer(() -> lazy.andThen(RIOOf::narrowK).get().instance));
  }

  public static  RIO task(Producer task) {
    return new RIO<>(PureIO.task(task));
  }
  
  public static  RIO never() {
    return async((env, cb) -> {});
  }
  
  public static  RIO async(Consumer2>> consumer) {
    return new RIO<>(PureIO.async(
      (env, cb1) -> consumer.accept(env, result -> cb1.accept(result.map(Either::right)))));
  }
  
  public static  RIO cancellable(Function2>, RIO> consumer) {
    return new RIO<>(PureIO.cancellable(
      (env, cb1) -> consumer.andThen(RIO::toPureIO).apply(env, result -> cb1.accept(result.map(Either::right)))));
  }

  public static  RIO> traverse(Sequence> sequence) {
    return traverse(Future.DEFAULT_EXECUTOR, sequence);
  }

  public static  RIO> traverse(Executor executor, Sequence> sequence) {
    return sequence.foldLeft(pure(ImmutableList.empty()), 
        (RIO> xs, RIO a) -> parMap2(executor, xs, a, Sequence::append));
  }

  public static  RIO bracket(Kind, ? extends A> acquire, 
      Function1, ? extends B>> use) {
    return new RIO<>(PureIO.bracket(acquire.fix(RIOOf::narrowK).instance, 
        resource -> use.andThen(RIOOf::narrowK).apply(resource).instance));
  }

  public static  RIO bracket(Kind, ? extends A> acquire, 
      Function1, ? extends B>> use, Consumer1 release) {
    return new RIO<>(PureIO.bracket(acquire.fix(RIOOf::narrowK).instance, 
        resource -> use.andThen(RIOOf::narrowK).apply(resource).instance, release));
  }

  public static  RIO bracket(Kind, ? extends A> acquire, 
      Function1, ? extends B>> use, Function1, Unit>> release) {
    return new RIO<>(PureIO.bracket(acquire.fix(RIOOf::narrowK).instance, 
        resource -> use.andThen(RIOOf::narrowK).apply(resource).instance, release.andThen(RIOOf::narrowK).andThen(RIO::toPureIO)));
  }

  @SuppressWarnings("unchecked")
  public static  RIO unit() {
    return (RIO) UNIT;
  }
}