From 9fd13b4e4ba484ea6ffa3e2dda6930bfc971bf58 Mon Sep 17 00:00:00 2001 From: scala-steward Date: Tue, 29 Aug 2023 00:06:17 +0000 Subject: [PATCH] Reformat with scalafmt 3.7.13 Executed command: scalafmt --non-interactive --- .../StaticContentSecurePekkoServer.scala | 1 - .../PekkoServerStubInterpreterExample.scala | 1 - .../websocket/WebSocketPekkoServer.scala | 1 - .../ClassDefinitionGeneratorSpec.scala | 9 ++-- .../tapir/codegen/EndpointGeneratorSpec.scala | 36 ++++++++++------ .../codegen/models/SchemaParserSpec.scala | 6 +-- .../sttp/tapir/sbt/OpenapiCodegenTask.scala | 6 ++- .../interpreter/ServerInterpreter.scala | 38 +++++++++------- .../sttp/tapir/server/http4s/package.scala | 4 +- .../server/pekkohttp/PekkoBodyListener.scala | 4 +- .../pekkohttp/PekkoToResponseBody.scala | 4 +- .../tapir/server/tests/ServerBasicTests.scala | 43 +++++++++++-------- .../server/ziohttp/ZioHttpResponseBody.scala | 3 +- .../testing/EndpointVerificationError.scala | 8 ++-- 14 files changed, 94 insertions(+), 70 deletions(-) diff --git a/examples/src/main/scala/sttp/tapir/examples/static_content/StaticContentSecurePekkoServer.scala b/examples/src/main/scala/sttp/tapir/examples/static_content/StaticContentSecurePekkoServer.scala index fd3724a674..2b860d8d90 100644 --- a/examples/src/main/scala/sttp/tapir/examples/static_content/StaticContentSecurePekkoServer.scala +++ b/examples/src/main/scala/sttp/tapir/examples/static_content/StaticContentSecurePekkoServer.scala @@ -56,4 +56,3 @@ object StaticContentSecurePekkoServer extends App { Await.result(bindAndCheck.transformWith { r => actorSystem.terminate().transform(_ => r) }, 1.minute) } - diff --git a/examples/src/main/scala/sttp/tapir/examples/testing/PekkoServerStubInterpreterExample.scala b/examples/src/main/scala/sttp/tapir/examples/testing/PekkoServerStubInterpreterExample.scala index 93a0449de4..768e53429c 100644 --- a/examples/src/main/scala/sttp/tapir/examples/testing/PekkoServerStubInterpreterExample.scala +++ b/examples/src/main/scala/sttp/tapir/examples/testing/PekkoServerStubInterpreterExample.scala @@ -65,4 +65,3 @@ object PekkoUsersApi { def options(implicit ec: ExecutionContext): CustomiseInterceptors[Future, PekkoHttpServerOptions] = PekkoHttpServerOptions.customiseInterceptors.exceptionHandler(exceptionHandler) } - diff --git a/examples/src/main/scala/sttp/tapir/examples/websocket/WebSocketPekkoServer.scala b/examples/src/main/scala/sttp/tapir/examples/websocket/WebSocketPekkoServer.scala index cd533bf2e5..6736ff941b 100644 --- a/examples/src/main/scala/sttp/tapir/examples/websocket/WebSocketPekkoServer.scala +++ b/examples/src/main/scala/sttp/tapir/examples/websocket/WebSocketPekkoServer.scala @@ -71,4 +71,3 @@ object WebSocketPekkoServer extends App { Await.result(bindAndCheck.transformWith { r => actorSystem.terminate().transform(_ => r) }, 1.minute) } - diff --git a/openapi-codegen/core/src/test/scala/sttp/tapir/codegen/ClassDefinitionGeneratorSpec.scala b/openapi-codegen/core/src/test/scala/sttp/tapir/codegen/ClassDefinitionGeneratorSpec.scala index af664bb813..febaba5ed7 100644 --- a/openapi-codegen/core/src/test/scala/sttp/tapir/codegen/ClassDefinitionGeneratorSpec.scala +++ b/openapi-codegen/core/src/test/scala/sttp/tapir/codegen/ClassDefinitionGeneratorSpec.scala @@ -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 + ) ) ) ) @@ -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) } diff --git a/openapi-codegen/core/src/test/scala/sttp/tapir/codegen/EndpointGeneratorSpec.scala b/openapi-codegen/core/src/test/scala/sttp/tapir/codegen/EndpointGeneratorSpec.scala index 897f68c238..9f9f4f592f 100644 --- a/openapi-codegen/core/src/test/scala/sttp/tapir/codegen/EndpointGeneratorSpec.scala +++ b/openapi-codegen/core/src/test/scala/sttp/tapir/codegen/EndpointGeneratorSpec.scala @@ -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 { @@ -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 () } } diff --git a/openapi-codegen/core/src/test/scala/sttp/tapir/codegen/models/SchemaParserSpec.scala b/openapi-codegen/core/src/test/scala/sttp/tapir/codegen/models/SchemaParserSpec.scala index a535b3f9ac..49c56d04e1 100644 --- a/openapi-codegen/core/src/test/scala/sttp/tapir/codegen/models/SchemaParserSpec.scala +++ b/openapi-codegen/core/src/test/scala/sttp/tapir/codegen/models/SchemaParserSpec.scala @@ -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( diff --git a/openapi-codegen/sbt-plugin/src/main/scala/sttp/tapir/sbt/OpenapiCodegenTask.scala b/openapi-codegen/sbt-plugin/src/main/scala/sttp/tapir/sbt/OpenapiCodegenTask.scala index c620d3d442..2817107974 100644 --- a/openapi-codegen/sbt-plugin/src/main/scala/sttp/tapir/sbt/OpenapiCodegenTask.scala +++ b/openapi-codegen/sbt-plugin/src/main/scala/sttp/tapir/sbt/OpenapiCodegenTask.scala @@ -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 diff --git a/server/core/src/main/scala/sttp/tapir/server/interpreter/ServerInterpreter.scala b/server/core/src/main/scala/sttp/tapir/server/interpreter/ServerInterpreter.scala index 38142c09e1..629bc5a16b 100644 --- a/server/core/src/main/scala/sttp/tapir/server/interpreter/ServerInterpreter.scala +++ b/server/core/src/main/scala/sttp/tapir/server/interpreter/ServerInterpreter.scala @@ -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) } } + ) + } } } @@ -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, @@ -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]) ) @@ -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 } diff --git a/server/http4s-server/src/main/scala/sttp/tapir/server/http4s/package.scala b/server/http4s-server/src/main/scala/sttp/tapir/server/http4s/package.scala index 3820b7ca51..3df5eac87e 100644 --- a/server/http4s-server/src/main/scala/sttp/tapir/server/http4s/package.scala +++ b/server/http4s-server/src/main/scala/sttp/tapir/server/http4s/package.scala @@ -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]()`. diff --git a/server/pekko-http-server/src/main/scala/sttp/tapir/server/pekkohttp/PekkoBodyListener.scala b/server/pekko-http-server/src/main/scala/sttp/tapir/server/pekkohttp/PekkoBodyListener.scala index 7e18297845..73b1606856 100644 --- a/server/pekko-http-server/src/main/scala/sttp/tapir/server/pekkohttp/PekkoBodyListener.scala +++ b/server/pekko-http-server/src/main/scala/sttp/tapir/server/pekkohttp/PekkoBodyListener.scala @@ -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( @@ -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(())) } } ) diff --git a/server/pekko-http-server/src/main/scala/sttp/tapir/server/pekkohttp/PekkoToResponseBody.scala b/server/pekko-http-server/src/main/scala/sttp/tapir/server/pekkohttp/PekkoToResponseBody.scala index faa8c1b32f..c355140ffc 100644 --- a/server/pekko-http-server/src/main/scala/sttp/tapir/server/pekkohttp/PekkoToResponseBody.scala +++ b/server/pekko-http-server/src/main/scala/sttp/tapir/server/pekkohttp/PekkoToResponseBody.scala @@ -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 diff --git a/server/tests/src/main/scala/sttp/tapir/server/tests/ServerBasicTests.scala b/server/tests/src/main/scala/sttp/tapir/server/tests/ServerBasicTests.scala index a5f501eb27..ecda573c9c 100644 --- a/server/tests/src/main/scala/sttp/tapir/server/tests/ServerBasicTests.scala +++ b/server/tests/src/main/scala/sttp/tapir/server/tests/ServerBasicTests.scala @@ -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) >> diff --git a/server/zio-http-server/src/main/scala/sttp/tapir/server/ziohttp/ZioHttpResponseBody.scala b/server/zio-http-server/src/main/scala/sttp/tapir/server/ziohttp/ZioHttpResponseBody.scala index 8f2b9251c9..d673cac40e 100644 --- a/server/zio-http-server/src/main/scala/sttp/tapir/server/ziohttp/ZioHttpResponseBody.scala +++ b/server/zio-http-server/src/main/scala/sttp/tapir/server/ziohttp/ZioHttpResponseBody.scala @@ -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 diff --git a/testing/src/main/scala/sttp/tapir/testing/EndpointVerificationError.scala b/testing/src/main/scala/sttp/tapir/testing/EndpointVerificationError.scala index 1065ba118e..58774446e8 100644 --- a/testing/src/main/scala/sttp/tapir/testing/EndpointVerificationError.scala +++ b/testing/src/main/scala/sttp/tapir/testing/EndpointVerificationError.scala @@ -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." }