Skip to content

Commit

Permalink
Format code before release
Browse files Browse the repository at this point in the history
  • Loading branch information
mathieuancelin committed Jul 8, 2022
1 parent d371bcb commit 1990864
Show file tree
Hide file tree
Showing 34 changed files with 2,785 additions and 6,641 deletions.
1,480 changes: 39 additions & 1,441 deletions manual/src/main/paradox/code/openapi.json

Large diffs are not rendered by default.

258 changes: 144 additions & 114 deletions otoroshi/app/cluster/cluster.scala

Large diffs are not rendered by default.

114 changes: 55 additions & 59 deletions otoroshi/app/controllers/BackOfficeController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -46,19 +46,19 @@ import scala.concurrent.{ExecutionContext, Future}
import scala.util.Try

case class ServiceLike(entity: EntityLocationSupport, groups: Seq[String]) extends EntityLocationSupport {
def id: String = internalId
override def internalId: String = entity.internalId
override def json: JsValue = entity.json
override def theName: String = entity.theName
override def theDescription: String = entity.theDescription
override def theTags: Seq[String] = entity.theTags
def id: String = internalId
override def internalId: String = entity.internalId
override def json: JsValue = entity.json
override def theName: String = entity.theName
override def theDescription: String = entity.theDescription
override def theTags: Seq[String] = entity.theTags
override def theMetadata: Map[String, String] = entity.theMetadata
override def location: EntityLocation = entity.location
override def location: EntityLocation = entity.location
}

object ServiceLike {
def fromService(service: ServiceDescriptor): ServiceLike = ServiceLike(service, service.groups)
def fromRoute(service: NgRoute): ServiceLike = ServiceLike(service, service.groups)
def fromService(service: ServiceDescriptor): ServiceLike = ServiceLike(service, service.groups)
def fromRoute(service: NgRoute): ServiceLike = ServiceLike(service, service.groups)
def fromRouteComposition(service: NgService): ServiceLike = ServiceLike(service, service.groups)
}

Expand Down Expand Up @@ -818,7 +818,7 @@ class BackOfficeController(
tags = Seq.empty,
metadata = Map.empty,
sessionCookieValues = sessionCookieValues,
clientSideSessionEnabled = true,
clientSideSessionEnabled = true
).asJson
)
)
Expand All @@ -838,7 +838,7 @@ class BackOfficeController(
tags = Seq.empty,
metadata = Map.empty,
sessionCookieValues = sessionCookieValues,
clientSideSessionEnabled = true,
clientSideSessionEnabled = true
)
val body = Json.parse(resp.body)
val issuer = (body \ "issuer").asOpt[String].getOrElse("http://localhost:8082/")
Expand Down Expand Up @@ -907,7 +907,7 @@ class BackOfficeController(
tags = Seq.empty,
metadata = Map.empty,
sessionCookieValues = sessionCookieValues,
clientSideSessionEnabled = true,
clientSideSessionEnabled = true
).asJson
)
}
Expand All @@ -924,7 +924,7 @@ class BackOfficeController(
tags = Seq.empty,
metadata = Map.empty,
sessionCookieValues = sessionCookieValues,
clientSideSessionEnabled = true,
clientSideSessionEnabled = true
).asJson
)
}
Expand Down Expand Up @@ -1602,13 +1602,15 @@ class BackOfficeController(
def findServiceLike(serviceId: String): Future[Option[ServiceLike]] = {
env.datastores.serviceDescriptorDataStore.findById(serviceId) flatMap {
case Some(service) => ServiceLike.fromService(service).some.vfuture
case None => env.datastores.routeDataStore.findById(serviceId) flatMap {
case Some(service) => ServiceLike.fromRoute(service).some.vfuture
case None => env.datastores.servicesDataStore.findById(serviceId) map {
case Some(service) => ServiceLike.fromRouteComposition(service).some
case None => None
case None =>
env.datastores.routeDataStore.findById(serviceId) flatMap {
case Some(service) => ServiceLike.fromRoute(service).some.vfuture
case None =>
env.datastores.servicesDataStore.findById(serviceId) map {
case Some(service) => ServiceLike.fromRouteComposition(service).some
case None => None
}
}
}
}
}

Expand Down Expand Up @@ -1723,8 +1725,8 @@ class BackOfficeController(
}

def graphqlProxy() = BackOfficeActionAuth.async(sourceBodyParser) { ctx =>
val url = ctx.request.queryString.get("url").map(_.last).get
val host = Uri(url).authority.host.toString()
val url = ctx.request.queryString.get("url").map(_.last).get
val host = Uri(url).authority.host.toString()
val headers = (ctx.request.headers.toSimpleMap ++ Map("Host" -> host)).toSeq

val builder = env.Ws
Expand All @@ -1744,15 +1746,16 @@ class BackOfficeController(
.execute()
.fast
.map { res =>
Results.Status(res.status)(res.body)
Results
.Status(res.status)(res.body)
.withHeaders(res.headers.mapValues(_.last).toSeq.filterNot(_._1 == "Content-Type"): _*)
.as(res.contentType)
}
}

def routeEntries(routeId: String) = BackOfficeActionAuth.async { ctx =>
env.datastores.routeDataStore.findById(routeId) flatMap {
case None => NotFound(Json.obj("error" -> "route not found")).future
case None => NotFound(Json.obj("error" -> "route not found")).future
case Some(route) =>
val isSecured = route.plugins.slots.exists(p => p.plugin.contains("ForceHttpsTraffic"))

Expand All @@ -1761,76 +1764,69 @@ class BackOfficeController(
.withScheme(if (isSecured) "https" else "http")
.withPort(if (isSecured) env.exposedHttpsPortInt else env.exposedHttpPortInt)
.toString()
})))
.future
}))).future
}
}

