Skip to content

Commit

Permalink
Merge pull request #2693 from softwaremill/update/scalafmt-core-3.7.1
Browse files Browse the repository at this point in the history
Update scalafmt-core to 3.7.1
  • Loading branch information
adamw authored Jan 27, 2023
2 parents 978fd43 + e8c0090 commit 57018a7
Show file tree
Hide file tree
Showing 23 changed files with 109 additions and 83 deletions.
3 changes: 3 additions & 0 deletions .git-blame-ignore-revs
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,6 @@ b2c641dce625096839305c65db550ac11c1be0e1

# Scala Steward: Reformat with scalafmt 3.6.1
9ed1c7512fcebb3d74089c275f9a66f9821a0060

# Scala Steward: Reformat with scalafmt 3.7.1
5629d39bd05c54bc957996ca4bf46c4bab1cbd67
2 changes: 1 addition & 1 deletion .scalafmt.conf
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
version = 3.6.1
version = 3.7.1
maxColumn = 140
runner.dialect = scala3
fileOverride {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
package sttp.tapir

trait CodecExtensions2
trait CodecExtensions2
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,11 @@ private[tapir] object ValidatorEnumerationMacro {
val enumNameComponents = weakTypeT.toString.split("\\.").dropRight(1)
val enumeration = enumNameComponents.toList match {
case head :: tail => tail.foldLeft[Tree](Ident(TermName(head))) { case (tree, nextName) => Select(tree, TermName(nextName)) }
case Nil => c.abort(c.enclosingPosition, s"Invalid enum name: ${weakTypeT.toString}")
case Nil => c.abort(c.enclosingPosition, s"Invalid enum name: ${weakTypeT.toString}")
}

q"_root_.sttp.tapir.Validator.enumeration($enumeration.values.toList, v => Option(v), Some(sttp.tapir.Schema.SName(${
enumNameComponents
.mkString(".")
})))"
q"_root_.sttp.tapir.Validator.enumeration($enumeration.values.toList, v => Option(v), Some(sttp.tapir.Schema.SName(${enumNameComponents
.mkString(".")})))"
}
}
}
2 changes: 0 additions & 2 deletions core/src/main/scala-2/sttp/tapir/macros/SchemaMacros.scala
Original file line number Diff line number Diff line change
Expand Up @@ -83,5 +83,3 @@ trait SchemaCompanionMacros extends SchemaMagnoliaDerivation {
*/
implicit def derivedEnumerationValue[T <: scala.Enumeration#Value]: Schema[T] = macro SchemaEnumerationMacro.derivedEnumerationValue[T]
}


1 change: 1 addition & 0 deletions core/src/main/scala-3-2.13+/sttp/tapir/model/package.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package sttp.tapir

package object model {

/** Used to lookup codecs which split/combine values using a comma. */
type CommaSeparated[T] = Delimited[",", T]
}
6 changes: 3 additions & 3 deletions core/src/main/scala-3/sttp/tapir/macros/SchemaMacros.scala
Original file line number Diff line number Diff line change
Expand Up @@ -254,11 +254,11 @@ private[tapir] object SchemaCompanionMacros {
TypeIdent(subclass).tpe.asType match {
case '[f] => {
Expr.summon[Schema[f]] match {
case Some (subSchema) => '{${Expr (subclass.name)} -> Schema.wrapWithSingleFieldProduct (${subSchema}) ($conf)}
case Some(subSchema) => '{ ${ Expr(subclass.name) } -> Schema.wrapWithSingleFieldProduct(${ subSchema })($conf) }
case None => {
val typeName = TypeRepr.of[f].typeSymbol.name
report.errorAndAbort (s"Cannot summon schema for `${typeName}`. Make sure schema derivation is properly configured.")
}
report.errorAndAbort(s"Cannot summon schema for `${typeName}`. Make sure schema derivation is properly configured.")
}
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions core/src/main/scala/sttp/tapir/Codec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -569,9 +569,9 @@ object Codec extends CodecExtensions with CodecExtensions2 with FormCodecMacros
}
}(_.toString)

implicit val contentRange: Codec[String, ContentRange, CodecFormat.TextPlain] = Codec.string.mapDecode { v =>
DecodeResult.fromEitherString(v, ContentRange.parse(v))
}(_.toString)
implicit val contentRange: Codec[String, ContentRange, CodecFormat.TextPlain] = Codec.string.mapDecode { v =>
DecodeResult.fromEitherString(v, ContentRange.parse(v))
}(_.toString)

implicit val cacheDirective: Codec[String, List[CacheDirective], CodecFormat.TextPlain] = Codec.string.mapDecode { v =>
@tailrec
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,6 @@ class EndpointToProtobufMessage {
}
List(ProtobufProductMessage(toMessageName(name), protoFields))
case SCoproduct(subtypes, discriminator) =>

List(
ProtobufCoproductMessage(
toMessageName(name),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ sealed trait ProtobufMessage {
}

case class ProtobufProductMessage(name: MessageName, fields: Iterable[ProtobufMessageField]) extends ProtobufMessage
case class ProtobufCoproductMessage(name: MessageName, alternatives: Iterable[ProtobufMessageField]) extends ProtobufMessage
case class ProtobufCoproductMessage(name: MessageName, alternatives: Iterable[ProtobufMessageField]) extends ProtobufMessage
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ class ProtoRendererTest extends AnyFlatSpec with ProtobufMatchers {
"Format",
List(
ProtobufMessageField(ProtobufMessageRef(SName("Epub")), "epub", None),
ProtobufMessageField(ProtobufMessageRef(SName("Paper")), "paper", None),
ProtobufMessageField(ProtobufMessageRef(SName("Paper")), "paper", None)
)
),
ProtobufProductMessage(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ trait TapirCodecEnumeratum {
implicit def schemaForEnumEntry[E <: EnumEntry](implicit annotations: SchemaAnnotations[E], `enum`: Enum[E]): Schema[E] =
annotations.enrich(Schema[E](SchemaType.SString()).validate(validatorEnumEntry))

def plainCodecEnumEntryUsing[E <: EnumEntry](f: String => Option[E])(implicit `enum`: Enum[E]): Codec[String, E, CodecFormat.TextPlain] = {
def plainCodecEnumEntryUsing[E <: EnumEntry](
f: String => Option[E]
)(implicit `enum`: Enum[E]): Codec[String, E, CodecFormat.TextPlain] = {
val validator = validatorEnumEntry
Codec.string
.mapDecode { s =>
Expand Down Expand Up @@ -47,7 +49,10 @@ trait TapirCodecEnumeratum {
implicit def schemaForShortEnumEntry[E <: ShortEnumEntry](implicit annotations: SchemaAnnotations[E], `enum`: ShortEnum[E]): Schema[E] =
annotations.enrich(Schema[E](SchemaType.SInteger()).validate(validatorValueEnumEntry[Short, E]))

implicit def schemaForStringEnumEntry[E <: StringEnumEntry](implicit annotations: SchemaAnnotations[E], `enum`: StringEnum[E]): Schema[E] =
implicit def schemaForStringEnumEntry[E <: StringEnumEntry](implicit
annotations: SchemaAnnotations[E],
`enum`: StringEnum[E]
): Schema[E] =
annotations.enrich(Schema[E](SchemaType.SString()).validate(validatorValueEnumEntry[String, E]))

implicit def schemaForByteEnumEntry[E <: ByteEnumEntry](implicit annotations: SchemaAnnotations[E], `enum`: ByteEnum[E]): Schema[E] =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,9 @@ class TapirCodecEnumeratumTest extends AnyFlatSpec with Matchers {
}
}

private def testValueEnumPlainCodec[T, EE <: ValueEnumEntry[T], E <: ValueEnum[T, EE]](codec: PlainCodec[EE])(implicit `enum`: E): Unit = {
private def testValueEnumPlainCodec[T, EE <: ValueEnumEntry[T], E <: ValueEnum[T, EE]](
codec: PlainCodec[EE]
)(implicit `enum`: E): Unit = {
`enum`.values.foreach { v =>
codec.encode(v) shouldBe v.value.toString
codec.decode(v.value.toString) shouldBe DecodeResult.Value(v)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,14 @@ object ZioMetrics {
Boundaries.fromChunk(Chunk(.005, .01, .025, .05, .075, .1, .25, .5, .75, 1, 2.5, 5, 7.5, 10, 15, 30, 45, 60))

/** Using the default namespace and labels, registers the following metrics:
*
* - `tapir_request_active{path, method}` (gauge)
* - `tapir_request_total{path, method, status}` (counter)
* - `tapir_request_duration_seconds{path, method, status, phase}` (histogram)
*
* Status is by default the status code class (1xx, 2xx, etc.), and phase can be either `headers` or `body` - request duration is
* measured separately up to the point where the headers are determined, and then once again when the whole response body is complete.
*/
*
* - `tapir_request_active{path, method}` (gauge)
* - `tapir_request_total{path, method, status}` (counter)
* - `tapir_request_duration_seconds{path, method, status, phase}` (histogram)
*
* Status is by default the status code class (1xx, 2xx, etc.), and phase can be either `headers` or `body` - request duration is
* measured separately up to the point where the headers are determined, and then once again when the whole response body is complete.
*/
def default[F[_]](namespace: String = DefaultNamespace, labels: MetricLabels = MetricLabels.Default): ZioMetrics[F] = ZioMetrics(
namespace,
List(
Expand All @@ -75,7 +75,6 @@ object ZioMetrics {
def getRequestDurationHistogram(namespace: String): zio.metrics.Metric.Histogram[Double] =
zio.metrics.Metric.histogram(s"${namespace}_request_duration_seconds", DurationBoundaries)


/** ZIO Unsafe Run Wrapper */
private def unsafeRun[T](task: Task[T]): T = Unsafe.unsafe { implicit u =>
runtime.unsafe.run(task.orDie).getOrThrowFiberFailure()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,18 @@ object ZioMetricsTest extends ZIOSpecDefault {
)

// when
val active: Counter[Long] = ZioMetrics.getActiveRequestCounter("tapir").tagged(
Set(MetricLabel("path", "/person"), MetricLabel("method", "GET"))
)
val active: Counter[Long] = ZioMetrics
.getActiveRequestCounter("tapir")
.tagged(
Set(MetricLabel("path", "/person"), MetricLabel("method", "GET"))
)

for {
_ <- ZIO.succeed({
interpreter.apply(PersonsApi.request("Jacob"))
}).fork
_ <- ZIO
.succeed({
interpreter.apply(PersonsApi.request("Jacob"))
})
.fork
_ <- ZIO.succeed(Thread.sleep(100))
state <- active.value
_ <- ZIO.succeed(Thread.sleep(150))
Expand All @@ -63,13 +67,17 @@ object ZioMetricsTest extends ZIOSpecDefault {
)

// when
val counter: Counter[Long] = ZioMetrics.getRequestsTotalCounter("tapir").tagged(
Set(MetricLabel("path", "/person"), MetricLabel("method", "GET"),MetricLabel("status", "2xx"))
)
val counter: Counter[Long] = ZioMetrics
.getRequestsTotalCounter("tapir")
.tagged(
Set(MetricLabel("path", "/person"), MetricLabel("method", "GET"), MetricLabel("status", "2xx"))
)

val missedCounter: Counter[Long] = ZioMetrics.getRequestsTotalCounter("tapir").tagged(
Set(MetricLabel("path", "/person"), MetricLabel("method", "GET"), MetricLabel("status", "4xx"))
)
val missedCounter: Counter[Long] = ZioMetrics
.getRequestsTotalCounter("tapir")
.tagged(
Set(MetricLabel("path", "/person"), MetricLabel("method", "GET"), MetricLabel("status", "4xx"))
)
for {
_ <- ZIO.succeed({
interpreter.apply(PersonsApi.request("Jacob"))
Expand All @@ -80,10 +88,10 @@ object ZioMetricsTest extends ZIOSpecDefault {
})
state <- counter.value
stateMissed <- missedCounter.value
} yield assertTrue(state == MetricState.Counter(3D)) &&
assertTrue(stateMissed == MetricState.Counter(2D))
} yield assertTrue(state == MetricState.Counter(3d)) &&
assertTrue(stateMissed == MetricState.Counter(2d))
},
test ("can collect requests duration") {
test("can collect requests duration") {
val serverEp = PersonsApi { name =>
PersonsApi.defaultLogic(name)
}.serverEp
Expand All @@ -98,9 +106,11 @@ object ZioMetricsTest extends ZIOSpecDefault {
)

// when
val histogram: Metric[MetricKeyType.Histogram, Double, MetricState.Histogram] = ZioMetrics.getRequestDurationHistogram("tapir").tagged(
Set(MetricLabel("path", "/person"), MetricLabel("method", "GET"), MetricLabel("status", "2xx"), MetricLabel("phase", "headers"))
)
val histogram: Metric[MetricKeyType.Histogram, Double, MetricState.Histogram] = ZioMetrics
.getRequestDurationHistogram("tapir")
.tagged(
Set(MetricLabel("path", "/person"), MetricLabel("method", "GET"), MetricLabel("status", "2xx"), MetricLabel("phase", "headers"))
)

for {
_ <- ZIO.succeed({
Expand All @@ -109,8 +119,8 @@ object ZioMetricsTest extends ZIOSpecDefault {
state <- histogram.value
} yield assertTrue(state.buckets.exists(_._2 > 0L)) &&
assertTrue(state.count == 1L) &&
assertTrue(state.min > 0D) &&
assertTrue(state.max > 0D)
assertTrue(state.min > 0d) &&
assertTrue(state.max > 0d)
}
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,34 +26,35 @@ trait FinatraServerInterpreter extends Logging {
finatraServerOptions.deleteFile
)(FutureMonadError, new FinatraBodyListener[Future]())

val handler = { request: Request =>
val serverRequest = new FinatraServerRequest(request)
val handler = {
request: Request =>
val serverRequest = new FinatraServerRequest(request)

serverInterpreter(serverRequest).map {
case RequestResult.Failure(_) => Response(Status.NotFound)
case RequestResult.Response(response) =>
val status = Status(response.code.code)
val responseWithContent = response.body match {
case Some(fContent) =>
val response = fContent match {
case FinatraContentBuf(buf) =>
val r = Response(Version.Http11, status)
r.content = buf
r
case FinatraContentReader(reader) => Response(Version.Http11, status, reader)
}
response
case None =>
Response(Version.Http11, status)
}
serverInterpreter(serverRequest).map {
case RequestResult.Failure(_) => Response(Status.NotFound)
case RequestResult.Response(response) =>
val status = Status(response.code.code)
val responseWithContent = response.body match {
case Some(fContent) =>
val response = fContent match {
case FinatraContentBuf(buf) =>
val r = Response(Version.Http11, status)
r.content = buf
r
case FinatraContentReader(reader) => Response(Version.Http11, status, reader)
}
response
case None =>
Response(Version.Http11, status)
}

response.headers.foreach(header => responseWithContent.headerMap.add(header.name, header.value))
response.headers.foreach(header => responseWithContent.headerMap.add(header.name, header.value))

// If there's a content-type header in headers, override the content-type.
response.contentType.foreach(ct => responseWithContent.contentType = ct)
// If there's a content-type header in headers, override the content-type.
response.contentType.foreach(ct => responseWithContent.contentType = ct)

responseWithContent
}
responseWithContent
}
}

FinatraRoute(handler, httpMethod(se.endpoint), path(se.securityInput.and(se.input)))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ sealed trait NettyResponseContent {
def channelPromise: ChannelPromise
}

object NettyResponseContent{
object NettyResponseContent {
final case class ByteBufNettyResponseContent(channelPromise: ChannelPromise, byteBuf: ByteBuf) extends NettyResponseContent
final case class ChunkedStreamNettyResponseContent(channelPromise: ChannelPromise, chunkedStream: ChunkedStream) extends NettyResponseContent
final case class ChunkedStreamNettyResponseContent(channelPromise: ChannelPromise, chunkedStream: ChunkedStream)
extends NettyResponseContent
final case class ChunkedFileNettyResponseContent(channelPromise: ChannelPromise, chunkedFile: ChunkedFile) extends NettyResponseContent
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@ import sttp.model.HasHeaders
import sttp.tapir.capabilities.NoStreams
import sttp.tapir.server.interpreter.ToResponseBody
import sttp.tapir.server.netty.NettyResponse
import sttp.tapir.server.netty.NettyResponseContent.{ByteBufNettyResponseContent, ChunkedFileNettyResponseContent, ChunkedStreamNettyResponseContent}
import sttp.tapir.server.netty.NettyResponseContent.{
ByteBufNettyResponseContent,
ChunkedFileNettyResponseContent,
ChunkedStreamNettyResponseContent
}
import sttp.tapir.{CodecFormat, FileRange, RawBodyType, WebSocketBodyOutput}

import java.io.{InputStream, RandomAccessFile}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,5 +57,4 @@ object NettyZioServerOptions {
private def debugLog[R](msg: String, exOpt: Option[Throwable]): RIO[R, Unit] =
ZIO.succeed(NettyDefaults.debugLog(log, msg, exOpt))


}
Original file line number Diff line number Diff line change
Expand Up @@ -57,5 +57,4 @@ object NettyZioServerOptions {
private def debugLog[R](msg: String, exOpt: Option[Throwable]): RIO[R, Unit] =
ZIO.succeed(NettyDefaults.debugLog(log, msg, exOpt))


}
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ import sttp.tapir.tests.Port

import scala.concurrent.Future

class VertxTestServerInterpreter(vertx: Vertx) extends TestServerInterpreter[Future, VertxStreams, VertxFutureServerOptions, Router => Route] {
class VertxTestServerInterpreter(vertx: Vertx)
extends TestServerInterpreter[Future, VertxStreams, VertxFutureServerOptions, Router => Route] {
import VertxTestServerInterpreter._

override def route(es: List[ServerEndpoint[VertxStreams, Future]], interceptors: Interceptors): Router => Route = { router =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ import scala.scalajs.js.JSConverters._

object AwsJsRouteHandler {

private def toJsRoute[F[_]](route: Route[F])(implicit monadError: MonadError[F]): JsRoute[F] = { awsJsRequest: AwsJsRequest =>
monadError.map(route.apply(AwsJsRequest.toAwsRequest(awsJsRequest)))(AwsJsResponse.fromAwsResponse)
private def toJsRoute[F[_]](route: Route[F])(implicit monadError: MonadError[F]): JsRoute[F] = {
awsJsRequest: AwsJsRequest =>
monadError.map(route.apply(AwsJsRequest.toAwsRequest(awsJsRequest)))(AwsJsResponse.fromAwsResponse)
}

def futureHandler(event: AwsJsRequest, route: Route[Future])(implicit ec: ExecutionContext): scala.scalajs.js.Promise[AwsJsResponse] = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,12 @@ class VerifySamTemplateTest extends AnyFunSuite with Matchers {
)
)
),
source = CodeSource(runtime = "java11", codeUri = "/somewhere/pet-api.jar", "pet.api.Handler::handleRequest", environment = Map("myEnv" -> "foo", "otherEnv" -> "bar")),
source = CodeSource(
runtime = "java11",
codeUri = "/somewhere/pet-api.jar",
"pet.api.Handler::handleRequest",
environment = Map("myEnv" -> "foo", "otherEnv" -> "bar")
),
memorySize = 1024
)

Expand Down

0 comments on commit 57018a7

Please sign in to comment.