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

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

/*
 * Copyright (c) 2018-2021, 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 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 URIO implements URIOOf, Effect, A>, Recoverable {

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

  private final PureIO instance;

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

  public A unsafeRunSync(R env) {
    return instance.provide(env).get();
  }

  public Try safeRunSync(R env) {
    return Try.of(() -> unsafeRunSync(env));
  }

  @SuppressWarnings("unchecked")
  public  PureIO toPureIO() {
    return (PureIO) instance;
  }

  @SuppressWarnings("unchecked")
  public  EIO toEIO() {
    return new EIO<>((PureIO) instance);
  }

  public RIO toRIO() {
    return new RIO<>(PureIO.redeem(instance));
  }

  public Future runAsync(R env) {
    return instance.runAsync(env).map(Either::getRight);
  }

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

  public void safeRunAsync(R env, Consumer1> callback) {
    instance.provideAsync(env, result -> callback.accept(result.map(Either::getRight)));
  }

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

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

  @Override
  public  URIO andThen(Kind, ? extends B> next) {
    return new URIO<>(instance.andThen(next.fix(URIOOf.toURIO()).instance));
  }
  
  @Override
  public  URIO ap(Kind, Function1> apply) {
    return new URIO<>(instance.ap(apply.fix(URIOOf.toURIO()).instance));
  }

  public URIO recover(Function1 mapError) {
    return redeem(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 redeem(
      Function1 mapError, Function1 map) {
    return redeemWith(mapError.andThen(URIO::pure), map.andThen(URIO::pure));
  }

  public  URIO redeemWith(
      Function1, ? extends B>> mapError, 
      Function1, ? extends B>> map) {
    return new URIO<>(PureIO.redeem(instance).foldM(
        error -> mapError.andThen(URIOOf::narrowK).apply(error).instance, 
        value -> map.andThen(URIOOf::narrowK).apply(value).instance));
  }
  
  @Override
  public  URIO> zip(Kind, ? extends B> other) {
    return zipWith(other, Tuple::of);
  }
  
  @Override
  public  URIO zipLeft(Kind, ? extends B> other) {
    return zipWith(other, first());
  }
  
  @Override
  public  URIO zipRight(Kind, ? extends B> other) {
    return zipWith(other, second());
  }
  
  @Override
  public  URIO zipWith(Kind, ? extends B> other, 
      Function2 mapper) {
    return parMap2(this, other.fix(URIOOf.toURIO()), mapper);
  }
  
  public URIO, A>> fork() {
    return new URIO<>(instance.fork().map(f -> f.mapK(new FunctionK, Nothing>, Kind>() {
      @Override
      public  URIO apply(Kind, Nothing>, ? extends T> from) {
        return new URIO<>(from.fix(PureIOOf::narrowK));
      }
    })));
  }

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

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

  @Override
  public URIO repeat(int times) {
    return fold(PureIO.redeem(instance).repeat(times));
  }

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

  @Override
  public URIO repeat(Duration delay, int times) {
    return fold(PureIO.redeem(instance).repeat(delay, times));
  }
  
  public  URIO repeat(Schedule schedule) {
    return fold(PureIO.redeem(instance).repeat(schedule));
  }

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

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

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

  @Override
  public URIO retry(Duration delay, int maxRetries) {
    return retry(Schedule.recursSpaced(delay, maxRetries));
  }
  
  public  URIO retry(Schedule schedule) {
    return fold(PureIO.redeem(instance).retry(schedule));
  }

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

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

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

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

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

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

  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  URIO sleep(Duration delay) {
    return fold(PureIO.sleep(delay));
  }

  public static  URIO exec(CheckedRunnable task) {
    return fold(PureIO.exec(task));
  }

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

  public static  URIO raiseError(Throwable throwable) {
    return new URIO<>(PureIO.fromEither(() -> { throw throwable; }));
  }

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

  public static  URIO task(Producer task) {
    return fold(PureIO.task(task));
  }

  public static  URIO fromOption(Option task) {
    return fromEither(task.toEither());
  }

  public static  URIO fromTry(Try task) {
    return fromEither(task.toEither());
  }

  public static  URIO fromEither(Either task) {
    return task.fold(URIO::raiseError, URIO::pure);
  }
  
  public static  URIO never() {
    return async((env, cb) -> {});
  }
  
  public static  URIO async(Consumer2>> consumer) {
    return fold(PureIO.async(
        (env, cb1) -> consumer.accept(env, result -> cb1.accept(result.map(Either::right)))));
  }
  
  public static  URIO cancellable(Function2>, URIO> consumer) {
    return fold(PureIO.cancellable(
        (env, cb1) -> consumer.andThen(URIO::toPureIO).apply(env, result -> cb1.accept(result.map(Either::right)))));
  }

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

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

  public static  URIO bracket(
    Kind, ? extends A> acquire, Function1, ? extends B>> use) {
    return fold(PureIO.bracket(PureIO.redeem(acquire.fix(URIOOf::narrowK).instance), 
        resource -> PureIO.redeem(use.andThen(URIOOf::narrowK).apply(resource).instance)));
  }

  public static  URIO bracket(Kind, ? extends A> acquire, 
      Function1, ? extends B>> use, Consumer1 release) {
    return fold(PureIO.bracket(PureIO.redeem(acquire.fix(URIOOf::narrowK).instance), 
        resource -> PureIO.redeem(use.andThen(URIOOf::narrowK).apply(resource).instance), release));
  }

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

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

  private static  URIO fold(PureIO zio) {
    return new URIO<>(zio.foldM(error -> URIO.raiseError(error).instance, value -> URIO.pure(value).instance));
  }
}