BlazeServerBuilder asking for extra parameter - scala

I'm trying to write a simple http server in scala with http4. But when I follow tutorials to create a BlazeServer builder, it will say that I need to supply a Timer[IO] (gives me the error Unspecified value parameters: timer: Timer[IO]), which I can't seem to find any information on why.
val server = BlazeServerBuilder[IO](global)

As Luis said, probably worth using the scala seed for http4s quickstart by calling
$ sbt new http4s/http4s.g8 --branch 0.23
This will give you a good idea about how to put together the server and routes and config)
In regards to your question, if you are using Blaze, you can see that timer is one of the implicit parametera for apply, this is the signature (in 0.21.9)
def apply[F[_]](executionContext: ExecutionContext)(implicit
F: ConcurrentEffect[F],
timer: Timer[F]): BlazeServerBuilder[F]
you can create an implicit timer like this, assuming you have an implicit execution context (in the code below, that is ec)
implicit val timer: Timer[IO] = IO.timer(ec)

Related

What exactly Ciris.ConfigDecoder does in scala

I am new to scala and trying to support an application written in scala using ciris package.
I want to understand the is ciris ConfigDecoder and what the below code is trying to do.
#inline implicit def sourceTopicsConfigDecoder(implicit ev: ConfigDecoder[String, NonEmptyString]): ConfigDecoder[String, SourceTopics] =
ev.map(_.value.split(",").toSet.map(NonEmptyString.unsafeFrom)) map SourceTopics.apply
#inline implicit val sourceTopicsShow: Show[SourceTopics] =
_.unMk.mkString(",")
I've never used (or even heard of) Ciris before, but a quick visit to the documentation informs me that ConfigDecoder is the means by which the received configuration type (usually a String) is cast to a more useful type. Something like: env("SIZE_LIMIT").as[Long]
I also learned that, while many useful ConfigDecoders are supplied, you can also make your own for decoding configuration values into application specific types, and that's what sourceTopicsConfigDecoder appears to be doing. It pulls an existing String-to-NonEmptyString decoder from the implicit scope and uses it to build a String-to-SourceTopics decoder. (SourceTopics must be previously defined.)
The new decoder is made implicit so that elsewhere in the code you can do something like: env("SRC_TOPICS").as[SourceTopics]

where is the implicit being supplied from when i invoke akka.http.scaladsl.Http.apply()?

I am using Akka HTTP for REST support, and I need to use Actors in another part of the
server I'm developing. My understanding is that one typically needs to use exactly ONE ActorSystem
instance throughout one's application. From the definition of akka.http.scaladsl.Http.apply(),
it seems that when I use the Http method, as in the snippet from my code below --
val service: FooRestService = new FooRestService()
Http(). bindAndHandle(service.route, "localhost", 8080) // something is supplying the imply method w/ implicit ActorSystem !
--- somehow the Http object's apply() method is getting supplied with an implicit ActorSystem instance... For easy reference, Http.apply() is defined like this:
package akka.http.scaladsl.Http
...
object Http {
...
def apply()(implicit system: ActorSystem): HttpExt = super.apply(system)
Since I need to stick to exactly one ActorSystem instance, I want to supply the other (non-REST) Actor-based code in my system with the
SAME reference as the one that is being supplied to the Http apply() method.
I guessed that my code must be doing a package import of a package with a package object with an implicit ActorSystem, or there
must be some other way this implicit is slipping in like a ninja in the dead of night. I've poked around quite a bit,
but couldn't figure it out ;^(
Any suggestions much appreciated !
Not sure I fully understood what the problem is but in your every actor you have context: ActorContext. You can obtain ActorSystem from context.system. Thus you don't need to explicitly pass ActorSystem around.
Here is how I used #expert's answer (above) to debug where my implicit was coming from. The key thing is to dump out the system variable from the Actor that is getting the implicit.. then look at the name to figure out where the implicit came from. In my case the implicit was coming from my own code (how dumb!). Anyway.. thanks to the answer above my problem is solved.
val http: HttpExt = Http()
val sys = http.system
System.out.println("sys:" + sys);
http. bindAndHandle(
service.route, "localhost", injector.getInstance(classOf[Conf]).getInt(PROVISIONER_PORT )
)

Elastic4s, mockito and verify with type erasure and implicits

In previous versions of Elastic4s you could do something like
val argument1: ArgumentCapture[DeleteIndexDefinition] = ???
verify(client).execute(argument1.capture())
assert(argument1 == ???)
val argument2: ArgumentCapture[IndexDefinition] = ???
verify(client, times(2)).execute(argument2.capture())
assert(argument2 == ???)
after several executions in your test (i.e. one DeleteIndexDefinition, followed of two IndexDefinition). And each verify would be matched against its type.
However, Elastic4s now takes an implicit parameter in its client.execute method. The parameter is of type Executable[T,R], which means you now need something like
val argument1: ArgumentCapture[DeleteIndexDefinition] = ???
verify(client).execute(argument1.capture())(any[Executable[DeleteIndexDefinition,R]])
assert(argument1 == ???)
val argument2: ArgumentCapture[IndexDefinition] = ???
verify(client, times(2)).execute(argument2.capture())(any[Executable[IndexDefinition,R]])
assert(argument2 == ???)
After doing that, I was getting an error. Mockito is considering both three client.execute in the first verify. Yes, even if the first parameter is of a different type.
That's because the implicit(the second parameter) has, after type erasure, the same type Executable.
So the asertions were failing. How to test in this setup?
The approach now taken in elastic4s to encapsulate the logic for executing each request type is one using typeclasses. This is why the implicit now exists. It help modularize each request type, and avoids the God class anti-pattern that was starting to creep into the ElasticClient class.
Two things I can think of that might help you:
What you already posted up, using Mockito and passing in the implicit as another matcher. This is how you can mock a method using implicits in general.
Not use mockito, but spool up a local embedded node, and try it against real data. This is my preferred approach when I write elasticsearch code. The advantages are that you're testing real queries against the real server, so not only checking that they are invoked, but that they actually work. (Some people might consider this an integration test, but whatever I don't agree, it all runs inside a single self contained test with no outside deps).
The latest release of elastic4s even include a testkit that makes it really easy to get the embedded node. You can look at almost any of the unit tests to give you an idea how to use it.
My solution was to create one verify with a generic type. It took me a while to realise that even if there is no common type, you always have AnyRef.
So, something like this works
val objs: ArgumentCaptor[AnyRef] = ArgumentCaptor.forClass(classOf[AnyRef])
verify(client, times(3)).execute(objs.capture())(any())
val values = objs.getAllValues
assert(values.get(0).isInstanceOf[DeleteIndexDefinition])
assert(values.get(1).isInstanceOf[IndexDefinition])
assert(values.get(2).isInstanceOf[IndexDefinition])
I've created both the question and the answer. But I'll consider other answers.

