-
Notifications
You must be signed in to change notification settings - Fork 1
/
smithy4s-fetch.scala
339 lines (292 loc) · 9.18 KB
/
smithy4s-fetch.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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
package smithy4s_fetch
import org.scalajs.dom.{Fetch, Headers, Request, RequestInfo, Response, URL}
import smithy4s.Endpoint.Middleware
import smithy4s.capability.MonadThrowLike
import smithy4s.client.*
import smithy4s.codecs.BlobEncoder
import smithy4s.http.HttpUriScheme.{Http, Https}
import smithy4s.http.{
CaseInsensitive,
HttpMethod,
HttpRequest,
HttpUnaryClientCodecs,
Metadata
}
import smithy4s.json.Json
import smithy4s.{Blob, Endpoint}
import scala.scalajs.js.Promise
import scala.scalajs.js.typedarray.Int8Array
import scalajs.js.JSConverters.*
import smithy4s.http.HttpDiscriminator
import org.scalajs.dom.RequestInit
class SimpleRestJsonFetchClient[
Alg[_[_, _, _, _, _]]
] private[smithy4s_fetch] (
service: smithy4s.Service[Alg],
uri: URL,
middleware: Endpoint.Middleware[SimpleRestJsonFetchClient.Client],
codecs: SimpleRestJsonCodecs
) {
def withMaxArity(maxArity: Int): SimpleRestJsonFetchClient[Alg] =
changeCodecs(_.copy(maxArity = maxArity))
def withExplicitDefaultsEncoding(
explicitDefaultsEncoding: Boolean
): SimpleRestJsonFetchClient[Alg] =
changeCodecs(_.copy(explicitDefaultsEncoding = explicitDefaultsEncoding))
def withHostPrefixInjection(
hostPrefixInjection: Boolean
): SimpleRestJsonFetchClient[Alg] =
changeCodecs(_.copy(hostPrefixInjection = hostPrefixInjection))
def make: Alg[[I, E, O, SI, SO] =>> Promise[O]] =
service.impl[Promise](
UnaryClientCompiler[
Alg,
Promise,
SimpleRestJsonFetchClient.Client,
RequestInfo,
Response
](
service = service,
toSmithy4sClient = SimpleRestJsonFetchClient.lowLevelClient(_),
client = Fetch.fetch(_),
middleware = middleware,
makeClientCodecs = codecs.makeClientCodecs(uri),
isSuccessful = resp => resp.ok
)
)
private def changeCodecs(
f: SimpleRestJsonCodecs => SimpleRestJsonCodecs
): SimpleRestJsonFetchClient[Alg] =
new SimpleRestJsonFetchClient(
service,
uri,
middleware,
f(codecs)
)
}
object SimpleRestJsonFetchClient {
type Client = RequestInfo => Promise[Response]
def apply[Alg[_[_, _, _, _, _]]](
service: smithy4s.Service[Alg],
url: String
) =
new SimpleRestJsonFetchClient(
service = service,
uri = new URL(url),
codecs = SimpleRestJsonCodecs,
middleware = Endpoint.Middleware.noop
)
private def lowLevelClient(fetch: Client) =
new UnaryLowLevelClient[Promise, RequestInfo, Response] {
override def run[Output](request: RequestInfo)(
responseCB: Response => Promise[Output]
): Promise[Output] =
fetch(request).`then`(resp => responseCB(resp))
}
}
private[smithy4s_fetch] object SimpleRestJsonCodecs
extends SimpleRestJsonCodecs(1024, false, false)
private[smithy4s_fetch] case class SimpleRestJsonCodecs(
maxArity: Int,
explicitDefaultsEncoding: Boolean,
hostPrefixInjection: Boolean
) {
private val hintMask =
alloy.SimpleRestJson.protocol.hintMask
def unsafeFromSmithy4sHttpMethod(
method: smithy4s.http.HttpMethod
): org.scalajs.dom.HttpMethod =
import smithy4s.http.HttpMethod.*
import org.scalajs.dom.HttpMethod as FetchMethod
method match
case GET => FetchMethod.GET
case PUT => FetchMethod.PUT
case POST => FetchMethod.POST
case DELETE => FetchMethod.DELETE
case PATCH => FetchMethod.PATCH
case OTHER(nm) => nm.asInstanceOf[FetchMethod]
def toHeaders(smithyHeaders: Map[CaseInsensitive, Seq[String]]): Headers = {
val h = new Headers()
smithyHeaders.foreach { case (name, values) =>
values.foreach { value =>
h.append(name.toString, value)
}
}
h
}
def fromSmithy4sHttpUri(uri: smithy4s.http.HttpUri): String = {
val qp = uri.queryParams
val protocol = {
uri.scheme match
case Http => "http"
case Https => "https"
}
val hostName = uri.host
val port =
uri.port
.filterNot(p => uri.host.endsWith(s":$p"))
.map(":" + _.toString)
.getOrElse("")
val path = "/" + uri.path.mkString("/")
val query =
if qp.isEmpty then ""
else
var b = "?"
qp.zipWithIndex.map:
case ((key, values), idx) =>
if idx != 0 then b += "&"
b += key
for
i <- 0 until values.length
value = values(i)
do
if i == 0 then b += "=" + value
else b += s"&$key=$value"
b
s"$protocol://$hostName$port$path$query"
}
def toSmithy4sHttpResponse(
resp: Response
): Promise[smithy4s.http.HttpResponse[Blob]] = {
resp
.arrayBuffer()
.`then`: body =>
val headers = Map.newBuilder[CaseInsensitive, Seq[String]]
resp.headers.foreach:
case arr if arr.size >= 2 =>
val header = arr(0)
val values = arr.tail.toSeq
headers += CaseInsensitive(header) -> values
case _ =>
smithy4s.http.HttpResponse(
resp.status,
headers.result(),
Blob(new Int8Array(body).toArray)
)
}
def fromSmithy4sHttpRequest(
req: smithy4s.http.HttpRequest[Blob]
): Request = {
val m = unsafeFromSmithy4sHttpMethod(req.method)
val h = toHeaders(req.headers)
val ri = new RequestInit {}
if (req.body.size != 0) {
val arr = new Int8Array(req.body.size)
arr.set(
req.body.toArray.toJSArray,
0
)
ri.body = arr
h.append("Content-Length", req.body.size.toString)
}
ri.method = m
ri.headers = h
new Request(fromSmithy4sHttpUri(req.uri), ri)
}
def toSmithy4sHttpUri(
uri: URL,
pathParams: Option[smithy4s.http.PathParams] = None
): smithy4s.http.HttpUri = {
import smithy4s.http.*
val uriScheme = uri.protocol match {
case "https:" => HttpUriScheme.Https
case "http:" => HttpUriScheme.Http
case _ =>
throw UnsupportedOperationException(
s"Protocol `${uri.protocol}` is not supported"
)
}
HttpUri(
uriScheme,
uri.host,
uri.port.toIntOption,
uri.pathname
// drop the guaranteed leading slash, so that we don't produce an empty segment for it
.tail
// splitting an empty path would produce a single element, so we special-case to empty
.match {
case "" => IndexedSeq.empty
case other => other.split("/")
},
uri.searchParams
.entries()
.toIterator
.toSeq
.groupMap(_._1)(_._2)
.toMap,
pathParams
)
}
val jsonCodecs = Json.payloadCodecs
.withJsoniterCodecCompiler(
Json.jsoniter
.withHintMask(hintMask)
.withMaxArity(maxArity)
.withExplicitDefaultsEncoding(explicitNulls = true)
)
val payloadEncoders: BlobEncoder.Compiler =
jsonCodecs.encoders
val payloadDecoders =
jsonCodecs.decoders
val errorHeaders = List(
smithy4s.http.errorTypeHeader
)
def makeClientCodecs(
uri: URL
): UnaryClientCodecs.Make[Promise, RequestInfo, Response] = {
val baseRequest = HttpRequest(
HttpMethod.POST,
toSmithy4sHttpUri(uri, None),
Map.empty,
Blob.empty
)
HttpUnaryClientCodecs.builder
.withBodyEncoders(payloadEncoders)
.withSuccessBodyDecoders(payloadDecoders)
.withErrorBodyDecoders(payloadDecoders)
.withErrorDiscriminator(resp =>
Promise.resolve(HttpDiscriminator.fromResponse(errorHeaders, resp))
)
.withMetadataDecoders(Metadata.Decoder)
.withMetadataEncoders(
Metadata.Encoder.withExplicitDefaultsEncoding(
explicitDefaultsEncoding
)
)
.withBaseRequest(_ => Promise.resolve(baseRequest))
.withRequestMediaType("application/json")
.withRequestTransformation(req =>
Promise.resolve(fromSmithy4sHttpRequest(req))
)
.withResponseTransformation[Response](resp =>
Promise.resolve(toSmithy4sHttpResponse(resp))
)
.withHostPrefixInjection(hostPrefixInjection)
.build()
}
}
given MonadThrowLike[Promise] with
override def map[A, B](fa: Promise[A])(f: A => B): Promise[B] = fa.`then`(f)
override def flatMap[A, B](fa: Promise[A])(f: A => Promise[B]): Promise[B] =
fa.`then`(f)
override def handleErrorWith[A](fa: Promise[A])(
f: Throwable => Promise[A]
): Promise[A] = fa.`catch`:
case ex: Throwable => f(ex) // TODO: does this make sense?
override def pure[A](a: A): Promise[A] = Promise.resolve(a)
override def raiseError[A](e: Throwable): Promise[A] = Promise.reject(e)
override def zipMapAll[A](seq: IndexedSeq[Promise[Any]])(
f: IndexedSeq[Any] => A
): Promise[A] =
Promise.all(seq.toJSIterable).`then`(res => Promise.resolve(f(res.toArray)))
override def zipMap[A, B, C](fa: Promise[A], fb: Promise[B])(
f: (A, B) => C
): Promise[C] = Promise
.all[Either[A, B]](
Seq(fa.`then`(Left(_)), fb.`then`(Right(_))).toJSIterable
)
.`then`: arr =>
(arr(0), arr(1)) match
case (Left(x), Right(y)) => f(x, y)
case (Right(y), Left(x)) => f(x, y)
case _ => ???