/
Client.scala
241 lines (215 loc) · 9.1 KB
/
Client.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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
package org.http4s
package client
import java.util.concurrent.atomic.AtomicBoolean
import org.http4s.Status.Successful
import org.http4s.headers.{Accept, MediaRangeAndQValue}
import org.http4s.internal.compatibility._
import scala.util.control.NoStackTrace
import java.io.IOException
import scalaz.concurrent.Task
import scalaz.stream.{Process, Process1}
import scalaz.stream.Process._
import scodec.bits.ByteVector
/**
* Contains a [[Response]] that needs to be disposed of to free the underlying
* HTTP connection.
* @param response
* @param dispose
*/
final case class DisposableResponse(response: Response, dispose: Task[Unit]) {
/**
* Returns a task to handle the response, safely disposing of the underlying
* HTTP connection when the task finishes.
*/
def apply[A](f: Response => Task[A]): Task[A] = {
val task = try f(response) catch { case e: Throwable => Task.fail(e) }
task.onFinish { case _ => dispose }
}
}
/**
* A [[Client]] submits [[Request]]s to a server and processes the [[Response]].
*
* @param open a service to asynchronously return a [[DisposableResponse]] from
* a [[Request]]. This is a low-level operation intended for client
* implementations and middleware.
*
* @param shutdown a Task to shut down this Shutdown this client, closing any
* open connections and freeing resources
*/
final case class Client(open: Service[Request, DisposableResponse], shutdown: Task[Unit]) {
/** Submits a request, and provides a callback to process the response.
*
* @param req The request to submit
* @param f A callback for the response to req. The underlying HTTP connection
* is disposed when the returned task completes. Attempts to read the
* response body afterward will result in an error.
* @return The result of applying f to the response to req
*/
def fetch[A](req: Request)(f: Response => Task[A]): Task[A] =
open.run(req).flatMap(_.apply(f))
/**
* Returns this client as a [[Service]]. All connections created by this
* service are disposed on completion of callback task f.
*
* This method effectively reverses the arguments to `fetch`, and is
* preferred when an HTTP client is composed into a larger Kleisli function,
* or when a common response callback is used by many call sites.
*/
def toService[A](f: Response => Task[A]): Service[Request, A] =
open.flatMapK(_.apply(f))
/**
* Returns this client as an [[HttpService]]. It is the responsibility of
* callers of this service to run the response body to dispose of the
* underlying HTTP connection.
*
* This is intended for use in proxy servers. `fetch`, `fetchAs`,
* [[toService]], and [[streaming]] are safer alternatives, as their
* signatures guarantee disposal of the HTTP connection.
*/
def toHttpService: HttpService =
open.map { case DisposableResponse(response, dispose) =>
response.copy(body = response.body.onComplete(eval_(dispose)))
}
def streaming[A](req: Request)(f: Response => Process[Task, A]): Process[Task, A] =
eval(open(req).map { case DisposableResponse(response, dispose) =>
f(response).onComplete(eval_(dispose))
}).flatMap(identity)
/**
* Submits a request and decodes the response on success. On failure, the
* status code is returned. The underlying HTTP connection is closed at the
* completion of the decoding.
*/
def expect[A](req: Request)(implicit d: EntityDecoder[A]): Task[A] = {
val r = if (d.consumes.nonEmpty) {
val m = d.consumes.toList
req.putHeaders(Accept(MediaRangeAndQValue(m.head), m.tail.map(MediaRangeAndQValue(_)):_*))
} else req
fetch(r) {
case Successful(resp) =>
d.decode(resp, strict = false).fold(throw _, identity)
case failedResponse =>
Task.fail(UnexpectedStatus(failedResponse.status))
}
}
/**
* Submits a request and decodes the response, regardless of the status code.
* The underlying HTTP connection is closed at the completion of the
* decoding.
*/
def fetchAs[A](req: Request)(implicit d: EntityDecoder[A]): Task[A] = {
val r = if (d.consumes.nonEmpty) {
val m = d.consumes.toList
req.putHeaders(Accept(MediaRangeAndQValue(m.head), m.tail.map(MediaRangeAndQValue(_)):_*))
} else req
fetch(r) { resp =>
d.decode(resp, strict = false).fold(throw _, identity)
}
}
@deprecated("Use expect", "0.14")
def prepAs[A](req: Request)(implicit d: EntityDecoder[A]): Task[A] =
fetchAs(req)(d)
/** Submits a GET request, and provides a callback to process the response.
*
* @param uri The URI to GET
* @param f A callback for the response to a GET on uri. The underlying HTTP connection
* is disposed when the returned task completes. Attempts to read the
* response body afterward will result in an error.
* @return The result of applying f to the response to req
*/
def get[A](uri: Uri)(f: Response => Task[A]): Task[A] =
fetch(Request(Method.GET, uri))(f)
/**
* Submits a request and decodes the response on success. On failure, the
* status code is returned. The underlying HTTP connection is closed at the
* completion of the decoding.
*/
def get[A](s: String)(f: Response => Task[A]): Task[A] =
Uri.fromString(s).fold(Task.fail, uri => get(uri)(f))
/**
* Submits a GET request to the specified URI and decodes the response on
* success. On failure, the status code is returned. The underlying HTTP
* connection is closed at the completion of the decoding.
*/
def expect[A](uri: Uri)(implicit d: EntityDecoder[A]): Task[A] =
expect(Request(Method.GET, uri))(d)
/**
* Submits a GET request to the URI specified by the String and decodes the
* response on success. On failure, the status code is returned. The
* underlying HTTP connection is closed at the completion of the decoding.
*/
def expect[A](s: String)(implicit d: EntityDecoder[A]): Task[A] =
Uri.fromString(s).fold(Task.fail, expect[A])
/**
* Submits a GET request and decodes the response. The underlying HTTP
* connection is closed at the completion of the decoding.
*/
@deprecated("Use expect", "0.14")
def getAs[A](uri: Uri)(implicit d: EntityDecoder[A]): Task[A] =
fetchAs(Request(Method.GET, uri))(d)
@deprecated("Use expect", "0.14")
def getAs[A](s: String)(implicit d: EntityDecoder[A]): Task[A] =
Uri.fromString(s).fold(Task.fail, uri => getAs[A](uri))
/** Submits a request, and provides a callback to process the response.
*
* @param req A Task of the request to submit
* @param f A callback for the response to req. The underlying HTTP connection
* is disposed when the returned task completes. Attempts to read the
* response body afterward will result in an error.
* @return The result of applying f to the response to req
*/
def fetch[A](req: Task[Request])(f: Response => Task[A]): Task[A] =
req.flatMap(fetch(_)(f))
def expect[A](req: Task[Request])(implicit d: EntityDecoder[A]): Task[A] =
req.flatMap(expect(_)(d))
/**
* Submits a request and decodes the response, regardless of the status code.
* The underlying HTTP connection is closed at the completion of the
* decoding.
*/
@deprecated("Use expect", "0.14")
def fetchAs[A](req: Task[Request])(implicit d: EntityDecoder[A]): Task[A] =
req.flatMap(fetchAs(_)(d))
@deprecated("Use expect", "0.14")
def prepAs[T](req: Task[Request])(implicit d: EntityDecoder[T]): Task[T] =
fetchAs(req)(d)
/** Shuts this client down, and blocks until complete. */
def shutdownNow(): Unit =
shutdown.unsafePerformSync
}
object Client {
/** Creates a client from the specified service. Useful for generating
* pre-determined responses for requests in testing.
*
* @param service the service to respond to requests to this client
*/
def fromHttpService(service: HttpService): Client = {
val isShutdown = new AtomicBoolean(false)
def interruptible(body: EntityBody, disposed: AtomicBoolean) = {
def loop(reason: String, killed: AtomicBoolean): Process1[ByteVector, ByteVector] = {
if (killed.get)
fail(new IOException(reason))
else
await1[ByteVector] ++ loop(reason, killed)
}
body.pipe(loop("response was disposed", disposed))
.pipe(loop("client was shut down", isShutdown))
}
def disposableService(service: HttpService) =
Service.lift { req: Request =>
val disposed = new AtomicBoolean(false)
val req0 = req.copy(body = interruptible(req.body, disposed))
service(req0) map { maybeResp =>
val resp = maybeResp.orNotFound
DisposableResponse(
resp.copy(body = interruptible(resp.body, disposed)),
Task.delay(disposed.set(true))
)
}
}
Client(disposableService(service),
Task.delay(isShutdown.set(true)))
}
}
final case class UnexpectedStatus(status: Status) extends RuntimeException with NoStackTrace {
override def getMessage: String = s"unexpected HTTP status: $status"
}