How to interpret a val in Scala that is of type Option[T]

I am trying to analyze Scala code written by someone else, and in doing so, I would like to be able to write Unit Tests (that were not written before the code was written, unfortunately).
Being a relative Newbie to Scala, especially in the Futures concept area, I am trying to understand the following line of code.
val niceAnalysis:Option[(niceReport) => Future[niceReport]] = None
Update:
The above line of code should be:
val niceAnalysis:Option[(NiceReport) => Future[NiceReport]] = None
- Where NiceReport is a case class
-----------Update ends here----------------
Since I am trying to mock up an Actor, I created this new Actor where I introduce my niceAnalysis val as a field.
The first problem I see with this "niceAnalysis" thing is that it looks like an anonymous function.
How do I "initialize" this val, or to give it an initial value.
My goal is to create a test in my test class, where I am going to pass in this initialized val value into my test actor's receive method.
My naive approach to accomplish this looked like:
val myActorUnderTestRef = TestActorRef(new MyActorUnderTest("None))
Neither does IntelliJ like it. My SBT compile and test fails.
So, I need to understand the "niceAnalyis" declaration first and then understand how to give it an initial value. Please advise.
You are correct that this is a value that might contain a function from type niceReport to Future[niceReport]. You can pass an anonymous function or just a function pointer. The easiest to understand might be the pointer, so I will provide that first, but the easiest in longer terms would be the anonymous function most likely, which I will show second:
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
def strToFuture(x: String) = Future{ x } //merely wrap the string in a future
val foo = Option(strToFuture)
Conversely, the one liner is as follows:
val foo = Option((x:String)=>Future{x})

Implicit conversions causing infinite recursion, but that shouldn't typecheck

I'm trying to write a Specs2 test for a class that takes a Squants Time as a parameter. The trick is that both tools define an implicit that adds a method called "seconds" to convert a number into their own representation (a squants.time.Seconds in one case and a org.specs2.time.Duration in the other), and unfortunately the wrong one seems to take precedence.
val a = new MyClass(10 seconds) // doesn't build because MyClass wants a Time instead of a Duration
To be clear, I could get around this by not relying on implicits to construct the Squants Time, that's not the question.
I rather like implicits so I decided to add an implicit to convert Durations into Times:
implicit def specsTimeToSquantsTime(t: org.specs2.time.Duration): squants.time.Time = squants.time.Seconds(t.toSeconds)
That got it to typecheck, but when I ran the test I got a stack overflow and the stack trace didn't make a great deal of sense, it said that my implicit conversion was calling itself (which wouldn't typecheck, and even if it would it still isn't possible given the above code!):
[error] package.TestConversions$.specsTimeToSquantsTime(TestConversions.scala:9)
[error] package.TestConversions$.specsTimeToSquantsTime(TestConversions.scala:9)
[error] package.TestConversions$.specsTimeToSquantsTime(TestConversions.scala:9)
...
So I have three questions: What's going on here? Is there a better way to do this? Could I manually hide the Int=>Duration implicit?
Method toSeconds is defined inside Time class:
final class Time private (val value: Double) extends Quantity[Time] {
...
def toSeconds = to(Seconds)
...
}
https://github.com/garyKeorkunian/squants/blob/master/src/main/scala/squants/time/Time.scala
So when compiler sees this method invoked on Duration - it's searching for appropriate implicit and it's specsTimeToSquantsTime, which contains Duration.toSeconds in its turn, which needs an implicit convertion from Duration to Time and so on and so forth. So you're getting infinite recursive call in runtime which is fully correct from compiler's side as theoretically you can stop this recursion and there is no general way (see halting problem) to detect that.
There is NoTimeConversions trait you can mix in Specification to avoid implicit conversions:
This trait can be used to deactivate the time conversions (to avoid
conflicts with Akka's conversions for example