-
Notifications
You must be signed in to change notification settings - Fork 788
/
ResourceService.scala
207 lines (188 loc) · 7.39 KB
/
ResourceService.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
/*
* Copyright 2014 http4s.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.http4s
package server
package staticcontent
import cats.data.Kleisli
import cats.data.OptionT
import cats.effect.Async
import cats.syntax.all._
import org.http4s.server.middleware.TranslateUri
import java.io.File
import java.nio.file.Paths
import scala.util.Failure
import scala.util.Success
import scala.util.Try
import scala.util.control.NoStackTrace
/** [[org.http4s.server.staticcontent.ResourceServiceBuilder]] builder
*
* @param basePath prefix of the path files will be served from
* @param pathPrefix prefix of the Uri that content will be served from
* @param bufferSize size hint of internal buffers to use when serving resources
* @param cacheStrategy strategy to use for caching purposes.
* @param preferGzipped whether to serve pre-gzipped files (with extension ".gz") if they exist
* @param classLoader optional classloader for extracting the resources
*/
class ResourceServiceBuilder[F[_]] private (
basePath: String,
pathPrefix: String,
bufferSize: Int,
cacheStrategy: CacheStrategy[F],
preferGzipped: Boolean,
classLoader: Option[ClassLoader],
) {
private[this] val logger = Platform.loggerFactory.getLogger
private def copy(
basePath: String = basePath,
pathPrefix: String = pathPrefix,
bufferSize: Int = bufferSize,
cacheStrategy: CacheStrategy[F] = cacheStrategy,
preferGzipped: Boolean = preferGzipped,
classLoader: Option[ClassLoader] = classLoader,
): ResourceServiceBuilder[F] =
new ResourceServiceBuilder[F](
basePath,
pathPrefix,
bufferSize,
cacheStrategy,
preferGzipped,
classLoader,
)
def withBasePath(basePath: String): ResourceServiceBuilder[F] = copy(basePath = basePath)
def withPathPrefix(pathPrefix: String): ResourceServiceBuilder[F] =
copy(pathPrefix = pathPrefix)
def withCacheStrategy(cacheStrategy: CacheStrategy[F]): ResourceServiceBuilder[F] =
copy(cacheStrategy = cacheStrategy)
def withPreferGzipped(preferGzipped: Boolean): ResourceServiceBuilder[F] =
copy(preferGzipped = preferGzipped)
def withClassLoader(classLoader: Option[ClassLoader]): ResourceServiceBuilder[F] =
copy(classLoader = classLoader)
def withBufferSize(bufferSize: Int): ResourceServiceBuilder[F] = copy(bufferSize = bufferSize)
def toRoutes(implicit F: Async[F]): HttpRoutes[F] = {
val basePath = if (this.basePath.isEmpty) "/" else this.basePath
object BadTraversal extends Exception with NoStackTrace
Try(Paths.get(basePath)) match {
case Success(rootPath) =>
TranslateUri(pathPrefix)(Kleisli {
case request if request.pathInfo.nonEmpty =>
val segments = request.pathInfo.segments.map(_.decoded(plusIsSpace = true))
OptionT
.liftF(F.catchNonFatal {
segments.foldLeft(rootPath) {
case (_, "" | "." | "..") => throw BadTraversal
case (path, segment) =>
path.resolve(segment)
}
})
.collect {
case path if path.startsWith(rootPath) => path
}
.flatMap { path =>
StaticFile.fromResource(
path.toString.replace(File.separatorChar, '/'),
Some(request),
preferGzipped = preferGzipped,
classLoader,
)
}
.semiflatMap(cacheStrategy.cache(request.pathInfo, _))
.recoverWith { case BadTraversal =>
OptionT.some(Response(Status.BadRequest))
}
case _ => OptionT.none
})
case Failure(e) =>
logger
.error(e)(
s"Could not get root path from ResourceService config: basePath = $basePath, pathPrefix = $pathPrefix. All requests will fail."
)
.unsafeRunSync()
Kleisli(_ => OptionT.pure(Response(Status.InternalServerError)))
}
}
}
object ResourceServiceBuilder {
def apply[F[_]](basePath: String): ResourceServiceBuilder[F] =
new ResourceServiceBuilder[F](
basePath = basePath,
pathPrefix = "",
bufferSize = 50 * 1024,
cacheStrategy = NoopCacheStrategy[F],
preferGzipped = false,
classLoader = None,
)
}
object ResourceService {
private[this] val logger = Platform.loggerFactory.getLogger
/** [[org.http4s.server.staticcontent.ResourceService]] configuration
*
* @param basePath prefix of the path files will be served from
* @param pathPrefix prefix of the Uri that content will be served from
* @param bufferSize size hint of internal buffers to use when serving resources
* @param cacheStrategy strategy to use for caching purposes. Default to no caching.
* @param preferGzipped whether to serve pre-gzipped files (with extension ".gz") if they exist
*/
final case class Config[F[_]](
basePath: String,
pathPrefix: String = "",
bufferSize: Int = 50 * 1024,
cacheStrategy: CacheStrategy[F] = NoopCacheStrategy[F],
preferGzipped: Boolean = false,
)
/** Make a new [[org.http4s.HttpRoutes]] that serves static files. */
@deprecated("use ResourceServiceBuilder", "1.0.0-M1")
private[staticcontent] def apply[F[_]](config: Config[F])(implicit F: Async[F]): HttpRoutes[F] = {
val basePath = if (config.basePath.isEmpty) "/" else config.basePath
object BadTraversal extends Exception with NoStackTrace
Try(Paths.get(basePath)) match {
case Success(rootPath) =>
TranslateUri(config.pathPrefix)(Kleisli {
case request if request.pathInfo.nonEmpty =>
val segments = request.pathInfo.segments.map(_.decoded(plusIsSpace = true))
OptionT
.liftF(F.catchNonFatal {
segments.foldLeft(rootPath) {
case (_, "" | "." | "..") => throw BadTraversal
case (path, segment) =>
path.resolve(segment)
}
})
.collect {
case path if path.startsWith(rootPath) => path
}
.flatMap { path =>
StaticFile.fromResource(
path.toString,
Some(request),
preferGzipped = config.preferGzipped,
)
}
.semiflatMap(config.cacheStrategy.cache(request.pathInfo, _))
.recoverWith { case BadTraversal =>
OptionT.some(Response(Status.BadRequest))
}
case _ => OptionT.none
})
case Failure(e) =>
logger
.error(e)(
s"Could not get root path from ResourceService config: basePath = ${config.basePath}, pathPrefix = ${config.pathPrefix}. All requests will fail."
)
.unsafeRunSync()
Kleisli(_ => OptionT.pure(Response(Status.InternalServerError)))
}
}
}