-
Notifications
You must be signed in to change notification settings - Fork 0
/
Schema.scala
384 lines (333 loc) · 13.5 KB
/
Schema.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
/*
* Copyright 2021 Erlend Hamnaberg
*
* SPDX-License-Identifier: Apache-2.0
*/
package net.hamnaberg.schema
import cats.Eval
import cats.data.{Chain, NonEmptyChain, ValidatedNel}
import cats.syntax.all._
import cats.free.FreeApplicative
import io.circe._
import net.hamnaberg.schema.internal.{encoding, validation}
import sttp.apispec.{
AnySchema,
ExampleSingleValue,
Pattern,
Reference,
ReferenceOr,
SchemaLike,
Schema => ApiSpecSchema
}
import java.time.{Instant, LocalDate, OffsetDateTime, ZonedDateTime}
import java.time.format.DateTimeFormatter
import java.time.temporal.TemporalAccessor
import java.util.UUID
import scala.annotation.nowarn
import scala.collection.immutable
import scala.util.Try
sealed trait Schema[A] extends Product with Serializable { self =>
import structure._
def compiled: SchemaLike = compiled_.value
def decoder: Decoder[A] = decoder_.value
def encoder: Encoder[A] = encoder_.value
def encode(a: A): Json = encoder(a)
def decode(json: Json): Decoder.Result[A] = decoder.decodeJson(json)
def validate(json: Json): ValidatedNel[ValidationError, Json] = validation.eval(this, json, Nil)
def validateDecode(json: Json): ValidatedNel[ValidationError, A] = validation
.eval(this, json, Nil)
.andThen(decode(_).fold(err => ValidationError(err.message, err.history).invalidNel, _.validNel))
def asList(reference: Option[Reference] = None, min: Option[Int] = None, max: Option[Int] = None): Schema[List[A]] =
Sequence(this, reference, min, max)
def asVector(
reference: Option[Reference] = None,
min: Option[Int] = None,
max: Option[Int] = None): Schema[Vector[A]] =
asList(reference, min, max).imap(_.toVector)(_.toList)
def asSeq(
reference: Option[Reference] = None,
min: Option[Int] = None,
max: Option[Int] = None): Schema[immutable.Seq[A]] =
asList(reference, min, max).imap[immutable.Seq[A]](x => x)(_.toList)
def reference(ref: Reference): Schema[A] = Custom(Left(ref), encoder, decoder)
def at(field: String, ref: Option[Reference] = None): Schema[A] =
Schema.record[A](_(field, identity)(ref.map(this.reference).getOrElse(this)))
def withDescription(description: String) =
this match {
case Meta(schema, meta, _, title) =>
Meta(schema, meta, Some(description), title)
case other =>
Meta(other, None, Some(description), None)
}
def withTitle(title: String) =
this match {
case Meta(schema, meta, desc, _) =>
Meta(schema, meta, desc, Some(title))
case other =>
Meta(other, None, None, Some(title))
}
def withMetaSchema(metaSchema: String) =
this match {
case Meta(schema, _, desc, title) =>
Meta(schema, Some(metaSchema), desc, title)
case other =>
Meta(other, Some(metaSchema), None, None)
}
def xmap[B](f: A => Decoder.Result[B])(g: B => A): Schema[B] =
Isos {
new XMap[B] {
type Repr = A
val schema = self
val r = f
val w = g
}
}
def imap[B](f: A => B)(g: B => A): Schema[B] =
Isos {
new XMap[B] {
type Repr = A
val schema = self
val r = f.andThen(_.asRight)
val w = g
}
}
val compiled_ : Eval[SchemaLike] = Eval.later(
internal.ApiSpecModel.schemaFor(this)
)
val decoder_ : Eval[Decoder[A]] = Eval.later(
internal.decoding.fromSchema(this)
)
val encoder_ : Eval[Encoder[A]] = Eval.later(
internal.encoding.fromSchema(this)
)
}
object Schema {
import structure._
def apply[A](implicit S: Schema[A]) = S
def boundedInt(bounds: Bounds[Int]): Schema[Int] =
SInt(Some("int32"), bounds).xmap(_.toInt.toRight(DecodingFailure("Invalid int", Nil)))(i =>
JsonNumber.fromIntegralStringUnsafe(i.toString))
def boundedLong(bounds: Bounds[Long]): Schema[Long] =
SInt(Some("int64"), bounds).xmap(_.toLong.toRight(DecodingFailure("Invalid long", Nil)))(i =>
JsonNumber.fromIntegralStringUnsafe(i.toString))
def boundedDouble(bounds: Bounds[Double]): Schema[Double] =
SNum(Some("double"), bounds).xmap(_.toDouble.asRight)(i => JsonNumber.fromDecimalStringUnsafe(i.toString))
def boundedBigInt(bounds: Bounds[BigInt]): Schema[BigInt] =
SInt(None, bounds).xmap(_.toBigInt.toRight(DecodingFailure("Invalid bigint", Nil)))(i =>
JsonNumber.fromIntegralStringUnsafe(i.toString))
def boundedFloat(bounds: Bounds[Float]): Schema[Float] =
SNum(Some("float"), bounds).xmap(_.toFloat.asRight)(i => JsonNumber.fromDecimalStringUnsafe(i.toString))
def fields[R](p: FreeApplicative[Field[R, *], R]): Schema[R] = Record(p)
def record[R](
b: FieldBuilder[R] => FreeApplicative[Field[R, *], R]
): Schema[R] =
fields(b(field))
def defer[A](schema: => Schema[A]): Schema[A] = Defer(() => schema)
def custom[A](schema: ApiSpecSchema, encoder: Encoder[A], decoder: Decoder[A]): Schema[A] =
Custom(Right(schema), encoder, decoder)
def allOf[A](schemas: NonEmptyChain[Schema[A]], schema: Option[Schema[A]]): Schema[A] = AllOf(schemas, schema)
def anyOf[A](schemas: NonEmptyChain[Schema[A]], schema: Option[Schema[A]]): Schema[A] = AnyOf(schemas, schema)
def alternatives[A](cases: Chain[Alt[A]]): Schema[A] =
Sum(cases)
def oneOf[A](b: AltBuilder[A] => Chain[Alt[A]]): Schema[A] =
alternatives(b(alt))
//TODO: According to https://json-schema.org/draft/2020-12/json-schema-validation.html#section-6.1.2
//this can be any type
def enumeration(options: List[String]) =
Enumeration(options)
def string[A](
format: Option[String] = None,
minLength: Option[Int] = None,
maxLength: Option[Int] = None,
pattern: Option[Pattern] = None
): Schema[String] = Str(format, minLength, maxLength, pattern)
def field[R] = new FieldBuilder[R]
def alt[R] = new AltBuilder[R]
class FieldBuilder[R] {
def apply[E](
name: String,
get: R => E,
default: Option[E] = None
)(implicit elemSchema: Schema[E]): FreeApplicative[Field[R, *], E] =
FreeApplicative.lift(Field.Required(name, elemSchema, default, get))
def pure[A](a: A): FreeApplicative[Field[R, *], A] = FreeApplicative.pure(a)
def const[V](
name: String,
value: V
)(implicit valueSchema: Schema[V]): FreeApplicative[Field[R, *], Unit] =
apply(name, _ => ()) {
valueSchema.xmap { r =>
Either.cond((r == value), (), DecodingFailure("Const not equal to self", Nil))
}(_ => value)
}
def opt[E](
name: String,
get: R => Option[E]
)(implicit elemSchema: Schema[E]): FreeApplicative[Field[R, *], Option[E]] =
FreeApplicative.lift(
Field.Optional(name, elemSchema, get): Field[R, Option[E]]
)
}
class AltBuilder[A] {
def apply[B](
caseSchema_ : Schema[B]
)(implicit prism_ : Prism[A, B]): Chain[Alt[A]] =
Chain.one {
new Alt[A] {
type Case = B
val caseSchema = caseSchema_
val prism = prism_
}
}
}
implicit val int: Schema[Int] = boundedInt(Bounds.empty)
implicit val long: Schema[Long] = boundedLong(Bounds.empty)
implicit val bigInt: Schema[BigInt] = boundedBigInt(Bounds.empty)
implicit val double: Schema[Double] = boundedDouble(Bounds.empty)
implicit val float: Schema[Float] = boundedFloat(Bounds.empty)
implicit val stringInstance: Schema[String] = string()
implicit val uuid: Schema[UUID] = Str(Some("uuid")).xmap(s =>
Try(UUID.fromString(s)).toEither.leftMap(m =>
DecodingFailure(Option(m.getMessage).getOrElse("Not a valid UUID"), Nil)))(_.toString)
implicit val anything: Schema[Json] = Custom(Right(AnySchema.Anything), Encoder[Json], Decoder[Json])
implicit val instant: Schema[Instant] =
_dateFormat(DateTimeFormatter.ISO_INSTANT, "date-time", (s, _) => Instant.parse(s))
implicit val zonedDateTime: Schema[ZonedDateTime] = _dateFormat(
DateTimeFormatter.ISO_ZONED_DATE_TIME,
"date-time",
(s, format) => ZonedDateTime.parse(s, format)
)
implicit val offsetDateTime: Schema[OffsetDateTime] = _dateFormat(
DateTimeFormatter.ISO_OFFSET_DATE_TIME,
"date-time",
(s, format) => OffsetDateTime.parse(s, format)
)
implicit val localDate: Schema[LocalDate] = _dateFormat(
DateTimeFormatter.ISO_LOCAL_DATE,
"date",
(s, format) => LocalDate.parse(s, format)
)
def _dateFormat[A <: TemporalAccessor](
formatter: DateTimeFormatter,
typ: String,
f: (String, DateTimeFormatter) => A) =
Str(Some(typ)).xmap(s =>
Try(f(s, formatter)).toEither.leftMap(m =>
DecodingFailure(Option(m.getMessage).getOrElse(s"Does not parse from ${formatter.toFormat}"), Nil)))(b =>
formatter.format(b))
implicit def unboundedVector[A](implicit s: Schema[A]): Schema[Vector[A]] = s.asVector()
implicit def unboundedList[A](implicit s: Schema[A]): Schema[List[A]] = s.asList()
implicit def unboundedSeq[A](implicit s: Schema[A]): Schema[immutable.Seq[A]] = s.asSeq()
}
object structure {
@nowarn
final case class SInt[A: Integral](format: Option[String], bounds: Bounds[A]) extends Schema[JsonNumber]
@nowarn
final case class SNum[A: Fractional](format: Option[String], bounds: Bounds[A]) extends Schema[JsonNumber]
case object SBool extends Schema[Boolean]
final case class Str(
format: Option[String] = None,
minLength: Option[Int] = None,
maxLength: Option[Int] = None,
pattern: Option[Pattern] = None
) extends Schema[String]
final case class Sequence[A](
value: Schema[A],
reference: Option[Reference] = None,
min: Option[Int] = None,
max: Option[Int] = None)
extends Schema[List[A]]
final case class Record[R](value: FreeApplicative[Field[R, *], R]) extends Schema[R]
final case class Isos[A](value: XMap[A]) extends Schema[A]
final case class Defer[A](value: () => Schema[A]) extends Schema[A]
//todo: enums may be of any type
final case class Enumeration(allowed: List[String]) extends Schema[String]
final case class AllOf[A](value: NonEmptyChain[Schema[A]], targetSchema: Option[Schema[A]]) extends Schema[A]
final case class AnyOf[A](value: NonEmptyChain[Schema[A]], targetSchema: Option[Schema[A]]) extends Schema[A]
final case class Sum[A](value: Chain[Alt[A]]) extends Schema[A]
final case class Custom[A](_compiled: ReferenceOr[SchemaLike], _encoder: Encoder[A], _decoder: Decoder[A])
extends Schema[A]
final case class Meta[A](
schema: Schema[A],
metaSchema: Option[String],
description: Option[String],
title: Option[String])
extends Schema[A]
sealed trait Field[R, E] extends Product with Serializable {
private[schema] def decode(c: HCursor): Decoder.Result[E]
private[schema] def encode(obj: R): List[(String, Json)]
private[schema] def validate(json: JsonObject, history: List[CursorOp]): ValidatedNel[ValidationError, Unit]
private[schema] def apiSpecSchema: List[(String, ApiSpecSchema)]
}
object Field {
private def write[E](name: String, schema: Schema[E], elem: E): List[(String, Json)] =
List(name -> internal.encoding.fromSchema(schema).apply(elem))
final case class Optional[R, E](
name: String,
elemSchema: Schema[E],
get: R => Option[E]
) extends Field[R, Option[E]] {
private[schema] override def decode(c: HCursor): Decoder.Result[Option[E]] = {
val from = internal.decoding.fromSchema(elemSchema)
c.get(name)(Decoder.decodeOption(from))
}
override private[schema] def encode(obj: R) = {
val elem = get(obj)
elem.foldMap(write(name, elemSchema, _))
}
override private[schema] def validate(
json: JsonObject,
history: List[CursorOp]): ValidatedNel[ValidationError, Unit] = {
val next = CursorOp.Field(name) :: history
json(name) match {
case Some(Json.Null) => ().validNel
case Some(value) => internal.validation.eval(elemSchema, value, next).map(_ => ())
case None => ().validNel
}
}
override private[schema] def apiSpecSchema =
List(name -> internal.ApiSpecModel.schemaFor(elemSchema).copy(nullable = Some(true)))
}
final case class Required[R, E](
name: String,
elemSchema: Schema[E],
default: Option[E],
get: R => E
) extends Field[R, E] {
private[schema] override def decode(c: HCursor) = {
val down = c.downField(name)
default match {
case Some(value) if down.failed => Right(value)
case _ => down.as(internal.decoding.fromSchema(elemSchema))
}
}
override private[schema] def encode(obj: R) =
write(name, elemSchema, get(obj))
override private[schema] def validate(
json: JsonObject,
history: List[CursorOp]): ValidatedNel[ValidationError, Unit] = {
val next = CursorOp.Field(name) :: history
json(name) match {
case Some(value) => internal.validation.eval(elemSchema, value, next).map(_ => ())
case None if default.isDefined => ().validNel
case None => ValidationError("Not a valid object", next).invalidNel
}
}
override private[schema] def apiSpecSchema = List(
name -> internal.ApiSpecModel
.schemaFor(elemSchema)
.copy(default = default.map(e => ExampleSingleValue(encoding.fromSchema(elemSchema).apply(e).noSpaces))))
}
}
trait Alt[A] extends Serializable {
type Case
def caseSchema: Schema[Case]
def prism: Prism[A, Case]
}
trait XMap[A] extends Serializable {
type Repr
def schema: Schema[Repr]
def w: A => Repr
def r: Repr => Decoder.Result[A]
}
}