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

Added implementation of row level headers , params in http method-3.1 #40

Merged
Merged
Show file tree
Hide file tree
Changes from all 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
447 changes: 339 additions & 108 deletions README.md

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -13,72 +13,100 @@ import scala.concurrent.duration.Duration
import scala.util.{Failure, Success, Try}

final case class Response(
`__ID__`:String,
`__BODY__`:Option[String] = None,
`__HEADER__`:Map[String,Seq[String]] = Map(),
`__STATUS_CODE__`:Option[Int] = None,
`__STATUS_MSG__`:Option[String] = None,
`__ERROR__`:Option[String] = None,
`__ELAPSED_TIME__`:Long,
`__URL__`:String,
`__DATA__`: String)
`__ID__`: String,
`__BODY__`: Option[String] = None,
`__HEADER__`: Map[String, Seq[String]] = Map(),
`__STATUS_CODE__`: Option[Int] = None,
`__STATUS_MSG__`: Option[String] = None,
`__ERROR__`: Option[String] = None,
`__ELAPSED_TIME__`: Long,
`__URL__`: String,
`__DATA__`: String)

final case class ResponseBatch(
`__ID__`:Seq[String],
`__BODY__`:Option[String] = None,
`__HEADER__`:Map[String,Seq[String]] = Map(),
`__STATUS_CODE__`:Option[Int] = None,
`__STATUS_MSG__`:Option[String] = None,
`__ERROR__`:Option[String] = None,
`__ELAPSED_TIME__`:Long,
`__URL__`:String,
`__DATA__`:String)
`__ID__`: Seq[String],
`__BODY__`: Option[String] = None,
`__HEADER__`: Map[String, Seq[String]] = Map(),
`__STATUS_CODE__`: Option[Int] = None,
`__STATUS_MSG__`: Option[String] = None,
`__ERROR__`: Option[String] = None,
`__ELAPSED_TIME__`: Long,
`__URL__`: String,
`__DATA__`: String)


object Alias {
val DataCol = "__DATA__"
val IdCol = "__ID__"
val UrlCol = "__URL__"
val ParamsCol = "__PARAMS__"
val HiddenParamsCol = "__HIDDEN_PARAMS__"
val HeadersCol = "__HEADERS__"
}


