Spray routing works for single slash but nothing else - scala

So i have asked about this before and have changed a lot of code around.
Spray Routing Doesn't match anything
Now I am executing my functions that return HTTPresponses insided detach() blocks so that i dont block. These then are completed and return to the client, but I still can't seem to get my routing to work.
In my tests, a request to a single slash works fine, but anything else, such as this create user path shown below fails. I can't seem to figure out why, and spray routing uses so many constructs I'm having a hard time figuring out how the system works well enough to find out whats happening.
I tried inserting logRequest blocks around certain paths thinking that might show me whats happening, but none of them seem to get hit. Any help would be greatly appreciated.
val route: Route = {
host("fakebook.com", "www.fakebook.com") {
pathSingleSlash {
complete("pong")
} ~
pathPrefix("users") { req =>
path("newuser") {
put {
detach() {
complete(genericPut(CreateUser(req.request)))
}
}
} ~
... rest of routing
And here is what my scalatests look like, the simple Put passes, but the put with newuser doesn't
val createUserSuccessRequest = Put(Uri("http://www.fakebook.com/users/newuser") withQuery(F_User.lastNameString -> "Doe", F_User.firstNameString -> "John", F_User.bioString -> "i like foobar",
F_User.ageString -> "42", F_User.dobString -> dateFormatter.format(new Date(1970 - 1900, 5, 7))))
"The FakeBook route" when {
"When sending a single slash request" should {
"respond with a simple pong" in {
Get() ~> logRequestResponse("plain get final request and response")(sealRoute(route)) ~> check {
assert(responseAs[String] == "pong")
}
}
}
"Running route to create a user with PUT" should {
"forward a message to the backbone to create a new user" in {
createUserSuccessRequest ~> logRequest("create user final request and response"){sealRoute(route)} ~> check {
expectMsg(CreateUser(createUserSuccessRequest))
}
}
}
}

For anyone else trying to solve this issue:
a lot of these directives actually DONT extract anything, so having the lambda inputs i have like req => and req2 => will not work.
It turns out, spray routing is designed so that you never have to touch the RequestContext as I have done with my functions (which is why I try to access it). They extract only the useful data. Rather than do things as I should and change my function signatures, i am going to (for now) do a hotfix that has worked.
if you absolutely must have the requestcontext, so long as you don't break it somehow, you can extract it by making your own extraction directive like so
val extractRequestContext = extract(x => x) and wrap your code in that
I did this
path("somepath") {
detach() {
extractRequestContext { request => complete(someFunc(request)) }
}
}
In the future I should learn to use the DSL more correctly and extract what I need from the request context using directives and pass THOSE to the functions

Related

How to redirect internally in Ktor?

I'm wondering if there's a way to do an internal redirect, re-route, or response forwarding inside Ktor.
call.respondRedirect("relative/url")
sends a HTTP 302 or 301 depending on the permantent: Boolean flag. I'm looking for something that would do the same without using HTTP, just internally in Ktor. Here's some pseudo-routing of what I want to achieve:
get("/foo") {
if (call.parameters["something"] != null) {
call.respondText("Yay, something!")
} else {
call.respondRedirect("/bar") // except without relying on client to handle HTTP redirects.
}
}
get("/bar") {
call.respondText("No thing :(")
}
The goal is that the client shouldn't make 2 requests, and shouldn't be aware of the redirection happening.
NB: I'm aware I can extract a function for /bar's body and invoke it, instead of responsdRedirect. However, I want to make Ktor handle it so that it goes through all the necessary lifecycle and pipeline with all the interceptors. This is to make sure it is handled as if it was an external request, except the network roundtrip.
I'm looking for something like Express.js' req.app.handle(req, res) as shown in the first half of this answer: https://stackoverflow.com/a/48790319/253468. A potential solution I couldn't understand yet is something like TestApplicationEngine.handleRequest (in io.ktor:ktor-server-test-host) is doing with pipeline.execute. I guess I could invoke call.application.execute(), the question is how to construct the ApplicationCall object then. Note this is for production use, so no TestApplicationCall.
You can do similar thing in Ktor by using call.application.execute function with cloned call object. For convenience let's define extension function for doing internal redirects:
suspend fun ApplicationCall.redirectInternally(path: String) {
val cp = object: RequestConnectionPoint by this.request.local {
override val uri: String = path
}
val req = object: ApplicationRequest by this.request {
override val local: RequestConnectionPoint = cp
}
val call = object: ApplicationCall by this {
override val request: ApplicationRequest = req
}
this.application.execute(call)
}
Here it creates a copy of an ApplicationCall object with the replaced path for a request. I use delegates to avoid boilerplate code. You can use redirectInternally function like this:
get("/foo") {
call.redirectInternally("/bar")
}

Scala akka-http evaluate headers and continue routing if successful?

I'm new to scala, and I'm trying to figure out how to add to the existing routes we have so that if a certain path is hit, we evaluate the headers by checking for the existence of some values and whether or not they equal some accepted values. If it succeeds, we get some String out of the headers and pass it on, otherwise we should not continue routing and return some failure.
/abc -> don't check headers
/abc/def -> check headers, return
pathPrefix("abc") {
path("def") { // want to ADD something here to check headers and send it into someMethod
get {
complete(HttpEntity(something.someMethod(someValue)))
}
} ~ path("gdi") {
get { ... etc}
}
}
Any ideas or dummy examples would be really helpful. I see some directives here to get stuff from the request, and the header (https://doc.akka.io/docs/akka-http/10.0.11/scala/http/routing-dsl/directives/header-directives/headerValue.html), but I don't understand how to chain directives in this way.
If I'm misunderstanding something, please help clarify! Thanks
Use headerValueByName, which looks for a specific header and rejects the request if that header isn't found:
get {
headerValueByName("MyHeader") { headerVal =>
complete(HttpEntity(something.someMethod(headerVal)))
}
}
To validate the header value if it exists:
get {
headerValueByName("MyHeader") { headerVal =>
if (isValid(headerVal)) // isValid is a custom method that you provide
complete(HttpEntity(something.someMethod(headerVal)))
else
complete((BadRequest, "The MyHeader value is invalid."))
}
}
isValid in the above example could look something like:
def isValid(headerValue: String): Boolean = {
val acceptedValues = Set("burrito", "quesadilla", "taco")
acceptedValues.contains(headerValue.toLowerCase)
}

Akka HTTP set response header based on result of Future

I'm designing a REST service using Akka-HTTP 2.0-M2 and have come across a situation where I'd like to supply additional headers which are dependent upon the reply of the queried Actor.
Currently, I have the following...
val route = {
path("oncologist") {
get {
parameters('active.as[Boolean].?, 'skip.as[Int].?, 'limit.as[Int].?).as(GetAllOncologists) {
req =>
complete {
(oncologistActor ? req).mapTo[OncologistList]
}
}
}
}
While this is returning without issue. I'd like to move some of the properties of OncologistList into the response header rather than returning them in the body. Namely, I'm returning total record counts and offset and I would like to generate a previous and next URL header value for use by the client. I'm at a loss on how to proceed.
I think you can use the onComplete and respondWithHeaders directives to accomplish what you want. The onComplete directive works with the result of a Future which is exactly what ask (?) will return. Here is an example using a case class like so:
case class Foo(id:Int, name:String)
And a simple route showing onComplete like so:
get{
parameters('active.as[Boolean].?, 'skip.as[Int].?, 'limit.as[Int].?).as(GetAllOncologists) { req =>
val fut = (oncologistActor ? req).mapTo[Foo]
onComplete(fut){
case util.Success(f) =>
val headers = List(
RawHeader("X-MyObject-Id", f.id.toString),
RawHeader("X-MyObject-Name", f.name)
)
respondWithHeaders(headers){
complete(StatusCodes.OK)
}
case util.Failure(ex) =>
complete(StatusCodes.InternalServerError )
}
}
}
So if we get a successful result from the ask on oncologistActor we can then leverage the respondWithHeaders to add some custom headers to the response. Hopefully this is what you were looking for.

Spray testing basicauth from js html

I have code like:
https://gist.github.com/daaatz/7665224
but dont know how to test request.
Trying mydomain/secured?user=John&password=p4ssw0rd etc but nothing works.
Can some one tell me or show example in js+html how to check is it working fine ?
Thanks
I've never used BasicAuth in Spray, so i'm not sure if this would be the complete answer, but i hope this will help you.
At first. in spray there is a great spray-testkit written on top of akka testkit. You should definitely check out SecurityDirectives test on github, this will show you how to test basic authentication. A little example, to make this simpler:
As for your route example, i would better edit to the following one:
val myRoute =
(path("secured") & get) {
authenticate(BasicAuth(myUserPassAuthenticator _, realm = "secure site")) {
userName => complete(s"The user is '$userName'")
}
}
}
Adding get directive will specify that this route expects a Get request and sealRoute is obsolete cause RejectionHandler and ExceptionHandler are provided implicitly with runRoute. It is used only in tests, if you want wo check exceptions/rejections.
Now in your tests you should construct auth entities, similar to the test one:
val challenge = `WWW-Authenticate`(HttpChallenge("Basic", "Realm"))
val doAuth = BasicAuth(UserPassAuthenticator[BasicUserContext] { userPassOption ⇒
Future.successful(Some(BasicUserContext(userPassOption.get.user)))
}, "Realm")
And you test case:
"simple auth test" in {
Get("security") ~> Authorization(BasicHttpCredentials("Alice", "")) ~> {
authenticate(doAuth) { echoComplete }
} ~> check { responseAs[String] === "BasicUserContext(Alice)" }
}
In Get("security") specifies that your test will send a Get request on "/security", then add Authorization to the test request, some action and the check part to test the request.
I've never tried to test BasicAuth, so there could be some mistakes.
I would look into CURL for testing routes in web applications, but I've also used the chrome extension Postman with great results as well.

Simple use of dispatch

I'm about to set up a stupid play/scala app whose only job will be to make some http call once it receives calls itself
GET /abracadabra controllers.Application.abracadabra(stuff: String)
and then
def abracadabra(stuff: String) = Action {
Logger.info("called for stuff: "+stuff);
// call this other URL with 'stuff' as get parameter
// log http return status code and return Ok/200 anyways
}
Now for the second (commented) part I thought about using Dispatch.
I've read the docs but I can't just figure out how to use Promises and all that.
If anybody could point me to some sample code or something, it will be much appreciated
Since Play! has a built in Async library, you should probably go ahead and use that unless there's a feature in Dispatch that you specifically need.
Here's a short example:
def abracadabra(stuff: String) = Action {
Logger.info("called for stuff: "+stuff);
Async {
WS.url("http://stackoverflow.com/").get().map { response =>
Ok("I got it: " + response)
}
}
}
The documentation is here: https://github.com/playframework/Play20/wiki/ScalaWS