-
Notifications
You must be signed in to change notification settings - Fork 820
/
HTTPTransformer.scala
148 lines (115 loc) · 5.31 KB
/
HTTPTransformer.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
// Copyright (C) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in project root for information.
package com.microsoft.azure.synapse.ml.io.http
import com.microsoft.azure.synapse.ml.codegen.Wrappable
import com.microsoft.azure.synapse.ml.core.contracts.{HasInputCol, HasOutputCol}
import com.microsoft.azure.synapse.ml.io.http.HandlingUtils.HandlerFunc
import com.microsoft.azure.synapse.ml.logging.{FeatureNames, SynapseMLLogging}
import com.microsoft.azure.synapse.ml.param.UDFParam
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.spark.injections.UDFUtils
import org.apache.spark.ml.param._
import org.apache.spark.ml.util.Identifiable
import org.apache.spark.ml.{ComplexParamsReadable, ComplexParamsWritable, Transformer}
import org.apache.spark.sql.catalyst.encoders.RowEncoder
import org.apache.spark.sql.expressions.UserDefinedFunction
import org.apache.spark.sql.types._
import org.apache.spark.sql.{DataFrame, Dataset, Row}
import scala.concurrent.ExecutionContext
import scala.concurrent.duration.Duration
trait HasHandler extends Params {
val handler: UDFParam = new UDFParam(
this, "handler", "Which strategy to use when handling requests")
/** @group getParam */
def getHandler: HandlerFunc = UDFUtils.unpackUdf($(handler))._1.asInstanceOf[HandlerFunc]
def setHandler(v: HandlerFunc): HasHandler.this.type = {
set(handler, UDFUtils.oldUdf(v, StringType))
}
def setHandler(v: UserDefinedFunction): HasHandler.this.type = set(handler, v)
setDefault(handler -> HandlingUtils.advancedUDF(100)) //scalastyle:ignore magic.number
def handlingFunc(client: CloseableHttpClient,
request: HTTPRequestData): HTTPResponseData =
getHandler(client, request)
}
trait ConcurrencyParams extends Wrappable {
val concurrency: Param[Int] = new IntParam(
this, "concurrency", "max number of concurrent calls")
/** @group getParam */
def getConcurrency: Int = $(concurrency)
/** @group setParam */
def setConcurrency(value: Int): this.type = set(concurrency, value)
val timeout: Param[Double] = new DoubleParam(
this, "timeout", "number of seconds to wait before closing the connection")
/** @group getParam */
def getTimeout: Double = $(timeout)
/** @group setParam */
def setTimeout(value: Double): this.type = set(timeout, value)
val concurrentTimeout: Param[Double] = new DoubleParam(
this, "concurrentTimeout", "max number seconds to wait on futures if concurrency >= 1")
/** @group getParam */
def getConcurrentTimeout: Double = $(concurrentTimeout)
/** @group setParam */
def setConcurrentTimeout(value: Double): this.type = set(concurrentTimeout, value)
def setConcurrentTimeout(value: Option[Double]): this.type = value match {
case Some(v) => setConcurrentTimeout(v)
case None => clear(concurrentTimeout)
}
setDefault(concurrency -> 1, timeout -> 60.0)
}
trait HasURL extends Params {
val url: Param[String] = new Param[String](this, "url", "Url of the service")
/** @group getParam */
def getUrl: String = $(url)
/** @group setParam */
def setUrl(value: String): this.type = set(url, value)
}
object HTTPTransformer extends ComplexParamsReadable[HTTPTransformer]
class HTTPTransformer(val uid: String)
extends Transformer with ConcurrencyParams with HasInputCol
with HasOutputCol with HasHandler
with ComplexParamsWritable with SynapseMLLogging {
logClass(FeatureNames.Core)
setDefault(handler -> HandlingUtils.advancedUDF(100, 500, 1000)) //scalastyle:ignore magic.number
def this() = this(Identifiable.randomUID("HTTPTransformer"))
val clientHolder = SharedVariable {
getConcurrency match {
case 1 => new SingleThreadedHTTPClient(getHandler, (getTimeout * 1000).toInt)
case n if n > 1 =>
val dur = get(concurrentTimeout)
.map(ct => Duration.fromNanos((ct * math.pow(10, 9)).toLong)) //scalastyle:ignore magic.number
.getOrElse(Duration.Inf)
val ec = ExecutionContext.global
new AsyncHTTPClient(getHandler, n, dur, (getTimeout * 1000).toInt)(ec)
}
}
/** @param dataset - The input dataset, to be transformed
* @return The DataFrame that results from column selection
*/
override def transform(dataset: Dataset[_]): DataFrame = {
logTransform[DataFrame]({
val df = dataset.toDF()
val enc = RowEncoder(transformSchema(df.schema))
val colIndex = df.schema.fieldNames.indexOf(getInputCol)
val fromRow = HTTPRequestData.makeFromRowConverter
val toRow = HTTPResponseData.makeToRowConverter
df.mapPartitions { it =>
if (!it.hasNext) {
Iterator()
} else {
val c = clientHolder.get
val responsesWithContext = c.sendRequestsWithContext(it.map { row =>
c.RequestWithContext(Option(row.getStruct(colIndex)).map(fromRow), Some(row))
})
responsesWithContext.map { rwc =>
Row.fromSeq(rwc.context.get.asInstanceOf[Row].toSeq :+ rwc.response.flatMap(Option.apply).map(toRow).orNull)
}
}
}(enc)
}, dataset.columns.length)
}
def copy(extra: ParamMap): HTTPTransformer = defaultCopy(extra)
def transformSchema(schema: StructType): StructType = {
assert(schema(getInputCol).dataType == HTTPSchema.Request)
schema.add(getOutputCol, HTTPSchema.Response, nullable = true)
}
}