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

com.github.tonivade.purefun.effect.Task 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.Function2.first;
import static com.github.tonivade.purefun.Function2.second;
import static com.github.tonivade.purefun.Nothing.nothing;
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.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 Task implements TaskOf, Effect, Recoverable {

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

  private final PureIO instance;

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

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

  public EIO toEIO() {
    return new EIO<>(instance);
  }

  @SuppressWarnings("unchecked")
  public  RIO toURIO() {
    return new RIO<>((PureIO)instance);
  }
  
  public UIO toUIO() {
    return recover(this::sneakyThrow);
  }

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

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

  public Future runAsync(Executor executor) {
    return Task.forked(executor).andThen(this).runAsync();
  }

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

  @Override
  public  Task map(Function1 map) {
    return flatMap(lift(map));
  }

  @Override
  public  Task flatMap(Function1> map) {
    return new Task<>(instance.flatMap(value -> {
      Task apply = map.andThen(TaskOf::narrowK).apply(value);
      return apply.instance;
    }));
  }

  @Override
  public  Task andThen(Kind next) {
    return new Task<>(instance.andThen(next.fix(TaskOf.toTask()).instance));
  }

  @Override
  public  Task ap(Kind> apply) {
    return new Task<>(instance.ap(apply.fix(TaskOf.toTask()).instance));
  }

  public  Task foldM(
      Function1> mapError, 
      Function1> map) {
    return new Task<>(instance.foldM(
        error -> mapError.andThen(TaskOf::narrowK).apply(error).instance, 
        value -> map.andThen(TaskOf::narrowK).apply(value).instance));
  }

  public  UIO fold(
      Function1 mapError, Function1 map) {
    return new UIO<>(instance.fold(mapError, map).toPureIO());
  }

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

  public UIO recover(Function1 mapError) {
    return new UIO<>(instance.recover(mapError).toPureIO());
  }

  public Task orElse(Kind other) {
    return new Task<>(instance.orElse(other.fix(TaskOf.toTask()).instance));
  }
  
  @Override
  public  Task> zip(Kind other) {
    return zipWith(other, Tuple::of);
  }
  
  @Override
  public  Task zipLeft(Kind other) {
    return zipWith(other, first());
  }
  
  @Override
  public  Task zipRight(Kind other) {
    return zipWith(other, second());
  }
  
  @Override
  public  Task zipWith(Kind other, 
      Function2 mapper) {
    return parMap2(this, other.fix(TaskOf.toTask()), mapper);
  }
  
  public Task> fork() {
    return new Task<>(instance.fork().map(f -> f.mapK(new FunctionK, Throwable>, Task_>() {
      @Override
      public  Task apply(Kind, Throwable>, ? extends T> from) {
        return new Task<>(from.fix(PureIOOf::narrowK));
      }
    })));
  }

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

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

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

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

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

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

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

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

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

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

  public static  Task parMap2(Kind za, Kind zb, 
      Function2 mapper) {
    return parMap2(Future.DEFAULT_EXECUTOR, za, zb, mapper);
  }

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

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

  public static  Function1> lift(Function1 function) {
    return PureIO.lift(function).andThen(Task::new);
  }

  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  Task fromOption(Option task) {
    return fromOption(cons(task));
  }

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

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

  public static  Task fromTry(Producer> task) {
    return fromEither(task.andThen(Try::toEither));
  }

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

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

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

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

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

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

  public static  Task defer(Producer> lazy) {
    return new Task<>(PureIO.defer(() -> lazy.andThen(TaskOf::narrowK).get().instance));
  }

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

  public static  Task raiseError(Throwable error) {
    return new Task<>(PureIO.raiseError(error));
  }

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

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

  public static  Task bracket(
      Kind acquire, Function1> use) {
    return new Task<>(PureIO.bracket(acquire.fix(TaskOf::narrowK).instance, resource -> use.andThen(TaskOf::narrowK).apply(resource).instance));
  }

  public static  Task bracket(
      Kind acquire, Function1> use, Consumer1 release) {
    return new Task<>(PureIO.bracket(acquire.fix(TaskOf::narrowK).instance, resource -> use.andThen(TaskOf::narrowK).apply(resource).instance, release));
  }

  public static  Task bracket(
      Kind acquire, Function1> use, Function1> release) {
    return new Task<>(PureIO.bracket(acquire.fix(TaskOf::narrowK).instance, resource -> use.andThen(TaskOf::narrowK).apply(resource).instance, release.andThen(TaskOf::narrowK).andThen(Task::toPureIO)));
  }

  public static Task unit() {
    return UNIT;
  }
}