-
Notifications
You must be signed in to change notification settings - Fork 787
/
CirceInstances.scala
344 lines (286 loc) · 12.6 KB
/
CirceInstances.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
340
341
342
343
344
/*
* Copyright 2015 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 circe
import cats.data.NonEmptyList
import cats.effect.Concurrent
import cats.syntax.either._
import fs2.Chunk
import fs2.Pull
import fs2.Stream
import io.circe._
import io.circe.jawn._
import org.http4s.headers.`Content-Type`
import org.http4s.jawn.JawnInstances
import org.typelevel.jawn.ParseException
import org.typelevel.jawn.fs2.unwrapJsonArray
trait CirceInstances extends JawnInstances {
protected val circeSupportParser =
new CirceSupportParser(maxValueSize = None, allowDuplicateKeys = false)
import circeSupportParser.facade
protected def defaultPrinter: Printer = Printer.noSpaces
protected def circeParseExceptionMessage: ParsingFailure => DecodeFailure =
CirceInstances.defaultCirceParseError
protected def jsonDecodeError: (Json, NonEmptyList[DecodingFailure]) => DecodeFailure =
CirceInstances.defaultJsonDecodeError
def jsonDecoderIncremental[F[_]: Concurrent]: EntityDecoder[F, Json] =
this.jawnDecoder[F, Json]
def jsonDecoderByteBuffer[F[_]: Concurrent]: EntityDecoder[F, Json] =
EntityDecoder.decodeBy(MediaType.application.json)(jsonDecoderByteBufferImpl[F])
private def jsonDecoderByteBufferImpl[F[_]: Concurrent](m: Media[F]): DecodeResult[F, Json] =
EntityDecoder.collectBinary(m).subflatMap { chunk =>
val bb = chunk.toByteBuffer
if (bb.hasRemaining)
circeSupportParser
.parseFromByteBuffer(bb)
.toEither
.leftMap(e => circeParseExceptionMessage(ParsingFailure(e.getMessage(), e)))
else
Left(jawnEmptyBodyMessage)
}
// default cutoff value is based on benchmarks results
implicit def jsonDecoder[F[_]: Concurrent]: EntityDecoder[F, Json] =
jsonDecoderAdaptive(cutoff = 100000, MediaType.application.json)
def jsonDecoderAdaptive[F[_]: Concurrent](
cutoff: Long,
r1: MediaRange,
rs: MediaRange*
): EntityDecoder[F, Json] =
EntityDecoder.decodeBy(r1, rs: _*) { msg =>
msg.contentLength match {
case Some(contentLength) if contentLength < cutoff =>
jsonDecoderByteBufferImpl[F](msg)
case _ => this.jawnDecoderImpl[F, Json](msg)
}
}
def jsonOf[F[_]: Concurrent, A: Decoder]: EntityDecoder[F, A] =
jsonOfWithMedia(MediaType.application.json)
def jsonOfSensitive[F[_]: Concurrent, A: Decoder](redact: Json => String): EntityDecoder[F, A] =
jsonOfWithSensitiveMedia(redact, MediaType.application.json)
def jsonOfWithMedia[F[_], A](r1: MediaRange, rs: MediaRange*)(implicit
F: Concurrent[F],
decoder: Decoder[A],
): EntityDecoder[F, A] =
jsonOfWithMediaHelper[F, A](r1, jsonDecodeError, rs: _*)
def jsonOfWithSensitiveMedia[F[_], A](
redact: Json => String,
r1: MediaRange,
rs: MediaRange*
)(implicit F: Concurrent[F], decoder: Decoder[A]): EntityDecoder[F, A] =
jsonOfWithMediaHelper[F, A](
r1,
(json, nelDecodeFailures) =>
CirceInstances.jsonDecodeErrorHelper(json, redact, nelDecodeFailures),
rs: _*
)
private def jsonOfWithMediaHelper[F[_], A](
r1: MediaRange,
decodeErrorHandler: (Json, NonEmptyList[DecodingFailure]) => DecodeFailure,
rs: MediaRange*
)(implicit F: Concurrent[F], decoder: Decoder[A]): EntityDecoder[F, A] =
jsonDecoderAdaptive[F](cutoff = 100000, r1, rs: _*).flatMapR { json =>
decoder
.decodeJson(json)
.fold(
failure => DecodeResult.failureT(decodeErrorHandler(json, NonEmptyList.one(failure))),
DecodeResult.successT(_),
)
}
/** An [[EntityDecoder]] that uses circe's accumulating decoder for decoding the JSON.
*
* In case of a failure, returns an [[InvalidMessageBodyFailure]] with the cause containing
* a [[DecodingFailures]] exception, from which the errors can be extracted.
*/
def accumulatingJsonOf[F[_], A](implicit
F: Concurrent[F],
decoder: Decoder[A],
): EntityDecoder[F, A] =
jsonDecoder[F].flatMapR { json =>
decoder
.decodeAccumulating(json.hcursor)
.fold(
failures => DecodeResult.failureT(jsonDecodeError(json, failures)),
DecodeResult.successT(_),
)
}
implicit def jsonEncoder: EntityEncoder.Pure[Json] = jsonEncoderWithPrinter(defaultPrinter)
def jsonEncoderWithPrinter(printer: Printer): EntityEncoder.Pure[Json] =
EntityEncoder
.Pure[Chunk[Byte]]
.contramap[Json](CirceInstances.fromJsonToChunk(printer))
.withContentType(`Content-Type`(MediaType.application.json))
def jsonEncoderOf[A: Encoder]: EntityEncoder.Pure[A] =
jsonEncoderWithPrinterOf(defaultPrinter)
def jsonEncoderWithPrinterOf[A](printer: Printer)(implicit
encoder: Encoder[A]
): EntityEncoder.Pure[A] =
jsonEncoderWithPrinter(printer).contramap[A](encoder.apply)
implicit def streamJsonArrayEncoder[F[_]]: EntityEncoder[F, Stream[F, Json]] =
streamJsonArrayEncoderWithPrinter(defaultPrinter)
implicit def streamJsonArrayDecoder[F[_]: Concurrent]: EntityDecoder[F, Stream[F, Json]] =
EntityDecoder.decodeBy(MediaType.application.json) { media =>
DecodeResult.successT(media.body.chunks.through(unwrapJsonArray))
}
/** An [[EntityEncoder]] for a [[fs2.Stream]] of JSONs, which will encode it as a single JSON array. */
def streamJsonArrayEncoderWithPrinter[F[_]](printer: Printer): EntityEncoder[F, Stream[F, Json]] =
EntityEncoder
.streamEncoder[F, Chunk[Byte]]
.contramap[Stream[F, Json]] { stream =>
stream.through(CirceInstances.streamedJsonArray(printer)).chunks
}
.withContentType(`Content-Type`(MediaType.application.json))
def streamJsonArrayEncoderOf[F[_], A: Encoder]: EntityEncoder[F, Stream[F, A]] =
streamJsonArrayEncoderWithPrinterOf(defaultPrinter)
/** An [[EntityEncoder]] for a [[fs2.Stream]] of values, which will encode it as a single JSON array. */
def streamJsonArrayEncoderWithPrinterOf[F[_], A](printer: Printer)(implicit
encoder: Encoder[A]
): EntityEncoder[F, Stream[F, A]] =
streamJsonArrayEncoderWithPrinter[F](printer).contramap[Stream[F, A]](_.map(encoder.apply))
implicit val encodeUri: Encoder[Uri] =
Encoder.encodeString.contramap[Uri](_.toString)
implicit val decodeUri: Decoder[Uri] =
Decoder.decodeString.emap { str =>
Uri.fromString(str).leftMap(_ => "Uri")
}
implicit final def toMessageSyntax[F[_]](req: Message[F]): CirceInstances.MessageSyntax[F] =
new CirceInstances.MessageSyntax(req)
}
sealed abstract case class CirceInstancesBuilder private[circe] (
defaultPrinter: Printer = Printer.noSpaces,
jsonDecodeError: (Json, NonEmptyList[DecodingFailure]) => DecodeFailure =
CirceInstances.defaultJsonDecodeError,
circeParseExceptionMessage: ParsingFailure => DecodeFailure =
CirceInstances.defaultCirceParseError,
jawnParseExceptionMessage: ParseException => DecodeFailure =
JawnInstances.defaultJawnParseExceptionMessage,
jawnEmptyBodyMessage: DecodeFailure = JawnInstances.defaultJawnEmptyBodyMessage,
circeSupportParser: CirceSupportParser =
new CirceSupportParser(maxValueSize = None, allowDuplicateKeys = false),
) { self =>
def withPrinter(pp: Printer): CirceInstancesBuilder =
this.copy(defaultPrinter = pp)
def withJsonDecodeError(
f: (Json, NonEmptyList[DecodingFailure]) => DecodeFailure
): CirceInstancesBuilder =
this.copy(jsonDecodeError = f)
def withJawnParseExceptionMessage(f: ParseException => DecodeFailure): CirceInstancesBuilder =
this.copy(jawnParseExceptionMessage = f)
def withCirceParseExceptionMessage(f: ParsingFailure => DecodeFailure): CirceInstancesBuilder =
this.copy(circeParseExceptionMessage = f)
def withEmptyBodyMessage(df: DecodeFailure): CirceInstancesBuilder =
this.copy(jawnEmptyBodyMessage = df)
def withCirceSupportParser(csp: CirceSupportParser): CirceInstancesBuilder =
this.copy(circeSupportParser = csp)
protected def copy(
defaultPrinter: Printer = self.defaultPrinter,
jsonDecodeError: (Json, NonEmptyList[DecodingFailure]) => DecodeFailure =
self.jsonDecodeError,
circeParseExceptionMessage: ParsingFailure => DecodeFailure = self.circeParseExceptionMessage,
jawnParseExceptionMessage: ParseException => DecodeFailure = self.jawnParseExceptionMessage,
jawnEmptyBodyMessage: DecodeFailure = self.jawnEmptyBodyMessage,
circeSupportParser: CirceSupportParser = self.circeSupportParser,
): CirceInstancesBuilder =
new CirceInstancesBuilder(
defaultPrinter,
jsonDecodeError,
circeParseExceptionMessage,
jawnParseExceptionMessage,
jawnEmptyBodyMessage,
circeSupportParser,
) {}
def build: CirceInstances =
new CirceInstances {
override val circeSupportParser: CirceSupportParser = self.circeSupportParser
override val defaultPrinter: Printer = self.defaultPrinter
override val jsonDecodeError: (Json, NonEmptyList[DecodingFailure]) => DecodeFailure =
self.jsonDecodeError
override val circeParseExceptionMessage: ParsingFailure => DecodeFailure =
self.circeParseExceptionMessage
override val jawnParseExceptionMessage: ParseException => DecodeFailure =
self.jawnParseExceptionMessage
override val jawnEmptyBodyMessage: DecodeFailure = self.jawnEmptyBodyMessage
}
}
object CirceInstances {
def withPrinter(p: Printer): CirceInstancesBuilder =
builder.withPrinter(p)
val builder: CirceInstancesBuilder = new CirceInstancesBuilder() {}
// These are lazy since they are used when initializing the `builder`!
private[circe] lazy val defaultCirceParseError: ParsingFailure => DecodeFailure =
pe => MalformedMessageBodyFailure("Invalid JSON", Some(pe))
private[circe] lazy val defaultJsonDecodeError
: (Json, NonEmptyList[DecodingFailure]) => DecodeFailure = { (json, failures) =>
jsonDecodeErrorHelper(json, _.toString, failures)
}
private def jsonDecodeErrorHelper(
json: Json,
jsonToString: Json => String,
failures: NonEmptyList[DecodingFailure],
): DecodeFailure = {
val str: String = jsonToString(json)
InvalidMessageBodyFailure(
s"Could not decode JSON: $str",
if (failures.tail.isEmpty) Some(failures.head) else Some(DecodingFailures(failures)),
)
}
// Constant byte chunks for the stream as JSON array encoder.
private def fromJsonToChunk(printer: Printer)(json: Json): Chunk[Byte] =
Chunk.ByteBuffer.view(printer.printToByteBuffer(json))
private def streamedJsonArray[F[_]](printer: Printer)(s: Stream[F, Json]): Stream[F, Byte] =
s.pull.uncons1.flatMap {
case None => Pull.output(emptyArray)
case Some((hd, tl)) =>
Pull.output(
Chunk.concat(Vector(CirceInstances.openBrace, fromJsonToChunk(printer)(hd)))
) >> // Output First Json As Chunk with leading `[`
tl.repeatPull {
_.uncons.flatMap {
case None => Pull.pure(None)
case Some((hd, tl)) =>
val interspersed = {
val bldr = Chunk.newBuilder[Byte]
hd.foreach { o =>
bldr += CirceInstances.comma
bldr += fromJsonToChunk(printer)(o)
}
bldr.result
}
Pull.output(interspersed) >> Pull.pure(Some(tl))
}
}.pull
.echo >>
Pull.output(closeBrace)
}.stream
private final val openBrace: Chunk[Byte] =
Chunk.singleton('['.toByte)
private final val closeBrace: Chunk[Byte] =
Chunk.singleton(']'.toByte)
private final val emptyArray: Chunk[Byte] =
Chunk.array(Array('['.toByte, ']'.toByte))
private final val comma: Chunk[Byte] =
Chunk.singleton(','.toByte)
// Extension methods.
private[circe] final class MessageSyntax[F[_]](private val req: Message[F]) extends AnyVal {
def asJson(implicit F: JsonDecoder[F]): F[Json] =
F.asJson(req)
def asJsonDecode[A](implicit F: JsonDecoder[F], decoder: Decoder[A]): F[A] =
F.asJsonDecode(req)
def decodeJson[A](implicit F: Concurrent[F], decoder: Decoder[A]): F[A] =
req.as(F, jsonOf[F, A])
def json(implicit F: Concurrent[F]): F[Json] =
req.as(F, jsonDecoder[F])
}
}