Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Changes the default Endpoint.outStream[X] encoding to produce a JSON array #3122

Merged
merged 15 commits into from
Sep 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ val _ = sys.props += ("ZIOHttpLogLevel" -> Debug.ZIOHttpLogLevel)
ThisBuild / githubWorkflowEnv += ("JDK_JAVA_OPTIONS" -> "-Xms4G -Xmx8G -XX:+UseG1GC -Xss10M -XX:ReservedCodeCacheSize=1G -XX:NonProfiledCodeHeapSize=512m -Dfile.encoding=UTF-8")
ThisBuild / githubWorkflowEnv += ("SBT_OPTS" -> "-Xms4G -Xmx8G -XX:+UseG1GC -Xss10M -XX:ReservedCodeCacheSize=1G -XX:NonProfiledCodeHeapSize=512m -Dfile.encoding=UTF-8")

ThisBuild / resolvers ++= Resolver.sonatypeOssRepos("snapshots")

ThisBuild / githubWorkflowJavaVersions := Seq(
JavaSpec.graalvm(Graalvm.Distribution("graalvm"), "17"),
JavaSpec.graalvm(Graalvm.Distribution("graalvm"), "21"),
Expand Down
2 changes: 1 addition & 1 deletion project/Dependencies.scala
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ object Dependencies {
val ZioCliVersion = "0.5.0"
val ZioJsonVersion = "0.7.1"
val ZioParserVersion = "0.1.10"
val ZioSchemaVersion = "1.4.1"
val ZioSchemaVersion = "1.5.0"
val SttpVersion = "3.3.18"
val ZioConfigVersion = "4.0.2"

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -460,7 +460,7 @@ final case class EndpointGen(config: Config) {

val (outImports: Iterable[List[Code.Import]], outCodes: Iterable[Code.OutCode]) =
// TODO: ignore default for now. Not sure how to handle it
op.responses.collect {
op.responses.toSeq.collect {
case (OpenAPI.StatusOrDefault.StatusValue(status), OpenAPI.ReferenceOr.Reference(ResponseRef(key), _, _)) =>
val response = resolveResponseRef(openAPI, key)
val (imports, code) =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,7 @@ object CodeGen {
case "www-authenticate" => "HeaderCodec.wwwAuthenticate"
case "x-frame-options" => "HeaderCodec.xFrameOptions"
case "x-requested-with" => "HeaderCodec.xRequestedWith"
case name => s"HeaderCodec.name[String]($name)"
case name => s"""HeaderCodec.name[String]("$name")"""
}
s""".header($headerSelector)"""
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ object Users {
val get = Endpoint(Method.GET / "api" / "v1" / "users")
.header(HeaderCodec.accept)
.header(HeaderCodec.contentType)
.header(HeaderCodec.name[String]("token"))
.in[Unit]

}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package zio.http.gen.scala
import java.nio.file._

import scala.annotation.nowarn
import scala.collection.immutable.ListMap
import scala.jdk.CollectionConverters._
import scala.meta._
import scala.meta.parsers._
Expand Down Expand Up @@ -151,7 +152,10 @@ object CodeGenSpec extends ZIOSpecDefault {
},
test("Endpoint with headers") {
val endpoint =
Endpoint(Method.GET / "api" / "v1" / "users").header(HeaderCodec.accept).header(HeaderCodec.contentType)
Endpoint(Method.GET / "api" / "v1" / "users")
.header(HeaderCodec.accept)
.header(HeaderCodec.contentType)
.header(HeaderCodec.name[String]("Token"))
val openAPI = OpenAPIGen.fromEndpoints(endpoint)

codeGenFromOpenAPI(openAPI) { testDir =>
Expand Down Expand Up @@ -972,5 +976,72 @@ object CodeGenSpec extends ZIOSpecDefault {
}
}
} @@ TestAspect.exceptScala3,
test("Generate all responses") {
val oapi =
OpenAPI(
openapi = "3.0.0",
info = OpenAPI.Info(
title = "XXX",
description = None,
termsOfService = None,
contact = None,
license = None,
version = "1.0.0",
),
paths = ListMap(
OpenAPI.Path
.fromString(name = "/api/a/b")
.map { path =>
path -> OpenAPI.PathItem(
ref = None,
summary = None,
description = None,
get = None,
put = None,
post = Some(
OpenAPI.Operation(
summary = None,
description = None,
externalDocs = None,
operationId = None,
requestBody = None,
responses = Map(
OpenAPI.StatusOrDefault.StatusValue(status = Status.Ok) ->
OpenAPI.ReferenceOr.Or(value = OpenAPI.Response()),
OpenAPI.StatusOrDefault.StatusValue(Status.BadRequest) ->
OpenAPI.ReferenceOr.Or(OpenAPI.Response()),
OpenAPI.StatusOrDefault.StatusValue(Status.Unauthorized) ->
OpenAPI.ReferenceOr.Or(OpenAPI.Response()),
),
),
),
delete = None,
options = None,
head = None,
patch = None,
trace = None,
)
}
.toSeq: _*,
),
components = None,
externalDocs = None,
)

val maybeEndpointCode =
EndpointGen
.fromOpenAPI(oapi, Config.default)
.files
.flatMap(_.objects)
.flatMap(_.endpoints)
.collectFirst {
case (field, code) if field.name == "post" => code
}

assertTrue(
maybeEndpointCode.is(_.some).outCodes.length == 1 &&
maybeEndpointCode.is(_.some).errorsCode.length == 2,
)
},
) @@ java11OrNewer @@ flaky @@ blocking // Downloading scalafmt on CI is flaky
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ private[zio] final case class ServerInboundHandler(

implicit private val unsafe: Unsafe = Unsafe.unsafe

private var routes: Routes[Any, Response] = _
private var runtime: NettyRuntime = _
private var handler: Handler[Any, Nothing, Request, Response] = _
private var runtime: NettyRuntime = _

val inFlightRequests: LongAdder = new LongAdder()
private val readClientCert = config.sslConfig.exists(_.includeClientCert)
Expand All @@ -58,7 +58,7 @@ private[zio] final case class ServerInboundHandler(
def refreshApp(): Unit = {
val pair = appRef.get()

this.routes = pair._1
this.handler = pair._1.toHandler
this.runtime = new NettyRuntime(pair._2)
}

Expand Down Expand Up @@ -88,7 +88,7 @@ private[zio] final case class ServerInboundHandler(
releaseRequest()
} else {
val req = makeZioRequest(ctx, jReq)
val exit = routes(req)
val exit = handler(req)
if (attemptImmediateWrite(ctx, req.method, exit)) {
releaseRequest()
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@ object BodySchemaOpsSpec extends ZIOHttpSpec {
},
test("Body.fromStream") {
val body = Body.fromStream(persons)
val expected = """{"name":"John","age":42}{"name":"Jane","age":43}"""
val expected =
"""{"name":"John","age":42}
|{"name":"Jane","age":43}""".stripMargin
body.asString.map(s => assertTrue(s == expected))
},
test("Body#to") {
Expand Down
2 changes: 1 addition & 1 deletion zio-http/jvm/src/test/scala/zio/http/ClientSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ object ClientSpec extends RoutesRunnableSpec {
val url = URL.decode("https://test.com").toOption.get
val resp = ZClient.batched(Request.get(url)).timeout(500.millis)
assertZIO(resp)(isNone)
} @@ timeout(5.seconds) @@ flaky(20),
} @@ timeout(5.seconds) @@ flaky(20) @@ TestAspect.ignore, // annoying in CI
test("authorization header without scheme") {
val app =
Handler
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,43 @@ object RoundtripSpec extends ZIOHttpSpec {
(stream: ZStream[Any, Nothing, Byte]) => stream.runCount.map(c => assert(c)(equalTo(1024L * 1024L))),
)
},
test("string stream output") {
val api = Endpoint(GET / "download").query(HttpCodec.query[Int]("count")).outStream[String]
val route = api.implementHandler {
Handler.fromFunctionZIO { count =>
ZIO.succeed(ZStream.fromIterable((0 until count).map(_.toString)))
}
}

testEndpointZIO(
api,
Routes(route),
1024 * 1024,
(stream: ZStream[Any, Nothing, String]) =>
stream.zipWithIndex
.runFold((true, 0)) { case ((allOk, count), (str, idx)) =>
(allOk && str == idx.toString, count + 1)
}
.map { case (allOk, c) =>
assertTrue(allOk && c == 1024 * 1024)
},
)
},
test("string output") {
val api = Endpoint(GET / "download").query(HttpCodec.query[String]("param")).out[String]
val route = api.implementHandler {
Handler.fromFunctionZIO { param =>
ZIO.succeed(param)
}
}

testEndpointZIO(
api,
Routes(route),
"test",
(str: String) => assertTrue(str == "test"),
)
},
test("multi-part input") {
val api = Endpoint(POST / "test")
.in[String]("name")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import zio.schema.{DeriveSchema, Schema}
import zio.http.Method.{GET, POST}
import zio.http._
import zio.http.codec.PathCodec.string
import zio.http.codec.{ContentCodec, Doc, HttpCodec, HttpContentCodec, QueryCodec}
import zio.http.codec.{ContentCodec, Doc, HttpCodec}
import zio.http.endpoint._

object OpenAPIGenSpec extends ZIOSpecDefault {
Expand Down Expand Up @@ -2854,6 +2854,119 @@ object OpenAPIGenSpec extends ZIOSpecDefault {
|""".stripMargin
assertTrue(json == toJsonAst(expectedJson))
},
test("Stream schema") {
val endpoint = Endpoint(RoutePattern.POST / "folder")
.outStream[Int]
val openApi = OpenAPIGen.fromEndpoints(endpoint)
val json = toJsonAst(openApi)
val expectedJson =
"""
|{
| "openapi" : "3.1.0",
| "info" : {
| "title" : "",
| "version" : ""
| },
| "paths" : {
| "/folder" : {
| "post" : {
| "responses" : {
| "200" :
| {
| "content" : {
| "application/json" : {
| "schema" :
| {
| "type" :
| "array",
| "items" : {
| "type" :
| "integer",
| "format" : "int32"
| }
| }
| }
| }
| }
| }
| }
| }
| },
| "components" : {
|
| }
|}
|""".stripMargin
assertTrue(json == toJsonAst(expectedJson))
},
test("Stream schema multipart") {
val endpoint = Endpoint(RoutePattern.POST / "folder")
.outCodec(
HttpCodec.contentStream[String]("strings") ++
HttpCodec.contentStream[Int]("ints"),
)
val openApi = OpenAPIGen.fromEndpoints(endpoint)
val json = toJsonAst(openApi)
val expectedJson =
"""
|{
| "openapi" : "3.1.0",
| "info" : {
| "title" : "",
| "version" : ""
| },
| "paths" : {
| "/folder" : {
| "post" : {
| "responses" : {
| "default" :
| {
| "content" : {
| "multipart/form-data" : {
| "schema" :
| {
| "type" :
| "object",
| "properties" : {
| "strings" : {
| "type" :
| "array",
| "items" : {
| "type" :
| "string"
| }
| },
| "ints" : {
| "type" :
| "array",
| "items" : {
| "type" :
| "integer",
| "format" : "int32"
| }
| }
| },
| "additionalProperties" :
| false,
| "required" : [
| "strings",
| "ints"
| ]
| }
| }
| }
| }
| }
| }
| }
| },
| "components" : {
|
| }
|}
|""".stripMargin
assertTrue(json == toJsonAst(expectedJson))
},
test("Lazy schema") {
val endpoint = Endpoint(RoutePattern.POST / "lazy")
.in[Lazy.A]
Expand Down
15 changes: 7 additions & 8 deletions zio-http/shared/src/main/scala/zio/http/RoutePattern.scala
Original file line number Diff line number Diff line change
Expand Up @@ -172,16 +172,15 @@ object RoutePattern {
tree.add(p, v)
}

private val wildcardsTree = roots.getOrElse(Method.ANY, null)

def get(method: Method, path: Path): Chunk[A] = {
val wildcards = roots.get(Method.ANY) match {
case None => Chunk.empty
case Some(value) => value.get(path)
val forMethod = roots.getOrElse(method, null) match {
case null => Chunk.empty
case value => value.get(path)
}

(roots.get(method) match {
case None => Chunk.empty
case Some(value) => value.get(path)
}) ++ wildcards
if (wildcardsTree eq null) forMethod
else forMethod ++ wildcardsTree.get(path)
}

def map[B](f: A => B): Tree[B] =
Expand Down
Loading
Loading