private[almaren] case class HTTP(
headers: Map[String, String],
params: Map[String, String],
hiddenParams: Map[String, String],
method: String,
requestHandler: (Row, Session, String, Map[String, String], Map[String, String], String, Int, Int) => requests.Response,
session: () => requests.Session,
connectTimeout: Int,
readTimeout: Int,
threadPoolSize: Int,
batchSize: Int) extends Main {
headers: Map[String, String],
params: Map[String, String],
hiddenParams: Map[String, String],
method: String,
requestHandler: (Row, Session, String, Map[String, String], Map[String, String], String, Int, Int) => requests.Response,
session: () => requests.Session,
connectTimeout: Int,
readTimeout: Int,
threadPoolSize: Int,
batchSize: Int) extends Main {

private def columnExists(df: DataFrame, colName: String): Option[String] =
Some(colName).filter(df.columns.contains)

private def getRowParam(row: Row, colNameExists: Option[String]): Map[String, String] =
colNameExists.map(name => row.getAs[Map[String, String]](name)).getOrElse(Map())

override def core(df: DataFrame): DataFrame = {
logger.info(s"headers:{$headers},params:{$params}, method:{$method}, connectTimeout:{$connectTimeout}, readTimeout{$readTimeout}, threadPoolSize:{$threadPoolSize}, batchSize:{$batchSize}")

import df.sparkSession.implicits._

val headersColExists = columnExists(df,Alias.HeadersCol)
val paramsColExists = columnExists(df,Alias.ParamsCol)
val hiddenParamsColExists = columnExists(df,Alias.HiddenParamsCol)

val result = df.mapPartitions(partition => {

implicit val ec:ExecutionContext = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(threadPoolSize))
val data:Iterator[Future[Seq[Response]]] = partition.grouped(batchSize).map(rows => Future {
implicit val ec: ExecutionContext = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(threadPoolSize))
val data: Iterator[Future[Seq[Response]]] = partition.grouped(batchSize).map(rows => Future {
val s = session()
rows.map(row => request(row,s))
rows.map(row => request(row, s, headersColExists, paramsColExists, hiddenParamsColExists))
})
val requests:Future[Iterator[Seq[Response]]] = Future.sequence(data)
val requests: Future[Iterator[Seq[Response]]] = Future.sequence(data)
Await.result(requests, Duration.Inf).flatten
})
result.toDF
}

private def request(row:Row, session:Session): Response = {
private def request(row: Row, session: Session, headersColExists: Option[String], paramsColExists: Option[String], hiddenParamsColExists: Option[String]): Response = {
val url = row.getAs[Any](Alias.UrlCol).toString
val startTime = System.currentTimeMillis()
val response = Try(requestHandler(row,session,url,headers,params ++ hiddenParams,method,connectTimeout,readTimeout))

val headersRow = getRowParam(row, headersColExists)
val paramsRow = getRowParam(row, paramsColExists)
val hiddenParamsRow = getRowParam(row, hiddenParamsColExists)

val allHeaders = headers ++ headersRow
val allParams = params ++ paramsRow
val allHiddenParams = hiddenParams ++ hiddenParamsRow

logger.info(s"headers:{$allHeaders},params:{$allParams}")
val response = Try(requestHandler(row, session, url, allHeaders, allParams ++ allHiddenParams, method, connectTimeout, readTimeout))
val elapsedTime = System.currentTimeMillis() - startTime
val id = row.getAs[Any](Alias.IdCol).toString
val data = row.getAs[Any](Alias.DataCol).toString

val data = method.toUpperCase match {
case "PUT" | "POST" | "DELETE" => row.getAs[Any](Alias.DataCol).toString
case _ => ""
}

def getResponse(r: requests.Response) = Response(
id,
Some(r.text()),
Expand All @@ -105,18 +133,18 @@ private[almaren] case class HTTP(
}

private[almaren] case class HTTPBatch(
url: String,
headers: Map[String, String],
params: Map[String, String],
hiddenParams: Map[String, String],
method: String,
requestHandler: (String, Session, String, Map[String, String], Map[String, String], String, Int, Int) => requests.Response,
session: () => requests.Session,
connectTimeout: Int,
readTimeout: Int,
batchSize: Int,
batchDelimiter: (Seq[Row]) => String
) extends Main {
url: String,
headers: Map[String, String],
params: Map[String, String],
hiddenParams: Map[String, String],
method: String,
requestHandler: (String, Session, String, Map[String, String], Map[String, String], String, Int, Int) => requests.Response,
session: () => requests.Session,
connectTimeout: Int,
readTimeout: Int,
batchSize: Int,
batchDelimiter: (Seq[Row]) => String
) extends Main {

override def core(df: DataFrame): DataFrame = {
logger.info(s"url:{$url}, headers:{$headers},params:{$params}, method:{$method}, connectTimeout:{$connectTimeout}, readTimeout{$readTimeout}, batchSize:{$batchSize}")
Expand All @@ -143,7 +171,9 @@ private[almaren] case class HTTPBatch(
`__DATA__` = data
)

Try{request(data,s)} match {
Try {
request(data, s)
} match {
case Success(r) => getResponse(r)
case Failure(re: RequestFailedException) => getResponse(re.response)
case Failure(f) => {
Expand All @@ -155,33 +185,33 @@ private[almaren] case class HTTPBatch(
`__URL__` = url,
`__DATA__` = data
)

}
}
})
})
result.toDF
}

private def request(data:String, session:Session): requests.Response =
requestHandler(data,session,url,headers,params ++ hiddenParams,method,connectTimeout,readTimeout)
private def request(data: String, session: Session): requests.Response =
requestHandler(data, session, url, headers, params ++ hiddenParams, method, connectTimeout, readTimeout)


}

private[almaren] trait HTTPConnector extends Core {

def http(
headers: Map[String, String] = Map(),
params: Map[String, String] = Map(),
hiddenParams: Map[String, String] = Map(),
method: String,
requestHandler: (Row, Session, String, Map[String, String], Map[String, String], String, Int, Int) => requests.Response = HTTPConn.defaultHandler,
session: () => requests.Session = HTTPConn.defaultSession,
connectTimeout: Int = 60000,
readTimeout: Int = 1000,
threadPoolSize: Int = 1,
batchSize: Int = 5000): Option[Tree] =
headers: Map[String, String] = Map(),
params: Map[String, String] = Map(),
hiddenParams: Map[String, String] = Map(),
method: String,
requestHandler: (Row, Session, String, Map[String, String], Map[String, String], String, Int, Int) => requests.Response = HTTPConn.defaultHandler,
session: () => requests.Session = HTTPConn.defaultSession,
connectTimeout: Int = 60000,
readTimeout: Int = 1000,
threadPoolSize: Int = 1,
batchSize: Int = 5000): Option[Tree] =
HTTP(
headers,
params,
Expand All @@ -196,18 +226,18 @@ private[almaren] trait HTTPConnector extends Core {
)

def httpBatch(
url: String,
headers: Map[String, String] = Map(),
params: Map[String, String] = Map(),
hiddenParams: Map[String, String] = Map(),
method: String,
requestHandler: (String, Session, String, Map[String, String], Map[String, String], String, Int, Int) => requests.Response = HTTPConn.defaultHandlerBatch,
session: () => requests.Session = HTTPConn.defaultSession,
connectTimeout: Int = 60000,
readTimeout: Int = 1000,
batchSize: Int = 5000,
batchDelimiter: (Seq[Row]) => String = HTTPConn.defaultBatchDelimiter
): Option[Tree] =
url: String,
headers: Map[String, String] = Map(),
params: Map[String, String] = Map(),
hiddenParams: Map[String, String] = Map(),
method: String,
requestHandler: (String, Session, String, Map[String, String], Map[String, String], String, Int, Int) => requests.Response = HTTPConn.defaultHandlerBatch,
session: () => requests.Session = HTTPConn.defaultSession,
connectTimeout: Int = 60000,
readTimeout: Int = 1000,
batchSize: Int = 5000,
batchDelimiter: (Seq[Row]) => String = HTTPConn.defaultBatchDelimiter
): Option[Tree] =
HTTPBatch(
url,
headers,
Expand All @@ -224,7 +254,7 @@ private[almaren] trait HTTPConnector extends Core {
}

object HTTPConn {
val defaultHandler = (row:Row, session:Session, url:String, headers:Map[String, String], params:Map[String, String], method:String, connectTimeout:Int, readTimeout:Int) => {
val defaultHandler = (row: Row, session: Session, url: String, headers: Map[String, String], params: Map[String, String], method: String, connectTimeout: Int, readTimeout: Int) => {
method.toUpperCase match {
case "GET" => session.get(url, headers = headers, params = params, readTimeout = readTimeout, connectTimeout = connectTimeout)
case "DELETE" => session.delete(url, headers = headers, params = params, data = row.getAs[String](Alias.DataCol), readTimeout = readTimeout, connectTimeout = connectTimeout)
Expand All @@ -236,7 +266,7 @@ object HTTPConn {
}
}

val defaultHandlerBatch = (data:String, session:Session, url:String, headers:Map[String, String], params:Map[String, String], method:String, connectTimeout:Int, readTimeout:Int) => {
val defaultHandlerBatch = (data: String, session: Session, url: String, headers: Map[String, String], params: Map[String, String], method: String, connectTimeout: Int, readTimeout: Int) => {
method.toUpperCase match {
case "GET" => session.get(url, headers = headers, params = params, readTimeout = readTimeout, connectTimeout = connectTimeout)
case "DELETE" => session.delete(url, headers = headers, params = params, data = data, readTimeout = readTimeout, connectTimeout = connectTimeout)
Expand All @@ -248,9 +278,9 @@ object HTTPConn {
}
}

val defaultBatchDelimiter = (rows:Seq[Row]) => rows.map(row => row.getAs[String](Alias.DataCol)).mkString("\n")
val defaultBatchDelimiter = (rows: Seq[Row]) => rows.map(row => row.getAs[String](Alias.DataCol)).mkString("\n")

val defaultSession = () => requests.Session()

implicit class HTTPImplicit(val container: Option[Tree]) extends HTTPConnector
}
}
Binary file not shown.
Binary file not shown.
Empty file.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Empty file.
Binary file not shown.
Loading
Loading