Minor refactoring in CachePolicy

Preparing the ground for TTLs
This commit is contained in:
Alexandre Archambault 2015-07-08 11:47:02 +01:00
parent 9f01dad027
commit ef09b62f3c
3 changed files with 38 additions and 20 deletions

View File

@ -80,7 +80,13 @@ case class MavenRepository(
)
}
EitherT(cachePolicy.saving(locally(localFile))(remote)(save))
EitherT(
cachePolicy[String \/ String](
_.isLeft )(
locally(localFile) )(
_ => CachePolicy.saving(remote)(save)
)
)
}
}

View File

@ -455,18 +455,18 @@ abstract class BaseMavenRepository(
}
sealed trait CachePolicy {
def apply[E,T](local: => Task[E \/ T])
(remote: => Task[E \/ T]): Task[E \/ T]
def saving[E,T](local: => Task[E \/ T])
(remote: => Task[E \/ T])
(save: => T => Task[Unit]): Task[E \/ T] =
apply(local)(CachePolicy.saving(remote)(save))
def apply[T](
tryRemote: T => Boolean )(
local: => Task[T] )(
remote: Option[T] => Task[T]
): Task[T]
}
object CachePolicy {
def saving[E,T](remote: => Task[E \/ T])
(save: T => Task[Unit]): Task[E \/ T] = {
def saving[E,T](
remote: => Task[E \/ T] )(
save: T => Task[Unit]
): Task[E \/ T] = {
for {
res <- remote
_ <- res.fold(_ => Task.now(()), t => save(t))
@ -474,19 +474,28 @@ object CachePolicy {
}
case object Default extends CachePolicy {
def apply[E,T](local: => Task[E \/ T])
(remote: => Task[E \/ T]): Task[E \/ T] =
def apply[T](
tryRemote: T => Boolean )(
local: => Task[T] )(
remote: Option[T] => Task[T]
): Task[T] =
local
.flatMap(res => if (res.isLeft) remote else Task.now(res))
.flatMap(res => if (tryRemote(res)) remote(Some(res)) else Task.now(res))
}
case object LocalOnly extends CachePolicy {
def apply[E,T](local: => Task[E \/ T])
(remote: => Task[E \/ T]): Task[E \/ T] =
def apply[T](
tryRemote: T => Boolean )(
local: => Task[T] )(
remote: Option[T] => Task[T]
): Task[T] =
local
}
case object ForceDownload extends CachePolicy {
def apply[E,T](local: => Task[E \/ T])
(remote: => Task[E \/ T]): Task[E \/ T] =
remote
def apply[T](
tryRemote: T => Boolean )(
local: => Task[T] )(
remote: Option[T] => Task[T]
): Task[T] =
remote(None)
}
}

View File

@ -143,8 +143,11 @@ case class Files(
val tasks =
for ((f, url) <- pairs if url != ("file:" + f) && url != ("file://" + f)) yield {
val file = new File(f)
cachePolicy(locally(file))(remote(file, url))
.map(e => (file, url) -> e.map(_ => ()))
cachePolicy[FileError \/ File](
_.isLeft )(
locally(file) )(
_ => remote(file, url)
).map(e => (file, url) -> e.map(_ => ()))
}
Nondeterminism[Task].gather(tasks)