This repository has been archived by the owner. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 50
/
package.scala
321 lines (279 loc) · 11.7 KB
/
package.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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
package korolev
import java.io.{ByteArrayOutputStream, InputStream}
import java.nio.charset.StandardCharsets
import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference}
import korolev.Async._
import korolev.internal.{ApplicationInstance, Connection}
import korolev.state._
import levsha.Id
import slogging.LazyLogging
import scala.collection.concurrent.TrieMap
import scala.collection.mutable
import scala.util.{Failure, Success, Try}
package object server extends LazyLogging {
type StateStorage[F[+_], S] = korolev.state.StateStorage[F, S]
val StateStorage = korolev.state.StateStorage
type MimeTypes = String => Option[String]
type KorolevService[F[+_]] = PartialFunction[Request, F[Response]]
def korolevService
[
F[+_]: Async,
S: StateSerializer: StateDeserializer,
M
] (
mimeTypes: MimeTypes,
config: KorolevServiceConfig[F, S, M]
): KorolevService[F] = {
import misc._
val sessions = TrieMap.empty[String, KorolevSession[F]]
def getOrCreateStateManager(deviceId: DeviceId, sessionId: SessionId): F[(StateManager[F], Boolean)] =
for {
maybeStateManager <- config.stateStorage.get(deviceId, sessionId)
stateManager <- maybeStateManager.fold(config.stateStorage.create(deviceId, sessionId))(Async[F].pure(_))
} yield (stateManager, maybeStateManager.isEmpty)
def renderStatic(request: Request): F[Response] =
for {
deviceId <- deviceFromRequest(request)
sessionId <- config.idGenerator.generateSessionId()
state <- config.router(deviceId, None)
.toState
.lift((None, request.path))
.getOrElse(config.stateStorage.createTopLevelState(deviceId))
.flatMap { state =>
getOrCreateStateManager(deviceId, sessionId).map(_._1).flatMap { manager =>
manager.write(Id.TopLevel, state).map(_ => state)
}
}
} yield {
val dsl = new levsha.TemplateDsl[Context.Effect[F, S, M]]()
val textRenderContext = new HtmlRenderContext[F, S, M]()
val rootPath = config.rootPath
val clw = {
val textRenderContext = new HtmlRenderContext[F, S, M]()
config.connectionLostWidget(textRenderContext)
textRenderContext.mkString
}
val heartbeatInterval = config.heartbeatInterval.toMillis
import dsl._
val kfg = s"window['kfg']={sid:'$sessionId',r:'$rootPath',clw:'$clw',heartbeatInterval:$heartbeatInterval}"
val document = 'html(
'head(
'script('language /= "javascript", kfg),
'script('src /= config.rootPath + "korolev-client.min.js"),
config.head
),
config.render(state)
)
// Render document to textRenderContext
document(textRenderContext)
Response.Http(
status = Response.Status.Ok,
headers = Seq(
"content-type" -> htmlContentType,
"set-cookie" -> s"${Cookies.DeviceId}=$deviceId"
),
body = Some {
val sb = mutable.StringBuilder.newBuilder
val html = sb
.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">")
.append('\n')
.append(textRenderContext.builder)
.mkString
html.getBytes(StandardCharsets.UTF_8)
}
)
}
object matchStatic {
/**
* @return (resource bytes, ContentType)
*/
def unapply(req: Request): Option[(Array[Byte], String)] =
req.path match {
case Root => None
case path @ _ / fileName =>
val fsPath = s"/static${path.toString}"
val stream = getClass.getResourceAsStream(fsPath)
Option(stream) map { stream =>
val fileExtension = fileName.lastIndexOf('.') match {
case -1 => binaryContentType
case index => fileName.substring(index + 1)
}
(inputStreamToBytes(stream), fileExtension)
}
}
private def inputStreamToBytes(stream: InputStream): Array[Byte] = {
val bufferSize = 32
val baos = new ByteArrayOutputStream(Math.max(bufferSize, stream.available()))
val buffer = new Array[Byte](bufferSize)
var lastBytesRead = 0
while ({
lastBytesRead = stream.read(buffer)
lastBytesRead != -1
}) {
baos.write(buffer, 0, lastBytesRead)
}
baos.toByteArray
}
}
def deviceFromRequest(request: Request): F[DeviceId] =
request.cookie(Cookies.DeviceId) match {
case None => config.idGenerator.generateDeviceId()
case Some(deviceId) => Async[F].pure(deviceId)
}
def makeSessionKey(deviceId: DeviceId, sessionId: SessionId): String =
s"$deviceId-$sessionId"
def createSession(deviceId: DeviceId, sessionId: SessionId): F[KorolevSession[F]] = {
val connection = new Connection[F]()
for {
stateManagerIsNew <- getOrCreateStateManager(deviceId, sessionId)
(stateManager, isNew) = stateManagerIsNew
initialState <- config.stateStorage.createTopLevelState(deviceId)
// Create Korolev with dynamic router
router = config.router(deviceId, Some(sessionId))
qualifiedSessionId = QualifiedSessionId(deviceId, sessionId)
korolev = new ApplicationInstance(
qualifiedSessionId, connection,
stateManager, initialState,
config.render, router, fromScratch = isNew
)
env <- config.envConfigurator.configure(korolev.topLevelComponentInstance.browserAccess)
} yield {
// Subscribe to events to publish them to env
korolev.topLevelComponentInstance.setEventsSubscription { message: M =>
env.onMessage(message).runIgnoreResult
}
new KorolevSession[F] {
val aliveRef = new AtomicBoolean(true)
val currentPromise = new AtomicReference(Option.empty[Async.Promise[F, String]])
// Put the session to registry
val sessionKey = makeSessionKey(deviceId, sessionId)
sessions.put(sessionKey, this)
def publish(message: String): F[Unit] = {
connection.receive(message)
Async[F].unit
}
def nextMessage: F[String] =
connection.sent
def resolveFormData(descriptor: String, formData: Try[FormData]): Unit = {
korolev.topLevelComponentInstance.resolveFormData(descriptor, formData)
}
def destroy(): F[Unit] = {
if (aliveRef.getAndSet(false))
env.onDestroy()
.recover {
case ex: Throwable =>
logger.error("Error destroying environment", ex)
()
}
.map { _ =>
currentPromise.get() foreach { promise =>
promise.complete(Failure(new SessionDestroyedException("Session has been closed")))
}
config.stateStorage.remove(deviceId, sessionId)
sessions.remove(sessionKey)
()
}
else Async[F].unit
}
}
}
}
val formDataCodec = new FormDataCodec(config.maxFormDataEntrySize)
val service: PartialFunction[Request, F[Response]] = {
case matchStatic(stream, fileExtensionOpt) =>
val headers = mimeTypes(fileExtensionOpt).fold(Seq.empty[(String, String)]) {
fileExtension =>
Seq("content-type" -> fileExtension)
}
val response = Response.Http(Response.Status.Ok, Some(stream), headers)
Async[F].pure(response)
case Request(Root / "bridge" / deviceId / sessionId / "form-data" / descriptor, _, _, headers, body) =>
sessions.get(makeSessionKey(deviceId, sessionId)) match {
case Some(session) =>
val boundaryOpt = headers collectFirst {
case (k, v) if k.toLowerCase == "content-type" && v.contains("multipart/form-data") => v
} flatMap {
_.split(';')
.toList
.filter(_.contains('='))
.map(_.split('=').map(_.trim))
.collectFirst { case Array("boundary", s) => s }
}
boundaryOpt match {
case None =>
val error = "Content-Type should be `multipart/form-data`"
val res = Response.Http(Response.Status.BadRequest, error)
Async[F].pure(res)
case Some(boundary) =>
val formData = Try(formDataCodec.decode(body, boundary))
session.resolveFormData(descriptor, formData)
Async[F].pure(Response.Http(Response.Status.Ok, None))
}
case None =>
Async[F].pure(Response.Http(Response.Status.BadRequest, "Session doesn't exist"))
}
case Request(Root / "bridge" / "long-polling" / deviceId / sessionId / "publish", _, _, _, body) =>
sessions.get(makeSessionKey(deviceId, sessionId)) match {
case Some(session) =>
val message = new String(body.array(), StandardCharsets.UTF_8)
session
.publish(message)
.map(_ => Response.Http(Response.Status.Ok))
case None =>
Async[F].pure(Response.Http(Response.Status.BadRequest, "Session doesn't exist"))
}
case Request(Root / "bridge" / "long-polling" / deviceId / sessionId / "subscribe", _, _, _, _) =>
val sessionAsync = sessions.get(makeSessionKey(deviceId, sessionId)) match {
case Some(x) => Async[F].pure(x)
case None => createSession(deviceId, sessionId)
}
sessionAsync.flatMap { session =>
session.nextMessage.map { message =>
Response.Http(Response.Status.Ok,
body = Some(message.getBytes(StandardCharsets.UTF_8)),
headers = Seq("Cache-Control" -> "no-cache")
)
}
} recover {
case _: SessionDestroyedException =>
Response.Http(Response.Status.Gone, "Session has been destroyed")
}
case Request(Root / "bridge" / "web-socket" / deviceId / sessionId, _, _, _, _) =>
val sessionAsync = sessions.get(makeSessionKey(deviceId, sessionId)) match {
case Some(x) => Async[F].pure(x)
case None => createSession(deviceId, sessionId)
}
sessionAsync map { session =>
Response.WebSocket(
destroyHandler = () => session.destroy() run {
case Success(_) => // do nothing
case Failure(e) => logger.error("An error occurred during destroying the session", e)
},
publish = message => session.publish(message) run {
case Success(_) => // do nothing
case Failure(e) => logger.error("An error occurred during publishing message to session", e)
},
subscribe = { newSubscriber =>
def aux(): Unit = session.nextMessage run {
case Success(message) =>
newSubscriber(message)
aux()
case Failure(_: SessionDestroyedException) => // Do nothing
case Failure(e) =>
logger.error("An error occurred during polling message from session", e)
}
aux()
}
)
}
case request => renderStatic(request)
}
service
}
def emptyRouter[F[+_]: Async, S]: (DeviceId, Option[SessionId]) => Router[F, S, Option[S]] =
(_, _) => Router.empty[F, S, Option[S]]
private[server] object misc {
val htmlContentType = "text/html; charset=utf-8"
val binaryContentType = "application/octet-stream"
}
}