-
Notifications
You must be signed in to change notification settings - Fork 787
/
JavaNetClientBuilder.scala
225 lines (206 loc) · 7.91 KB
/
JavaNetClientBuilder.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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
/*
* Copyright 2014 http4s.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.http4s
package client
import cats.effect.Async
import cats.effect.Resource
import cats.effect.Sync
import cats.syntax.all._
import fs2.Stream
import fs2.io.readInputStream
import fs2.io.writeOutputStream
import org.http4s.internal.BackendBuilder
import org.http4s.internal.CollectionCompat.CollectionConverters._
import org.typelevel.ci.CIString
import java.io.IOException
import java.net.HttpURLConnection
import java.net.Proxy
import java.net.URL
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.HttpsURLConnection
import javax.net.ssl.SSLSocketFactory
import scala.concurrent.duration.Duration
import scala.concurrent.duration.FiniteDuration
/** Builder for a [[Client]] backed by on `java.net.HttpUrlConnection`.
*
* The java.net client adds no dependencies beyond `http4s-client`.
* This client is generally not production grade, but convenient for
* exploration in a REPL.
*
* All I/O operations in this client are blocking.
*
* @define WHYNOSHUTDOWN Creation of the client allocates no
* resources, and any resources allocated while using this client
* are reclaimed by the JVM at its own leisure.
*/
sealed abstract class JavaNetClientBuilder[F[_]] private (
val connectTimeout: Duration,
val readTimeout: Duration,
val proxy: Option[Proxy],
val hostnameVerifier: Option[HostnameVerifier],
val sslSocketFactory: Option[SSLSocketFactory],
)(implicit protected val F: Async[F])
extends BackendBuilder[F, Client[F]] {
private def copy(
connectTimeout: Duration = connectTimeout,
readTimeout: Duration = readTimeout,
proxy: Option[Proxy] = proxy,
hostnameVerifier: Option[HostnameVerifier] = hostnameVerifier,
sslSocketFactory: Option[SSLSocketFactory] = sslSocketFactory,
): JavaNetClientBuilder[F] =
new JavaNetClientBuilder[F](
connectTimeout = connectTimeout,
readTimeout = readTimeout,
proxy = proxy,
hostnameVerifier = hostnameVerifier,
sslSocketFactory = sslSocketFactory,
) {}
def withConnectTimeout(connectTimeout: Duration): JavaNetClientBuilder[F] =
copy(connectTimeout = connectTimeout)
def withReadTimeout(readTimeout: Duration): JavaNetClientBuilder[F] =
copy(readTimeout = readTimeout)
def withProxyOption(proxy: Option[Proxy]): JavaNetClientBuilder[F] =
copy(proxy = proxy)
def withProxy(proxy: Proxy): JavaNetClientBuilder[F] =
withProxyOption(Some(proxy))
def withoutProxy: JavaNetClientBuilder[F] =
withProxyOption(None)
def withHostnameVerifierOption(
hostnameVerifier: Option[HostnameVerifier]
): JavaNetClientBuilder[F] =
copy(hostnameVerifier = hostnameVerifier)
def withHostnameVerifier(hostnameVerifier: HostnameVerifier): JavaNetClientBuilder[F] =
withHostnameVerifierOption(Some(hostnameVerifier))
def withoutHostnameVerifier: JavaNetClientBuilder[F] =
withHostnameVerifierOption(None)
def withSslSocketFactoryOption(
sslSocketFactory: Option[SSLSocketFactory]
): JavaNetClientBuilder[F] =
copy(sslSocketFactory = sslSocketFactory)
def withSslSocketFactory(sslSocketFactory: SSLSocketFactory): JavaNetClientBuilder[F] =
withSslSocketFactoryOption(Some(sslSocketFactory))
def withoutSslSocketFactory: JavaNetClientBuilder[F] =
withSslSocketFactoryOption(None)
/** Creates a [[Client]].
*
* The shutdown of this client is a no-op. $WHYNOSHUTDOWN
*/
def create: Client[F] =
Client { (req: Request[F]) =>
def respond(conn: HttpURLConnection): F[Response[F]] =
for {
_ <- configureSsl(conn)
_ <- F.delay(conn.setConnectTimeout(timeoutMillis(connectTimeout)))
_ <- F.delay(conn.setReadTimeout(timeoutMillis(readTimeout)))
_ <- F.delay(conn.setRequestMethod(req.method.renderString))
_ <- F.delay(req.headers.foreach { case Header.Raw(name, value) =>
conn.setRequestProperty(name.toString, value)
})
_ <- F.delay(conn.setInstanceFollowRedirects(false))
_ <- F.delay(conn.setDoInput(true))
// TODO: fix the blocking here
resp <- fetchResponse(req, conn)
} yield resp
for {
url <- Resource.eval(F.delay(new URL(req.uri.toString)))
conn <- Resource.make(openConnection(url)) { conn =>
F.delay(conn.getInputStream().close()).recoverWith { case _: IOException =>
F.delay(Option(conn.getErrorStream()).foreach(_.close()))
}
}
resp <- Resource.eval(respond(conn))
} yield resp
}
def resource: Resource[F, Client[F]] =
Resource.eval(F.delay(create))
private def fetchResponse(req: Request[F], conn: HttpURLConnection) =
for {
_ <- writeBody(req, conn)
code <- F.blocking(conn.getResponseCode)
status <- F.fromEither(Status.fromInt(code))
headers <- F.blocking(
Headers(
conn.getHeaderFields.asScala
.filter(_._1 != null)
.flatMap { case (k, vs) => vs.asScala.map(Header.Raw(CIString(k), _)) }
.toList
)
)
} yield Response(status = status, headers = headers, body = readBody(conn))
private def timeoutMillis(d: Duration): Int =
d match {
case d: FiniteDuration if d > Duration.Zero => d.toMillis.max(0).min(Int.MaxValue).toInt
case _ => 0
}
private def openConnection(url: URL)(implicit F: Sync[F]) =
proxy match {
case Some(p) =>
F.delay(url.openConnection(p).asInstanceOf[HttpURLConnection])
case None =>
F.delay(url.openConnection().asInstanceOf[HttpURLConnection])
}
private def writeBody(req: Request[F], conn: HttpURLConnection): F[Unit] =
if (req.isChunked)
F.delay(conn.setDoOutput(true)) *>
F.delay(conn.setChunkedStreamingMode(4096)) *>
req.body
.through(writeOutputStream(F.delay(conn.getOutputStream), false))
.compile
.drain
else
req.contentLength match {
case Some(len) if len >= 0L =>
F.delay(conn.setDoOutput(true)) *>
F.delay(conn.setFixedLengthStreamingMode(len)) *>
req.body
.through(writeOutputStream(F.delay(conn.getOutputStream), false))
.compile
.drain
case _ =>
F.delay(conn.setDoOutput(false))
}
private def readBody(conn: HttpURLConnection): Stream[F, Byte] = {
def inputStream =
F.delay(Option(conn.getInputStream)).recoverWith {
case _: IOException if conn.getResponseCode > 0 =>
F.delay(Option(conn.getErrorStream))
}
Stream.eval(inputStream).flatMap {
case Some(in) => readInputStream(F.pure(in), 4096, false)
case None => Stream.empty
}
}
private def configureSsl(conn: HttpURLConnection) =
conn match {
case connSsl: HttpsURLConnection =>
for {
_ <- hostnameVerifier.fold(F.unit)(hv => F.delay(connSsl.setHostnameVerifier(hv)))
_ <- sslSocketFactory.fold(F.unit)(sslf => F.delay(connSsl.setSSLSocketFactory(sslf)))
} yield ()
case _ => F.unit
}
}
/** Builder for a [[Client]] backed by on `java.net.HttpUrlConnection`. */
object JavaNetClientBuilder {
def apply[F[_]: Async]: JavaNetClientBuilder[F] =
new JavaNetClientBuilder[F](
connectTimeout = defaults.ConnectTimeout,
readTimeout = defaults.RequestTimeout,
proxy = None,
hostnameVerifier = None,
sslSocketFactory = None,
) {}
}