def graphQLToJson() = BackOfficeActionAuth.async(parse.json) { ctx =>
val schema = ctx.request.body.select("schema").asOpt[String].getOrElse("{}")

sangria.parser.QueryParser.parse(schema) match {
case scala.util.Failure(exception) => BadRequest(Json.obj("error" -> exception.getMessage)).future
case scala.util.Failure(exception) => BadRequest(Json.obj("error" -> exception.getMessage)).future
case scala.util.Success(astDocument) =>
val generatedSchema = sangria.schema.Schema.buildFromAst(astDocument)
val res = GraphQLFormats.astDocumentToJson(generatedSchema)
val generatedSchema = sangria.schema.Schema.buildFromAst(astDocument)
val res = GraphQLFormats.astDocumentToJson(generatedSchema)

Ok(Json.obj("types" -> res)).future
Ok(Json.obj("types" -> res)).future
}
}

def jsonToGraphqlSchema() = BackOfficeActionAuth.async(parse.json) { ctx =>
import sangria.schema.Schema

val types = ctx.request.body.select("types")
.as[JsArray]
.value
.map(GraphQLFormats.objectTypeDefinitionFmt.reads)
.flatMap {
case JsSuccess(v, _) => Some(v)
case JsError(_) => None
}
val types = ctx.request.body
.select("types")
.as[JsArray]
.value
.map(GraphQLFormats.objectTypeDefinitionFmt.reads)
.flatMap {
case JsSuccess(v, _) => Some(v)
case JsError(_) => None
}

val schema = ctx.request.body.select("schema").asOpt[String].getOrElse("{}")

Try {
sangria.parser.QueryParser.parse(schema) match {
case scala.util.Failure(exception) => BadRequest(Json.obj("error" -> exception.getMessage)).future
case scala.util.Failure(exception) => BadRequest(Json.obj("error" -> exception.getMessage)).future
case scala.util.Success(astDocument) =>
val generatedSchema = Schema.buildFromAst(astDocument)
val document = generatedSchema.toAst
val document = generatedSchema.toAst

val newDocument = document.copy(
definitions = document.definitions.flatMap {
case _: sangria.ast.TypeDefinition => None
case _: sangria.ast.TypeDefinition => None
case _: sangria.ast.InterfaceTypeDefinition => None
case v => Some(v)
case v => Some(v)
} ++ types
)

Ok(Json.obj(
"schema" -> Schema.buildFromAst(newDocument).renderPretty
)).future
Ok(
Json.obj(
"schema" -> Schema.buildFromAst(newDocument).renderPretty
)
).future
}
} recover {
case e => BadRequest(Json.obj(
"error" -> e.getMessage
)).future
} recover { case e =>
BadRequest(
Json.obj(
"error" -> e.getMessage
)
).future
} get
}

def toYaml = BackOfficeActionAuth(parse.json) { ctx =>
Ok(Yaml.write(ctx.request.body)).as("application/yaml")
}
}











14 changes: 10 additions & 4 deletions otoroshi/app/controllers/HealthController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ import otoroshi.utils.syntax.implicits._

import scala.concurrent.Future

