Skip to content

Commit

Permalink
Split Client into api-specific Clients and agnostic Transport (closes #…
Browse files Browse the repository at this point in the history
  • Loading branch information
asoltysik committed Jul 12, 2018
1 parent c225fa1 commit 21c4d02
Show file tree
Hide file tree
Showing 16 changed files with 494 additions and 408 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package com.snowplowanalytics.weather.providers.openweather
package com.snowplowanalytics.weather

import io.circe.generic.JsonCodec

Expand Down
96 changes: 96 additions & 0 deletions src/main/scala/com.snowplowanalytics/weather/HttpTransport.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/*
* Copyright (c) 2015-2018 Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package com.snowplowanalytics.weather

// cats
import cats.effect.Sync
import cats.syntax.either._

// circe
import io.circe.{Decoder, Json}
import io.circe.parser.parse

// hammock
import hammock.{Hammock, HttpResponse, Method, Status, Uri}
import hammock.jvm.Interpreter

// This library
import Errors._

class HttpTransport[F[_]: Sync](apiHost: String, apiKey: String, ssl: Boolean = true) extends Transport[F] {
import HttpTransport._

private implicit val interpreter = Interpreter[F]

def receive[W <: WeatherResponse: Decoder](request: WeatherRequest): F[Either[WeatherError, W]] = {
val scheme = if (ssl) "https" else "http"
val authority = Uri.Authority(None, Uri.Host.Other(apiHost), None)
val baseUri = Uri(Some(scheme), Some(authority))

val uri = request.constructQuery(baseUri, apiKey)

Hammock
.request(Method.GET, uri, Map())
.map(uri => processResponse(uri))
.exec[F]
}
}

object HttpTransport {

/**
* Decode response case class from HttpResponse body
*
* @param response full HTTP response
* @return either error or decoded case class
*/
private def processResponse[A: Decoder](response: HttpResponse): Either[WeatherError, A] =
getResponseContent(response)
.flatMap(parseJson)
.flatMap(json => extractWeather(json))

/**
* Convert the response to string
*
* @param response full HTTP response
* @return either entity content of HTTP response or WeatherError (AuthorizationError / HTTPError)
*/
private def getResponseContent(response: HttpResponse): Either[WeatherError, String] =
response.status match {
case Status.OK => Right(response.entity.content.toString)
case Status.Unauthorized => Left(AuthorizationError)
case _ => Left(HTTPError(s"Request failed with status ${response.status.code}"))
}

private def parseJson(content: String): Either[ParseError, Json] =
parse(content)
.leftMap(e =>
ParseError(
s"OpenWeatherMap Error when trying to parse following json: \n$content\n\nMessage from the parser:\n ${e.message}"))

/**
* Transform JSON into parseable format and try to extract specified response
*
* @param response response json
* @tparam W specific response case class from
* `com.snowplowanalytics.weather.providers.openweather.Responses`
* @return either weather error or response case class
*/
private[weather] def extractWeather[W: Decoder](response: Json): Either[WeatherError, W] =
response.as[W].leftFlatMap { _ =>
response.as[ErrorResponse] match {
case Right(error) => Left(error)
case Left(_) => Left(ParseError(s"Could not extract ${Decoder[W].toString} from ${response.toString}"))
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* Copyright (c) 2015-2018 Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package com.snowplowanalytics.weather

// Scala
import scala.concurrent.ExecutionContext

// cats
import cats.effect.{Concurrent, Timer}
import cats.syntax.functor._

// circe
import io.circe.Decoder

// This library
import Errors.{TimeoutError, WeatherError}

import scala.concurrent.duration.FiniteDuration

class TimeoutHttpTransport[F[_]: Concurrent](apiHost: String,
apiKey: String,
requestTimeout: FiniteDuration,
ssl: Boolean = true)(implicit val executionContext: ExecutionContext)
extends HttpTransport[F](apiHost, apiKey, ssl) {

import TimeoutHttpTransport._

private val timer: Timer[F] = Timer.derive[F]

override def receive[W <: WeatherResponse: Decoder](request: WeatherRequest): F[Either[Errors.WeatherError, W]] =
timeout(super.receive(request), requestTimeout, timer)

}

object TimeoutHttpTransport {

/**
* Apply timeout to the `operation` parameter. To be replaced by Concurrent[F].timeout in cats-effect 1.0.0
*
* @param operation The operation we want to run with a timeout
* @param duration Duration to timeout after
* @return either Left(TimeoutError) or a result of the operation, wrapped in F
*/
private def timeout[F[_]: Concurrent, W](operation: F[Either[WeatherError, W]],
duration: FiniteDuration,
timer: Timer[F]): F[Either[WeatherError, W]] =
Concurrent[F]
.race(operation, timer.sleep(duration))
.map {
case Left(value) => value
case Right(_) => Left(TimeoutError(s"OpenWeatherMap request timed out after ${duration.toSeconds} seconds"))
}
}
33 changes: 33 additions & 0 deletions src/main/scala/com.snowplowanalytics/weather/Transport.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* Copyright (c) 2015-2018 Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package com.snowplowanalytics.weather

// circe
import io.circe.Decoder

// This library
import Errors.WeatherError

trait Transport[F[_]] {

/**
* Main client logic for Request => Response function,
* where Response is wrapped in tparam `F`
*
* @param request request built by client method
* @tparam W type of weather response to extract
* @return extracted either error or weather wrapped in `F`
*/
def receive[W <: WeatherResponse: Decoder](request: WeatherRequest): F[Either[WeatherError, W]]

}
7 changes: 7 additions & 0 deletions src/main/scala/com.snowplowanalytics/weather/package.scala
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,16 @@
*/
package com.snowplowanalytics

import hammock.Uri

package object weather {

type Timestamp = Int
type Day = Int // 0:00:00 timestamp of day

trait WeatherRequest {
def constructQuery(baseUri: Uri, apiKey: String): Uri
}
trait WeatherResponse

}
Loading

0 comments on commit 21c4d02

Please sign in to comment.