Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add tasks status definition + use HashedWheelTimer in waitFor #393

Merged
merged 4 commits into from
Aug 3, 2017
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/main/scala/algolia/AlgoliaDsl.scala
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ trait AlgoliaDsl
with SearchDsl
with SynonymsDsl
with WaitForTaskDsl
with TaskStatusDsl

object AlgoliaDsl extends AlgoliaDsl {

Expand Down
64 changes: 64 additions & 0 deletions src/main/scala/algolia/definitions/TaskStatusDefinition.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Algolia
* http://www.algolia.com/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

package algolia.definitions

import algolia.http.{GET, HttpPayload}
import algolia.responses.{AlgoliaTask, TaskStatus}
import algolia.{AlgoliaClient, Executable}

import scala.concurrent.{ExecutionContext, Future}

case class TaskStatusDefinition(taskId: Long, index: Option[String] = None) extends Definition {

def from(index: String): TaskStatusDefinition = copy(index = Some(index))

override private[algolia] def build(): HttpPayload = {
HttpPayload(
GET,
Seq("1", "indexes") ++ index ++ Seq("task", taskId.toString),
isSearch = true
)
}

}

trait TaskStatusDsl {

case object getStatus {
def task(task: AlgoliaTask): TaskStatusDefinition =
TaskStatusDefinition(task.idToWaitFor())
}

implicit object TaskStatusExecutable extends Executable[TaskStatusDefinition, TaskStatus] {

override def apply(client: AlgoliaClient, query: TaskStatusDefinition)(
implicit executor: ExecutionContext): Future[TaskStatus] = {
client.request[TaskStatus](query.build())
}

}

}
47 changes: 27 additions & 20 deletions src/main/scala/algolia/definitions/WaitForTaskDefinition.scala
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,12 @@

package algolia.definitions

import java.util.{Timer, TimerTask}
import java.util.concurrent.{Executors, ThreadFactory, TimeUnit}

import algolia.http.{GET, HttpPayload}
import algolia.http.HttpPayload
import algolia.responses.{AlgoliaTask, TaskStatus}
import algolia.{AlgoliaClient, Executable}
import io.netty.util.{HashedWheelTimer, Timeout, TimerTask}

import scala.concurrent.{ExecutionContext, Future, Promise}

Expand All @@ -45,13 +46,8 @@ case class WaitForTaskDefinition(taskId: Long,

def maxDelay(delay: Long): WaitForTaskDefinition = copy(maxDelay = delay)

override private[algolia] def build(): HttpPayload = {
HttpPayload(
GET,
Seq("1", "indexes") ++ index ++ Seq("task", taskId.toString),
isSearch = true
)
}
override private[algolia] def build(): HttpPayload = TaskStatusDefinition(taskId, index).build()

}

trait WaitForTaskDsl {
Expand All @@ -64,6 +60,19 @@ trait WaitForTaskDsl {
implicit object WaitForTaskDefinitionExecutable
extends Executable[WaitForTaskDefinition, TaskStatus] {

// Run every 50 ms, use a wheel with 512 buckets
private lazy val timer = {
val threadFactory = new ThreadFactory {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

couldn't we reuse the thread pool from the execution context?
Not a big fan of hiding a theadFactory.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This ThreadFactory is used to create the worker thread of the wheel, and nothing else. This is the thread that runs the "timed out" timer tasks. The problem of using the given ExecutionContext is that we impose the creation of a long running worker thread in the pool. So if the client passes in a single thread pool, we are left with no thread to execute the map operations over the returned Futures. Also if the created thread is not a daemon thread, it may lead to complications when terminating the application.

In a nutshell, I think it makes more sense for the library to take care of its own worker thread and prevent the user from having to care about it. (That is basically what the current implementation using Timer does!)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, you are right the current implementation was using an internal pool of threads, but I was not very big fan of it.
At least, could you expose the number of threads of this pool in the configuration? So people could tweak it.

Copy link
Contributor Author

@jlogeart jlogeart Aug 2, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It will always be one thread. The real configuration is what HashedWheelTimer offers as parameters:

  • ThreadFactory to determine how to create this single worker thread
  • the tickDuration: how often are timed out tasks being executed by the worker thread
  • the size of the wheel

I am not sure users care too much about all of them but maybe the tickDuration if they are willing to go for "more often" or "more batching". I guess we can add a tickDuration as a FiniteDuration in the WaitForTaskDefinition. It exposes the internals though.

Something like:

case class WaitForTaskDefinition(taskId: Long,
                             index: Option[String] = None,
                             baseDelay: Long = 100,
                             maxDelay: Long = Long.MaxValue,
                             tickDuration: Long = 50)  // using Long here for consistency with the other fields
...

new HashedWheelTimer(threadFactory, query.tickDuration, TimeUnit.MILLISECONDS, 512)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually the whole point being to reuse this HashedWheelTimer for all submitted queries, there is no way to use the query itself to create it.

Given that it is used for network calls, I think 50 or 100 ms is a good number, especially considering the default base delay is 100ms and then 200, 400 etc.

What do you think?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fine by me 😄

override def newThread(r: Runnable): Thread = {
val t = Executors.defaultThreadFactory().newThread(r)
t.setDaemon(true)
t.setName("algolia-waitfor-thread")
t
}
}
new HashedWheelTimer(threadFactory, 50, TimeUnit.MILLISECONDS, 512)
}

/**
* Wait for the completion of a task
* By default it waits `baseDelay` and multiple it by 2 each time until it's greater than `maxDelay`:
Expand All @@ -79,32 +88,30 @@ trait WaitForTaskDsl {
*/
override def apply(client: AlgoliaClient, query: WaitForTaskDefinition)(
implicit executor: ExecutionContext): Future[TaskStatus] = {
def request(d: Long): Future[TaskStatus] =

def request(d: Long, totalDelay: Long): Future[TaskStatus] =
delay[TaskStatus](d) {
client.request[TaskStatus](query.build())
}.flatMap { res =>
if (res.status == "published") {
Future.successful(res)
} else if (d > query.maxDelay) {
} else if (totalDelay > query.maxDelay) {
Future.failed(WaitForTimeoutException(
s"Waiting for task `${query.taskId}` on index `${query.index.get}` timeout after ${d}ms"))
} else {
request(d * 2)
request(d * 2, totalDelay + d)
}
}

request(query.baseDelay)
request(query.baseDelay, 0L)
}

//from http://stackoverflow.com/questions/16359849/scala-scheduledfuture
private def delay[T](delay: Long)(block: => Future[T]): Future[T] = {
val promise = Promise[T]()
val t = new Timer()
t.schedule(new TimerTask {
override def run(): Unit = {
promise.completeWith(block)
}
}, delay)
val task = new TimerTask {
override def run(timeout: Timeout): Unit = promise.completeWith(block)
}
timer.newTimeout(task, delay, TimeUnit.MILLISECONDS)
promise.future
}
}
Expand Down
17 changes: 11 additions & 6 deletions src/test/scala/algolia/AlgoliaTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import algolia.AlgoliaDsl._
import algolia.responses.{AlgoliaTask, TasksMultipleIndex}
import org.scalamock.scalatest.MockFactory
import org.scalatest._
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.concurrent.{Eventually, ScalaFutures}
import org.scalatest.time.{Millis, Seconds, Span}

import scala.concurrent.{ExecutionContext, Future}
Expand All @@ -43,7 +43,8 @@ class AlgoliaTest
with ScalaFutures
with Inside
with MockFactory
with EitherValues {
with EitherValues
with Eventually {

val applicationId: String = System.getenv("APPLICATION_ID")
val apiKey: String = System.getenv("API_KEY")
Expand All @@ -61,12 +62,16 @@ class AlgoliaTest
client.close()
}

def taskShouldBeCreatedAndWaitForIt(task: Future[AlgoliaTask], index: String)(
implicit ec: ExecutionContext): Unit = {
val t: AlgoliaTask = whenReady(task) { result =>
def taskShouldBeCreated(task: Future[AlgoliaTask])(implicit ec: ExecutionContext): AlgoliaTask = {
whenReady(task) { result =>
result.idToWaitFor should not be 0
result //for getting it after
result
}
}

def taskShouldBeCreatedAndWaitForIt(task: Future[AlgoliaTask], index: String)(
implicit ec: ExecutionContext): Unit = {
val t: AlgoliaTask = taskShouldBeCreated(task)

val waiting = client.execute {
waitFor task t from index maxDelay (60 * 10 * 1000) //600 seconds
Expand Down
52 changes: 52 additions & 0 deletions src/test/scala/algolia/dsl/TaskStatusTest.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Algolia
* http://www.algolia.com/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

package algolia.dsl

import algolia.AlgoliaDsl._
import algolia.AlgoliaTest
import algolia.http.{GET, HttpPayload}
import algolia.responses.Task

class TaskStatusTest extends AlgoliaTest {

describe("get task status") {

it("get the status of a task") {
getStatus task Task(1L, None) from "toto"
}

it("should call API") {
(getStatus task Task(1L, None) from "toto").build() should be(
HttpPayload(
GET,
Seq("1", "indexes", "toto", "task", "1"),
isSearch = true
)
)
}
}

}
73 changes: 73 additions & 0 deletions src/test/scala/algolia/integration/TaskStatusIntegrationTest.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Algolia
* http://www.algolia.com/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

package algolia.integration

import algolia.AlgoliaDsl._
import algolia.AlgoliaTest
import algolia.responses.{TaskIndexing, TasksMultipleIndex}

import scala.concurrent.Future

class TaskStatusIntegrationTest extends AlgoliaTest {

after {
clearIndices("indexToGetTaskStatus")
}

it("should get the status of a single object task") {
val create: Future[TaskIndexing] = client.execute {
index into "indexToGetTaskStatus" `object` ObjectToGet("1", "toto")
}

val task = taskShouldBeCreated(create)

eventually {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do you need the eventually?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same question for the test below

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need eventually because it takes some time for a task to be actually published: the very frirst call may indicate the task as "pending" and not "published".

So eventually retries (as defined in Eventually) until the block does not throw any exception (in our case a TestFailedException if the status is not "published").

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok make sense

val status = client.execute { getStatus task task from "indexToGetTaskStatus" }
whenReady(status) { result =>
result.status == "published"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldn't there be a assertion here?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same question for the test below

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah you are right. Fixed.

}
}
}

it("should get the status of a multiple objects task") {
val create: Future[TasksMultipleIndex] = client.execute {
batch(
index into "indexToGetTaskStatus" `object` ObjectToGet("1", "toto"),
index into "indexToGetTaskStatus" `object` ObjectToGet("2", "tata")
)
}

val task = taskShouldBeCreated(create)

eventually {
val status = client.execute { getStatus task task from "indexToGetTaskStatus" }
whenReady(status) { result =>
result.status == "published"
}
}
}

}