class HealthController(cc: ControllerComponents, BackOfficeActionAuth: BackOfficeActionAuth)(implicit env: Env) extends AbstractController(cc) {
class HealthController(cc: ControllerComponents, BackOfficeActionAuth: BackOfficeActionAuth)(implicit env: Env)
extends AbstractController(cc) {

implicit lazy val ec = env.otoroshiExecutionContext
implicit lazy val mat = env.otoroshiMaterializer
Expand Down Expand Up @@ -159,7 +160,12 @@ class HealthController(cc: ControllerComponents, BackOfficeActionAuth: BackOffic
}
}

def fetchMetrics(format: Option[String], acceptsJson: Boolean, acceptsProm: Boolean, filter: Option[String]): Result = {
def fetchMetrics(
format: Option[String],
acceptsJson: Boolean,
acceptsProm: Boolean,
filter: Option[String]
): Result = {
if (format.contains("old_json") || format.contains("old")) {
Ok(env.metrics.jsonExport(filter)).as("application/json")
} else if (format.contains("json")) {
Expand All @@ -176,8 +182,8 @@ class HealthController(cc: ControllerComponents, BackOfficeActionAuth: BackOffic
}

def processMetrics() = Action.async { req =>
val format = req.getQueryString("format")
val filter = req.getQueryString("filter")
val format = req.getQueryString("format")
val filter = req.getQueryString("filter")
val acceptsJson = req.accepts("application/json")
val acceptsProm = req.accepts("application/prometheus")
if (env.metricsEnabled) {
Expand Down
39 changes: 24 additions & 15 deletions otoroshi/app/controllers/adminapi/ClusterController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import otoroshi.actions.ApiAction
import otoroshi.cluster._
import otoroshi.env.Env
import otoroshi.models.{PrivateAppsUser, RightsChecker}
import otoroshi.next.proxy.{RelayRoutingRequest, ProxyEngine}
import otoroshi.next.proxy.{ProxyEngine, RelayRoutingRequest}
import otoroshi.script.RequestHandler
import otoroshi.security.IdGenerator
import otoroshi.utils.syntax.implicits._
Expand Down Expand Up @@ -352,7 +352,9 @@ class ClusterController(ApiAction: ApiAction, cc: ControllerComponents)(implicit
.map { name =>
env.datastores.clusterStateDataStore.registerMember(
MemberView(
id = ctx.request.headers.get(ClusterAgent.OtoroshiWorkerIdHeader).getOrElse(s"tmpnode_${IdGenerator.uuid}"),
id = ctx.request.headers
.get(ClusterAgent.OtoroshiWorkerIdHeader)
.getOrElse(s"tmpnode_${IdGenerator.uuid}"),
name = name,
memberType = ClusterMode.Worker,
location =
Expand Down Expand Up @@ -451,7 +453,9 @@ class ClusterController(ApiAction: ApiAction, cc: ControllerComponents)(implicit
ctx.request.headers.get(ClusterAgent.OtoroshiWorkerNameHeader).map { name =>
env.datastores.clusterStateDataStore.registerMember(
MemberView(
id = ctx.request.headers.get(ClusterAgent.OtoroshiWorkerIdHeader).getOrElse(s"tmpnode_${IdGenerator.uuid}"),
id = ctx.request.headers
.get(ClusterAgent.OtoroshiWorkerIdHeader)
.getOrElse(s"tmpnode_${IdGenerator.uuid}"),
name = name,
memberType = ClusterMode.Worker,
location = ctx.request.headers.get(ClusterAgent.OtoroshiWorkerLocationHeader).getOrElse("--"),
Expand Down Expand Up @@ -640,30 +644,35 @@ class ClusterController(ApiAction: ApiAction, cc: ControllerComponents)(implicit
ctx.checkRights(RightsChecker.SuperAdminOnly) {
env.clusterConfig.mode match {
case Off => NotFound(Json.obj("error" -> "Cluster API not available")).future
case _ => {
val engine = env.scriptManager.getAnyScript[RequestHandler](s"cp:${classOf[ProxyEngine].getName}").right.get
val cookies = ctx.request.headers.get("Otoroshi-Relay-Routing-Cookies").map(c => Cookies.decodeCookieHeader(c)).getOrElse(Seq.empty[Cookie])
val certs = ctx.request.headers.headers.filter(_._1.startsWith("Otoroshi-Relay-Routing-Certs-"))
case _ => {
val engine = env.scriptManager.getAnyScript[RequestHandler](s"cp:${classOf[ProxyEngine].getName}").right.get
val cookies = ctx.request.headers
.get("Otoroshi-Relay-Routing-Cookies")
.map(c => Cookies.decodeCookieHeader(c))
.getOrElse(Seq.empty[Cookie])
val certs = ctx.request.headers.headers
.filter(_._1.startsWith("Otoroshi-Relay-Routing-Certs-"))
.map { case (key, value) => (key.replace("Otoroshi-Relay-Routing-Certs-", "").toInt, value) }
.sortWith((a, b) => a._1.compareTo(b._1) < 0)
.map {
case (_, value) => value.trim.toCertificate
}.applyOn { seq =>
.map { case (_, value) =>
value.trim.toCertificate
}
.applyOn { seq =>
if (seq.isEmpty) {
None
} else {
seq.some
}
}
val request = new RelayRoutingRequest(ctx.request, Cookies(cookies), certs)
val routeName = ctx.request.headers.get("Otoroshi-Relay-Routing-Route-Name").getOrElse("--")
val request = new RelayRoutingRequest(ctx.request, Cookies(cookies), certs)
val routeName = ctx.request.headers.get("Otoroshi-Relay-Routing-Route-Name").getOrElse("--")
val callerName = ctx.request.headers.get("Otoroshi-Relay-Routing-Caller-Name").getOrElse("--")
RelayRouting.logger.debug(s"routing relay call to '${routeName}' from '${callerName}'")
engine.handle(request, _ => Results.InternalServerError("bad default routing").vfuture).map { resp =>
resp.copy(
header = resp.header.copy(
headers = resp.header.headers.map {
case (key, value) => (s"Otoroshi-Relay-Routing-Response-Header-$key", value)
headers = resp.header.headers.map { case (key, value) =>
(s"Otoroshi-Relay-Routing-Response-Header-$key", value)
}
)
)
Expand All @@ -672,4 +681,4 @@ class ClusterController(ApiAction: ApiAction, cc: ControllerComponents)(implicit
}
}
}
}
}
Loading

0 comments on commit 1990864

Please sign in to comment.