Skip to content

Commit

Permalink
Reformat with scalafmt 3.7.13
Browse files Browse the repository at this point in the history
Executed command: scalafmt --non-interactive
  • Loading branch information
scala-steward committed Aug 29, 2023
1 parent 48547ec commit 9fd13b4
Show file tree
Hide file tree
Showing 14 changed files with 94 additions and 70 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,3 @@ object StaticContentSecurePekkoServer extends App {

Await.result(bindAndCheck.transformWith { r => actorSystem.terminate().transform(_ => r) }, 1.minute)
}

Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,3 @@ object PekkoUsersApi {
def options(implicit ec: ExecutionContext): CustomiseInterceptors[Future, PekkoHttpServerOptions] =
PekkoHttpServerOptions.customiseInterceptors.exceptionHandler(exceptionHandler)
}

Original file line number Diff line number Diff line change
Expand Up @@ -71,4 +71,3 @@ object WebSocketPekkoServer extends App {

Await.result(bindAndCheck.transformWith { r => actorSystem.terminate().transform(_ => r) }, 1.minute)
}

Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,11 @@ class ClassDefinitionGeneratorSpec extends CompileCheckTestBase {
Some(
OpenapiComponent(
Map(
"Test" -> OpenapiSchemaEnum("string", Seq(OpenapiSchemaConstantString("paperback"), OpenapiSchemaConstantString("hardback")), false)
"Test" -> OpenapiSchemaEnum(
"string",
Seq(OpenapiSchemaConstantString("paperback"), OpenapiSchemaConstantString("hardback")),
false
)
)
)
)
Expand Down Expand Up @@ -259,8 +263,7 @@ class ClassDefinitionGeneratorSpec extends CompileCheckTestBase {
val gen = new ClassDefinitionGenerator()
val res = gen.classDefs(doc, true)
// can't just check whether this compiles, because our tests only run on scala 2.12 - so instead just eyeball it...
res shouldBe Some(
"""enum Test derives org.latestbit.circe.adt.codec.JsonTaggedAdt.PureCodec {
res shouldBe Some("""enum Test derives org.latestbit.circe.adt.codec.JsonTaggedAdt.PureCodec {
| case enum1, enum2
|}""".stripMargin)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,19 +109,21 @@ class EndpointGeneratorSpec extends CompileCheckTestBase {
)
)
),
Some(OpenapiComponent(
Map(),
Map(
"httpBearer" -> OpenapiSecuritySchemeBearerType,
"httpBasic" -> OpenapiSecuritySchemeBasicType,
"apiKeyHeader" -> OpenapiSecuritySchemeApiKeyType("header", "X-API-KEY"),
"apiKeyCookie" -> OpenapiSecuritySchemeApiKeyType("cookie", "api_key"),
"apiKeyQuery" -> OpenapiSecuritySchemeApiKeyType("query", "api-key")
Some(
OpenapiComponent(
Map(),
Map(
"httpBearer" -> OpenapiSecuritySchemeBearerType,
"httpBasic" -> OpenapiSecuritySchemeBasicType,
"apiKeyHeader" -> OpenapiSecuritySchemeApiKeyType("header", "X-API-KEY"),
"apiKeyCookie" -> OpenapiSecuritySchemeApiKeyType("cookie", "api_key"),
"apiKeyQuery" -> OpenapiSecuritySchemeApiKeyType("query", "api-key")
)
)
))
)
)
BasicGenerator.imports ++
new EndpointGenerator().endpointDefs(doc) shouldCompile()
new EndpointGenerator().endpointDefs(doc) shouldCompile ()
}

it should "handle status codes" in {
Expand Down Expand Up @@ -165,10 +167,16 @@ class EndpointGeneratorSpec extends CompileCheckTestBase {
null
)
val generatedCode = BasicGenerator.imports ++ new EndpointGenerator().endpointDefs(doc)
generatedCode should include(""".out(stringBody.description("Processing").and(statusCode(sttp.model.StatusCode(202))))""") // status code with body
generatedCode should include(""".errorOut(stringBody.description("couldn't find thing").and(statusCode(sttp.model.StatusCode(404))))""") // error status code with body
generatedCode should include(""".errorOut(statusCode(sttp.model.StatusCode(403)).description("Not authorised"))""") // error status code, no body
generatedCode should include(
""".out(stringBody.description("Processing").and(statusCode(sttp.model.StatusCode(202))))"""
) // status code with body
generatedCode should include(
""".errorOut(stringBody.description("couldn't find thing").and(statusCode(sttp.model.StatusCode(404))))"""
) // error status code with body
generatedCode should include(
""".errorOut(statusCode(sttp.model.StatusCode(403)).description("Not authorised"))"""
) // error status code, no body
generatedCode should include(""".out(statusCode(sttp.model.StatusCode(204)).description("No body"))""") // status code, no body
generatedCode shouldCompile()
generatedCode shouldCompile ()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,9 @@ class SchemaParserSpec extends AnyFlatSpec with Matchers with Checkers {
| name: api-key""".stripMargin

val res = parser
.parse(yaml)
.leftMap(err => err: Error)
.flatMap(_.as[OpenapiComponent])
.parse(yaml)
.leftMap(err => err: Error)
.flatMap(_.as[OpenapiComponent])

res shouldBe Right(
OpenapiComponent(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,10 @@ case class OpenapiCodegenTask(

def makeFile(file: File): Task[File] = {
task {
val parsed = YamlParser.parseFile(IO.readLines(inputYaml).mkString("\n"))
.left.map(d => new RuntimeException(_root_.io.circe.Error.showError.show(d)))
val parsed = YamlParser
.parseFile(IO.readLines(inputYaml).mkString("\n"))
.left
.map(d => new RuntimeException(_root_.io.circe.Error.showError.show(d)))
val lines = BasicGenerator.generateObjects(parsed.toTry.get, packageName, objectName, targetScala3).linesIterator.toSeq
IO.writeLines(file, lines, IO.utf8)
file
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,15 @@ class ServerInterpreter[R, F[_], B, S](
): RequestHandler[F, R, B] = {
is match {
case Nil => RequestHandler.from { (request, ses, _) => firstNotNone(request, ses, eisAcc.reverse, Nil) }
case is => is.head match {
case ei: EndpointInterceptor[F] => callInterceptors(is.tail, ei :: eisAcc, responder)
case i: RequestInterceptor[F] =>
i(
responder,
{ ei => RequestHandler.from { (request, ses, _) => callInterceptors(is.tail, ei :: eisAcc, responder).apply(request, ses) } }
)
}
case is =>
is.head match {
case ei: EndpointInterceptor[F] => callInterceptors(is.tail, ei :: eisAcc, responder)
case i: RequestInterceptor[F] =>
i(
responder,
{ ei => RequestHandler.from { (request, ses, _) => callInterceptors(is.tail, ei :: eisAcc, responder).apply(request, ses) } }
)
}
}
}

Expand Down Expand Up @@ -64,12 +65,15 @@ class ServerInterpreter[R, F[_], B, S](
}

private val defaultSecurityFailureResponse =
ServerResponse[B](StatusCode.InternalServerError, Nil, None, None).unit
ServerResponse[B](StatusCode.InternalServerError, Nil, None, None).unit

private def endpointHandler(securityFailureResponse: => F[ServerResponse[B]], endpointInterceptors: List[EndpointInterceptor[F]]): EndpointHandler[F, B] =
endpointInterceptors.foldRight(defaultEndpointHandler(securityFailureResponse)) { case (interceptor, handler) =>
interceptor(responder(defaultSuccessStatusCode), handler)
}
private def endpointHandler(
securityFailureResponse: => F[ServerResponse[B]],
endpointInterceptors: List[EndpointInterceptor[F]]
): EndpointHandler[F, B] =
endpointInterceptors.foldRight(defaultEndpointHandler(securityFailureResponse)) { case (interceptor, handler) =>
interceptor(responder(defaultSuccessStatusCode), handler)
}

private def tryServerEndpoint[A, U, I, E, O](
request: ServerRequest,
Expand Down Expand Up @@ -117,7 +121,10 @@ class ServerInterpreter[R, F[_], B, S](
response <- securityLogicResult match {
case Left(e) =>
resultOrValueFrom.value(
endpointHandler(responder(defaultErrorStatusCode)(request, model.ValuedEndpointOutput(se.endpoint.errorOutput, e)), endpointInterceptors)
endpointHandler(
responder(defaultErrorStatusCode)(request, model.ValuedEndpointOutput(se.endpoint.errorOutput, e)),
endpointInterceptors
)
.onSecurityFailure(SecurityFailureContext(se, a, request))
.map(r => RequestResult.Response(r): RequestResult[B])
)
Expand Down Expand Up @@ -225,7 +232,8 @@ class ServerInterpreter[R, F[_], B, S](

val headers = outputValues.headers
(statusCode, outputValues.body) match {
case (StatusCode.NoContent | StatusCode.NotModified, Some(_)) => monad.error(new IllegalStateException(s"Unexpected response body when status code == $statusCode"))
case (StatusCode.NoContent | StatusCode.NotModified, Some(_)) =>
monad.error(new IllegalStateException(s"Unexpected response body when status code == $statusCode"))
case (_, Some(bodyFromHeaders)) => ServerResponse(statusCode, headers, Some(bodyFromHeaders(Headers(headers))), Some(output)).unit
case (_, None) => ServerResponse(statusCode, headers, None: Option[B], Some(output)).unit
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ package object http4s {

/** Access the context provided by an http4s middleware, such as authentication data.
*
* Interpreting endpoints which access the http4s context requires the usage of the [[Http4sServerInterpreter.toContextRoutes]]
* method. This then yields a [[org.http4s.ContextRoutes]] instance, which needs to be correctly mounted in the http4s router.
* Interpreting endpoints which access the http4s context requires the usage of the [[Http4sServerInterpreter.toContextRoutes]] method.
* This then yields a [[org.http4s.ContextRoutes]] instance, which needs to be correctly mounted in the http4s router.
*
* Note that the correct syntax for adding the context input includes `()` after the method invocation, to properly infer types and
* capture implicit parameters, e.g. `myEndpoint.contextIn[Auth]()`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class PekkoBodyListener(implicit ec: ExecutionContext) extends BodyListener[Futu
override def onComplete(body: PekkoResponseBody)(cb: Try[Unit] => Future[Unit]): Future[PekkoResponseBody] = {
body match {
case ws @ Left(_) => cb(Success(())).map(_ => ws)
case Right(e@HttpEntity.Empty) =>
case Right(e @ HttpEntity.Empty) =>
Future.successful(Right(e)).andThen { case _ => cb(Success(())) }
case Right(e: UniversalEntity) =>
Future.successful(
Expand All @@ -24,7 +24,7 @@ class PekkoBodyListener(implicit ec: ExecutionContext) extends BodyListener[Futu
Flow[ByteString].watchTermination() { case (_, f) =>
f.onComplete {
case Failure(ex) => cb(Failure(ex))
case Success(_) => cb(Success(()))
case Success(_) => cb(Success(()))
}
}
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ private[pekkohttp] class PekkoToResponseBody(implicit m: Materializer, ec: Execu
case nb: ContentType.NonBinary => HttpEntity(nb, r)
case _ => HttpEntity(ct, r.getBytes(charset))
}
case RawBodyType.ByteArrayBody => HttpEntity(ct, r)
case RawBodyType.ByteBufferBody => HttpEntity(ct, ByteString(r))
case RawBodyType.ByteArrayBody => HttpEntity(ct, r)
case RawBodyType.ByteBufferBody => HttpEntity(ct, ByteString(r))
case RawBodyType.InputStreamBody => streamToEntity(ct, contentLength, StreamConverters.fromInputStream(() => r, ChunkSize))
case RawBodyType.InputStreamRangeBody =>
val resource = r
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -773,25 +773,32 @@ class ServerBasicTests[F[_], OPTIONS, ROUTE](
testServer(
"fail when status is 204 or 304, but there's a body",
NonEmptyList.of(
route(List(
endpoint.in("no_content").out(jsonBody[Unit]).out(statusCode(StatusCode.NoContent)).serverLogicSuccess[F](_ => pureResult(())),
endpoint.in("not_modified").out(jsonBody[Unit]).out(statusCode(StatusCode.NotModified)).serverLogicSuccess[F](_ => pureResult(())),
endpoint
.in("one_of")
.in(query[String]("select_err"))
.errorOut(
sttp.tapir.oneOf[ErrorInfo](
oneOfVariant(statusCode(StatusCode.NotFound).and(jsonBody[NotFound])),
oneOfVariant(statusCode(StatusCode.NoContent).and(jsonBody[NoContentData])),
route(
List(
endpoint.in("no_content").out(jsonBody[Unit]).out(statusCode(StatusCode.NoContent)).serverLogicSuccess[F](_ => pureResult(())),
endpoint
.in("not_modified")
.out(jsonBody[Unit])
.out(statusCode(StatusCode.NotModified))
.serverLogicSuccess[F](_ => pureResult(())),
endpoint
.in("one_of")
.in(query[String]("select_err"))
.errorOut(
sttp.tapir.oneOf[ErrorInfo](
oneOfVariant(statusCode(StatusCode.NotFound).and(jsonBody[NotFound])),
oneOfVariant(statusCode(StatusCode.NoContent).and(jsonBody[NoContentData]))
)
)
)
.serverLogic[F] { selectErr =>
if (selectErr == "no_content")
pureResult[F, Either[ErrorInfo, Unit]](Left(NoContentData("error")))
else
pureResult[F, Either[ErrorInfo, Unit]](Left(NotFound("error")))
}
)))
.serverLogic[F] { selectErr =>
if (selectErr == "no_content")
pureResult[F, Either[ErrorInfo, Unit]](Left(NoContentData("error")))
else
pureResult[F, Either[ErrorInfo, Unit]](Left(NotFound("error")))
}
)
)
)
) { (backend, baseUri) =>
basicRequest.get(uri"$baseUri/no_content").send(backend).map(_.code shouldBe StatusCode.InternalServerError) >>
basicRequest.get(uri"$baseUri/not_modified").send(backend).map(_.code shouldBe StatusCode.InternalServerError) >>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ sealed trait ZioHttpResponseBody {
def contentLength: Option[Long]
}

case class ZioStreamHttpResponseBody(stream: ZStream[Any, Throwable, Byte], contentLength: Option[Long])
extends ZioHttpResponseBody
case class ZioStreamHttpResponseBody(stream: ZStream[Any, Throwable, Byte], contentLength: Option[Long]) extends ZioHttpResponseBody

case class ZioRawHttpResponseBody(bytes: Chunk[Byte], contentLength: Option[Long]) extends ZioHttpResponseBody
Original file line number Diff line number Diff line change
Expand Up @@ -54,16 +54,16 @@ case class DuplicatedMethodDefinitionError(e: AnyEndpoint, methods: List[Method]
override def toString: String = s"An endpoint ${e.show} have multiple method definitions: $methods"
}

/**
* Endpoint `e` defines outputs where status code indicates no body, but at the same time a body output is specified. For status codes 204 and 304 it's forbidden by specification.
/** Endpoint `e` defines outputs where status code indicates no body, but at the same time a body output is specified. For status codes 204
* and 304 it's forbidden by specification.
*
* Example of incorrectly defined endpoint:
*
* {{{
* endpoint.get.in("x").out(jsonBody[Unit]).out(statusCode(StatusCode.NoContent))
* }}}
*
*/
case class UnexpectedBodyError(e: AnyEndpoint, statusCode: StatusCode) extends EndpointVerificationError {
override def toString: String = s"An endpoint ${e.show} may return status code ${statusCode} with body, which is not allowed by specificiation."
override def toString: String =
s"An endpoint ${e.show} may return status code ${statusCode} with body, which is not allowed by specificiation."
}

0 comments on commit 9fd13b4

Please sign in to comment.