Skip to content

Commit 9321524

Browse files
authored
Merge pull request #25 from Quafadas/proxyWork
Proxy fixes
2 parents f3b7324 + 6027e87 commit 9321524

File tree

10 files changed

+139
-82
lines changed

10 files changed

+139
-82
lines changed

justfile

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,14 @@ test:
1414
checkOpts:
1515
mill project.run --help
1616

17+
1718
jvmServe:
1819
mill -w project.runBackground --build-tool scala-cli --project-dir /Users/simon/Code/indigoLite --log-level info --browse-on-open-at / --path-to-index-html /Users/simon/Code/indigoLite/static
1920

21+
proxy:
22+
mill -w project.runBackground --project-dir /Users/simon/Code/viteless --port 3006 --proxy-prefix-path /api --proxy-target-port 8080 --log-level trace
23+
24+
2025
goViteless:
2126
mill -w project.run --project-dir /Users/simon/Code/viteless --styles-dir /Users/simon/Code/viteless/styles
2227

project/src/build.runner.scala

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -127,13 +127,16 @@ def buildRunnerMill(
127127
.background
128128
.void
129129

130+
val millargs = List(
131+
"-w",
132+
s"$moduleName.fastLinkJS",
133+
"-j",
134+
"0"
135+
) ++ extraBuildArgs
130136
// TODO pipe this to stdout so that we can see linker progress / errors.
131137
val builder = ProcessBuilder(
132138
"mill",
133-
List(
134-
"-w",
135-
s"$moduleName.fastLinkJS"
136-
) ++ extraBuildArgs
139+
millargs
137140
).withWorkingDirectory(workDir)
138141
.spawn[IO]
139142
.use {
@@ -147,6 +150,7 @@ def buildRunnerMill(
147150
for
148151
_ <- logger.trace("Starting buildRunnerMill").toResource
149152
_ <- logger.trace(s"watching path $watchLinkComplePath").toResource
153+
_ <- logger.trace(s"running mill with args $millargs").toResource
150154
_ <- builder
151155
_ <- watcher
152156
yield ()

project/src/live.server.scala

Lines changed: 2 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,6 @@ import cats.implicits.*
2323
import _root_.io.circe.*
2424
import _root_.io.circe.Encoder
2525

26-
import ProxyConfig.Equilibrium
27-
import ProxyConfig.Server
28-
import com.comcast.ip4s.Host
29-
import cats.data.NonEmptyList
30-
import ProxyConfig.LocationMatcher
31-
3226
sealed trait FrontendEvent derives Encoder.AsObject
3327

3428
case class KeepAlive() extends FrontendEvent derives Encoder.AsObject
@@ -213,46 +207,6 @@ object LiveServer extends IOApp:
213207
.withHandler(minimumLevel = Some(Level.get(lvl).get))
214208
.replace()
215209

216-
val proxyConf2: Resource[IO, Option[Equilibrium]] = proxyTarget
217-
.zip(pathPrefix)
218-
.traverse {
219-
(pt, prfx) =>
220-
IO(
221-
Equilibrium(
222-
ProxyConfig.HttpProxyConfig(
223-
servers = NonEmptyList(
224-
Server(
225-
listen = port,
226-
serverNames = List("localhost"),
227-
locations = List(
228-
ProxyConfig.Location(
229-
matcher = LocationMatcher.Prefix(prfx),
230-
proxyPass = s"http://$$backend"
231-
)
232-
)
233-
),
234-
List()
235-
),
236-
upstreams = List(
237-
ProxyConfig.Upstream(
238-
name = "backend",
239-
servers = NonEmptyList(
240-
ProxyConfig.UpstreamServer(
241-
host = Host.fromString("localhost").get,
242-
port = pt,
243-
weight = 5
244-
),
245-
List()
246-
)
247-
)
248-
)
249-
)
250-
)
251-
)
252-
253-
}
254-
.toResource
255-
256210
val server = for
257211
_ <- logger
258212
.debug(
@@ -295,7 +249,8 @@ object LiveServer extends IOApp:
295249
CliValidationError("path-to-index-html and styles-dir can't be defined at the same time")
296250
)
297251

298-
proxyRoutes <- makeProxyRoutes(client, pathPrefix, proxyConf2)(logger)
252+
proxyConf2 <- proxyConf(proxyTarget, pathPrefix)
253+
proxyRoutes: HttpRoutes[IO] = makeProxyRoutes(client, proxyConf2)(logger)
299254

300255
_ <- buildRunner(
301256
buildTool,

project/src/middleware/ETagMiddleware.scala

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,8 @@ object ETagMiddleware:
6363
OptionT.liftF(logger.debug("No ETag header in query, service it")) >>
6464
service(req).semiflatMap {
6565
resp =>
66-
respondWithEtag(resp)
66+
logger.trace(resp.toString) >>
67+
respondWithEtag(resp)
6768
}
6869
end match
6970
}

project/src/middleware/noCache.middleware.scala

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,12 @@ import org.http4s.HttpRoutes
33
import org.http4s.Request
44
import org.typelevel.ci.CIStringSyntax
55

6+
import scribe.Scribe
7+
68
import cats.data.Kleisli
9+
import cats.data.OptionT
710
import cats.effect.*
811
import cats.effect.IO
9-
import scribe.Scribe
10-
import cats.data.OptionT
1112
import cats.syntax.all.*
1213

1314
object NoCacheMiddlware:

project/src/proxy.config.scala

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import com.comcast.ip4s.*
22

33
import cats.data.NonEmptyList
4-
54
import cats.syntax.all.*
65

76
object ProxyConfig:

project/src/proxy.http.scala

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,14 @@ object HttpProxy:
2929

3030
val routes: HttpRoutes[F] = HttpRoutes.of {
3131
case (req: Request[F]) =>
32+
// println("in proxy")
33+
// println(req)
3234
val pathRendered = pathPrefix + req.uri.path.renderString
35+
// println(pathRendered)
3336
val host = req.headers.get[Host].map(_.host).getOrElse("") // Host set otherwise empty string
3437
val newServers = servers.filter(_.serverNames.contains(host))
35-
38+
// println(host)
39+
// println(newServers)
3640
val exact =
3741
newServers
3842
.flatMap(_.locations)
@@ -59,12 +63,13 @@ object HttpProxy:
5963
.headOption
6064
.map(_._2)
6165
}
62-
6366
proxy.fold(
6467
Response[F](Status.NotFound).withEntity("No Route Found").pure[F]
6568
)(
66-
proxyThrough[F](_, upstreams)
67-
.flatMap(uri => client.toHttpApp(req.removeHeader[Host].withUri(uri.addPath(pathRendered))))
69+
proxyThrough[F](_, upstreams).flatMap {
70+
uri =>
71+
client.toHttpApp(req.removeHeader[Host].withUri(uri.addPath(pathRendered)))
72+
}
6873
)
6974
}
7075

@@ -76,6 +81,8 @@ object HttpProxy:
7681
proxyPass: String,
7782
upstreams: Map[String, NonEmptyList[ProxyConfig.UpstreamServer]]
7883
): F[Uri] =
84+
println(s"proxypass $proxyPass")
85+
println(upstreams)
7986
if !proxyPass.contains("$") then Uri.fromString(proxyPass).liftTo[F]
8087
else
8188
extractVariable(proxyPass).flatMap {
@@ -89,6 +96,8 @@ object HttpProxy:
8996
)
9097
)
9198
}
99+
end if
100+
end proxyThrough
92101

93102
private def extractVariable[F[_]: ApplicativeThrow](s: String): F[(String, String, String)] =
94103
s.split('$').toList match
@@ -131,6 +140,8 @@ object HttpProxy:
131140

132141
def xForwardedMiddleware[G[_], F[_]](http: Http[G, F]): Http[G, F] = Kleisli {
133142
(req: Request[F]) =>
143+
println("in middleware")
144+
println(req)
134145
req
135146
.remote
136147
.fold(http.run(req)) {

project/src/proxy.routes.scala

Lines changed: 69 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,86 @@
11
import org.http4s.HttpRoutes
22
import org.http4s.client.Client
3+
import org.http4s.server.Router
4+
import org.http4s.server.middleware.Logger
5+
6+
import com.comcast.ip4s.Host
7+
import com.comcast.ip4s.Port
38

49
import scribe.Scribe
510

11+
import cats.data.NonEmptyList
612
import cats.effect.IO
713
import cats.effect.kernel.Resource
814
import cats.effect.std.Random
15+
import cats.syntax.all.*
916

1017
import ProxyConfig.Equilibrium
18+
import ProxyConfig.LocationMatcher
19+
import ProxyConfig.Server
1120

1221
def makeProxyRoutes(
1322
client: Client[IO],
14-
pathPrefix: Option[String],
15-
proxyConfig: Resource[IO, Option[Equilibrium]]
16-
)(logger: Scribe[IO]): Resource[IO, HttpRoutes[IO]] =
17-
proxyConfig.flatMap {
18-
case Some(pc) =>
19-
{
20-
given R: Random[IO] = Random.javaUtilConcurrentThreadLocalRandom[IO]
21-
logger.debug("setup proxy server") >>
22-
IO(HttpProxy.servers[IO](pc, client, pathPrefix.getOrElse(???)).head._2)
23-
}.toResource
23+
proxyConfig: Option[(Equilibrium, String)]
24+
)(logger: Scribe[IO]): HttpRoutes[IO] =
25+
proxyConfig match
26+
case Some((pc, pathPrefix)) =>
27+
given R: Random[IO] = Random.javaUtilConcurrentThreadLocalRandom[IO]
28+
Logger.httpRoutes[IO](
29+
logHeaders = true,
30+
logBody = true,
31+
redactHeadersWhen = _ => false,
32+
logAction = Some((msg: String) => logger.trace(msg))
33+
)(
34+
Router(
35+
pathPrefix -> HttpProxy.servers[IO](pc, client, pathPrefix).head._2
36+
)
37+
)
2438

2539
case None =>
26-
(
27-
logger.debug("no proxy set") >>
28-
IO(HttpRoutes.empty[IO])
29-
).toResource
30-
}
40+
HttpRoutes.empty[IO]
3141

3242
end makeProxyRoutes
43+
44+
def proxyConf(proxyTarget: Option[Port], pathPrefix: Option[String]): Resource[IO, Option[(Equilibrium, String)]] =
45+
proxyTarget
46+
.zip(pathPrefix)
47+
.traverse {
48+
(pt, prfx) =>
49+
IO(
50+
(
51+
Equilibrium(
52+
ProxyConfig.HttpProxyConfig(
53+
servers = NonEmptyList(
54+
Server(
55+
listen = pt,
56+
serverNames = List("localhost"),
57+
locations = List(
58+
ProxyConfig.Location(
59+
matcher = LocationMatcher.Prefix(prfx),
60+
proxyPass = "http://$backend"
61+
)
62+
)
63+
),
64+
List()
65+
),
66+
upstreams = List(
67+
ProxyConfig.Upstream(
68+
name = "backend",
69+
servers = NonEmptyList(
70+
ProxyConfig.UpstreamServer(
71+
host = Host.fromString("localhost").get,
72+
port = pt,
73+
weight = 5
74+
),
75+
List()
76+
)
77+
)
78+
)
79+
)
80+
),
81+
prfx
82+
)
83+
)
84+
85+
}
86+
.toResource

project/src/routes.scala

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import org.http4s.Response
1111
import org.http4s.ServerSentEvent
1212
import org.http4s.StaticFile
1313
import org.http4s.Status
14+
import org.http4s.Uri.Path.SegmentEncoder
1415
import org.http4s.dsl.io.*
1516
import org.http4s.scalatags.*
1617
import org.http4s.server.Router
@@ -35,7 +36,6 @@ import cats.effect.kernel.Resource
3536
import cats.syntax.all.*
3637

3738
import _root_.io.circe.syntax.EncoderOps
38-
import org.http4s.Uri.Path.SegmentEncoder
3939

4040
def routes[F[_]: Files: MonadThrow](
4141
stringPath: String,
@@ -60,6 +60,12 @@ def routes[F[_]: Files: MonadThrow](
6060
StaticFile
6161
.fromPath(fs2.io.file.Path(stringPath) / req.uri.path.renderString, Some(req))
6262
.getOrElseF(NotFound())
63+
64+
case req @ GET -> Root / fName ~ "map" =>
65+
StaticFile
66+
.fromPath(fs2.io.file.Path(stringPath) / req.uri.path.renderString, Some(req))
67+
.getOrElseF(NotFound())
68+
6369
},
6470
ref
6571
)(logger)
@@ -209,9 +215,9 @@ def routes[F[_]: Files: MonadThrow](
209215
val app = logMiddler(
210216
refreshRoutes
211217
.combineK(linkedAppWithCaching)
218+
.combineK(proxyRoutes)
212219
.combineK(clientSpaRoutes)
213220
.combineK(staticAssetRoutes)
214-
.combineK(proxyRoutes)
215221
)
216222

217223
clientRoutingPrefix.fold(IO.unit)(s => logger.trace(s"client spa at : $s")).toResource >>

0 commit comments

Comments
 (0)