Debian Codegraph @

R/server.R

raw
1 #' @include server-input-handlers.R
2
3 appsByToken <- NULL
4 appsNeedingFlush <- NULL
5 on_load({
6 appsByToken <- Map$new()
7 appsNeedingFlush <- Map$new()
8 })
9
10
11 # Provide a character representation of the WS that can be used
12 # as a key in a Map.
13 wsToKey <- function(WS) {
14 as.character(WS$socket)
15 }
16
17 .globals$clients <- function(req) NULL
18
19
20 clearClients <- function() {
21 .globals$clients <- function(req) NULL
22 }
23
24
25 registerClient <- function(client) {
26 .globals$clients <- append(.globals$clients, client)
27 }
28
29
30 .globals$showcaseDefault <- 0
31
32 .globals$showcaseOverride <- FALSE
33
34
35 #' Define Server Functionality
36 #'
37 #' @description `r lifecycle::badge("superseded")`
38 #'
39 #' @description Defines the server-side logic of the Shiny application. This generally
40 #' involves creating functions that map user inputs to various kinds of output.
41 #' In older versions of Shiny, it was necessary to call `shinyServer()` in
42 #' the `server.R` file, but this is no longer required as of Shiny 0.10.
43 #' Now the `server.R` file may simply return the appropriate server
44 #' function (as the last expression in the code), without calling
45 #' `shinyServer()`.
46 #'
47 #' Call `shinyServer` from your application's `server.R`
48 #' file, passing in a "server function" that provides the server-side logic of
49 #' your application.
50 #'
51 #' The server function will be called when each client (web browser) first loads
52 #' the Shiny application's page. It must take an `input` and an
53 #' `output` parameter. Any return value will be ignored. It also takes an
54 #' optional `session` parameter, which is used when greater control is
55 #' needed.
56 #'
57 #' See the [tutorial](https://shiny.rstudio.com/tutorial/) for more
58 #' on how to write a server function.
59 #'
60 #' @param func The server function for this application. See the details section
61 #' for more information.
62 #'
63 #' @examples
64 #' \dontrun{
65 #' # A very simple Shiny app that takes a message from the user
66 #' # and outputs an uppercase version of it.
67 #' shinyServer(function(input, output, session) {
68 #' output$uppercase <- renderText({
69 #' toupper(input$message)
70 #' })
71 #' })
72 #'
73 #'
74 #' # It is also possible for a server.R file to simply return the function,
75 #' # without calling shinyServer().
76 #' # For example, the server.R file could contain just the following:
77 #' function(input, output, session) {
78 #' output$uppercase <- renderText({
79 #' toupper(input$message)
80 #' })
81 #' }
82 #' }
83 #' @export
84 #' @keywords internal
85 shinyServer <- function(func) {
86 if (in_devmode()) {
87 shinyDeprecated(
88 "0.10.0", "shinyServer()",
89 details = paste0(
90 "When removing `shinyServer()`, ",
91 "ensure that the last expression returned from server.R ",
92 "is the function normally supplied to `shinyServer(func)`."
93 )
94 )
95 }
96
97 .globals$server <- list(func)
98 invisible(func)
99 }
100
101 decodeMessage <- function(data) {
102 readInt <- function(pos) {
103 packBits(rawToBits(data[pos:(pos+3)]), type='integer')
104 }
105
106 if (readInt(1) != 0x01020202L) {
107 # Treat message as UTF-8
108 charData <- rawToChar(data)
109 Encoding(charData) <- 'UTF-8'
110 return(safeFromJSON(charData, simplifyVector=FALSE))
111 }
112
113 i <- 5
114 parts <- list()
115 while (i <= length(data)) {
116 length <- readInt(i)
117 i <- i + 4
118 if (length != 0)
119 parts <- append(parts, list(data[i:(i+length-1)]))
120 else
121 parts <- append(parts, list(raw(0)))
122 i <- i + length
123 }
124
125 mainMessage <- decodeMessage(parts[[1]])
126 mainMessage$blobs <- parts[2:length(parts)]
127 return(mainMessage)
128 }
129
130 autoReloadCallbacks <- NULL
131 on_load({
132 autoReloadCallbacks <- Callbacks$new()
133 })
134
135 createAppHandlers <- function(httpHandlers, serverFuncSource) {
136 appvars <- new.env()
137 appvars$server <- NULL
138
139 sys.www.root <- system_file('www', package='shiny')
140
141 # This value, if non-NULL, must be present on all HTTP and WebSocket
142 # requests as the Shiny-Shared-Secret header or else access will be
143 # denied (403 response for HTTP, and instant close for websocket).
144 checkSharedSecret <- loadSharedSecret()
145
146 appHandlers <- list(
147 http = joinHandlers(c(
148 sessionHandler,
149 httpHandlers,
150 sys.www.root,
151 resourcePathHandler,
152 reactLogHandler
153 )),
154 ws = function(ws) {
155 if (!checkSharedSecret(ws$request$HTTP_SHINY_SHARED_SECRET)) {
156 ws$close()
157 return(TRUE)
158 }
159
160 if (identical(ws$request$PATH_INFO, "/autoreload/")) {
161 if (!get_devmode_option("shiny.autoreload", FALSE)) {
162 ws$close()
163 return(TRUE)
164 }
165
166 callbackHandle <- autoReloadCallbacks$register(function() {
167 ws$send("autoreload")
168 ws$close()
169 })
170 ws$onClose(function() {
171 callbackHandle()
172 })
173 return(TRUE)
174 }
175
176 if (!is.null(getOption("shiny.observer.error", NULL))) {
177 warning(
178 call. = FALSE,
179 "options(shiny.observer.error) is no longer supported; please unset it!"
180 )
181 stopApp()
182 }
183
184 shinysession <- ShinySession$new(ws)
185 appsByToken$set(shinysession$token, shinysession)
186 shinysession$setShowcase(.globals$showcaseDefault)
187
188 messageHandler <- function(binary, msg) {
189 withReactiveDomain(shinysession, {
190 # To ease transition from websockets-based code. Should remove once we're stable.
191 if (is.character(msg))
192 msg <- charToRaw(msg)
193
194 traceOption <- getOption('shiny.trace', FALSE)
195 if (isTRUE(traceOption) || traceOption == "recv") {
196 if (binary)
197 message("RECV ", '$$binary data$$')
198 else
199 message("RECV ", rawToChar(msg))
200 }
201
202 if (isEmptyMessage(msg))
203 return()
204
205 msg <- decodeMessage(msg)
206
207 # Set up a restore context from .clientdata_url_search before
208 # handling all the input values, because the restore context may be
209 # used by an input handler (like the one for "shiny.file"). This
210 # should only happen once, when the app starts.
211 if (is.null(shinysession$restoreContext)) {
212 bookmarkStore <- getShinyOption("bookmarkStore", default = "disable")
213 if (bookmarkStore == "disable") {
214 # If bookmarking is disabled, use empty context
215 shinysession$restoreContext <- RestoreContext$new()
216 } else {
217 # If there's bookmarked state, save it on the session object
218 shinysession$restoreContext <- RestoreContext$new(msg$data$.clientdata_url_search)
219 shinysession$createBookmarkObservers()
220 }
221 }
222
223
224 msg$data <- applyInputHandlers(msg$data)
225
226 switch(
227 msg$method,
228 init = {
229
230 serverFunc <- withReactiveDomain(NULL, serverFuncSource())
231 if (!identicalFunctionBodies(serverFunc, appvars$server)) {
232 appvars$server <- serverFunc
233 if (!is.null(appvars$server))
234 {
235 # Tag this function as the Shiny server function. A debugger may use this
236 # tag to give this function special treatment.
237 # It's very important that it's appvars$server itself and NOT a copy that
238 # is invoked, otherwise new breakpoints won't be picked up.
239 attr(appvars$server, "shinyServerFunction") <- TRUE
240 registerDebugHook("server", appvars, "Server Function")
241 }
242 }
243
244 # Check for switching into/out of showcase mode
245 if (.globals$showcaseOverride &&
246 exists(".clientdata_url_search", where = msg$data)) {
247 mode <- showcaseModeOfQuerystring(msg$data$.clientdata_url_search)
248 if (!is.null(mode))
249 shinysession$setShowcase(mode)
250 }
251
252 # In shinysession$createBookmarkObservers() above, observers may be
253 # created, which puts the shiny session in busyCount > 0 state. That
254 # prevents the manageInputs here from taking immediate effect, by
255 # default. The manageInputs here needs to take effect though, because
256 # otherwise the bookmark observers won't find the clientData they are
257 # looking for. So use `now = TRUE` to force the changes to be
258 # immediate.
259 #
260 # FIXME: break createBookmarkObservers into two separate steps, one
261 # before and one after manageInputs, and put the observer creation
262 # in the latter. Then add an assertion that busyCount == 0L when
263 # this manageInputs is called.
264 shinysession$manageInputs(msg$data, now = TRUE)
265
266 # The client tells us what singletons were rendered into
267 # the initial page
268 if (!is.null(msg$data$.clientdata_singletons)) {
269 shinysession$singletons <- strsplit(
270 msg$data$.clientdata_singletons, ',')[[1]]
271 }
272
273 local({
274 args <- argsForServerFunc(serverFunc, shinysession)
275
276 withReactiveDomain(shinysession, {
277 otel_span_session_start(domain = shinysession, {
278
279 do.call(
280 # No corresponding ..stacktraceoff; the server func is pure
281 # user code
282 wrapFunctionLabel(appvars$server, "server",
283 ..stacktraceon = TRUE
284 ),
285 args
286 )
287
288 })
289 })
290
291 })
292 },
293 update = {
294 shinysession$manageInputs(msg$data)
295 },
296 shinysession$dispatch(msg)
297 )
298 # The HTTP_GUID, if it exists, is for Shiny Server reporting purposes
299 shinysession$startTiming(ws$request$HTTP_GUID)
300 shinysession$requestFlush()
301
302 # Make httpuv return control to Shiny quickly, instead of waiting
303 # for the usual timeout
304 httpuv::interrupt()
305 })
306 }
307 ws$onMessage(function(binary, msg) {
308 # If unhandled errors occur, make sure they get properly logged
309 withLogErrors(messageHandler(binary, msg))
310 })
311
312 ws$onClose(function() {
313 shinysession$wsClosed()
314 appsByToken$remove(shinysession$token)
315 appsNeedingFlush$remove(shinysession$token)
316 })
317
318 return(TRUE)
319 }
320 )
321 return(appHandlers)
322 }
323
324 # Determine what arguments should be passed to this serverFunc. All server funcs
325 # must take input and output, but clientData (obsolete) and session are
326 # optional.
327 argsForServerFunc <- function(serverFunc, session) {
328 args <- list(input = session$input, output = .createOutputWriter(session))
329
330 paramNames <- names(formals(serverFunc))
331
332 # The clientData and session arguments are optional; check if
333 # each exists
334
335 if ("clientData" %in% paramNames)
336 args$clientData <- session$clientData
337
338 if ("session" %in% paramNames)
339 args$session <- session
340
341 args
342 }
343
344 getEffectiveBody <- function(func) {
345 if (is.null(func))
346 NULL
347 else if (isS4(func) && inherits(func, "functionWithTrace"))
348 body(func@original)
349 else
350 body(func)
351 }
352
353 identicalFunctionBodies <- function(a, b) {
354 identical(getEffectiveBody(a), getEffectiveBody(b))
355 }
356
357 handlerManager <- HandlerManager$new()
358
359 addSubApp <- function(appObj, autoRemove = TRUE) {
360 path <- createUniqueId(16, "/app")
361 appHandlers <- createAppHandlers(appObj$httpHandler, appObj$serverFuncSource)
362
363 # remove the leading / from the path so a relative path is returned
364 # (needed for the case where the root URL for the Shiny app isn't /, such
365 # as portmapped URLs)
366 finalPath <- paste(
367 substr(path, 2, nchar(path)),
368 "/?w=", workerId(),
369 "&__subapp__=1",
370 sep="")
371 handlerManager$addHandler(routeHandler(path, appHandlers$http), finalPath)
372 handlerManager$addWSHandler(routeWSHandler(path, appHandlers$ws), finalPath)
373
374 if (autoRemove) {
375 # If a session is currently active, remove this subapp automatically when
376 # the current session ends
377 onReactiveDomainEnded(getDefaultReactiveDomain(), function() {
378 removeSubApp(finalPath)
379 })
380 }
381
382 return(finalPath)
383 }
384
385 removeSubApp <- function(path) {
386 handlerManager$removeHandler(path)
387 handlerManager$removeWSHandler(path)
388 }
389
390 startApp <- function(appObj, port, host, quiet) {
391 appHandlers <- createAppHandlers(appObj$httpHandler, appObj$serverFuncSource)
392 handlerManager$addHandler(appHandlers$http, "/", tail = TRUE)
393 handlerManager$addWSHandler(appHandlers$ws, "/", tail = TRUE)
394
395 httpuvApp <- handlerManager$createHttpuvApp()
396 httpuvApp$staticPaths <- c(
397 appObj$staticPaths,
398 list(
399 # Always handle /session URLs dynamically, even if / is a static path.
400 "session" = excludeStaticPath(),
401 "shared" = system_file(package = "shiny", "www", "shared")
402 ),
403 .globals$resourcePaths
404 )
405
406 # throw an informative warning if a subdirectory of the
407 # app's www dir conflicts with another resource prefix
408 wwwDir <- httpuvApp$staticPaths[["/"]]$path
409 if (length(wwwDir)) {
410 # although httpuv allows for resource prefixes like 'foo/bar',
411 # we won't worry about conflicts in sub-sub directories since
412 # addResourcePath() currently doesn't allow it
413 wwwSubDirs <- list.dirs(wwwDir, recursive = FALSE, full.names = FALSE)
414 resourceConflicts <- intersect(wwwSubDirs, names(httpuvApp$staticPaths))
415 if (length(resourceConflicts)) {
416 warning(
417 "Found subdirectories of your app's www/ directory that ",
418 "conflict with other resource URL prefixes. ",
419 "Consider renaming these directories: '",
420 paste0("www/", resourceConflicts, collapse = "', '"), "'",
421 call. = FALSE
422 )
423 }
424 }
425
426 # check for conflicts in each pairwise combinations of resource mappings
427 checkResourceConflict <- function(paths) {
428 if (length(paths) < 2) return(NULL)
429 # ensure paths is a named character vector: c(resource_path = local_path)
430 paths <- vapply(paths, function(x) if (inherits(x, "staticPath")) x$path else x, character(1))
431 # get all possible pairwise combinations of paths
432 pair_indices <- utils::combn(length(paths), 2, simplify = FALSE)
433 lapply(pair_indices, function(x) {
434 p1 <- paths[x[1]]
435 p2 <- paths[x[2]]
436 if (identical(names(p1), names(p2)) && (p1 != p2)) {
437 warning(
438 "Found multiple local file paths pointing the same resource prefix: ", names(p1), ". ",
439 "If you run into resource-related issues (e.g. 404 requests), consider ",
440 "using `addResourcePath()` and/or `removeResourcePath()` to manage resource mappings.",
441 call. = FALSE
442 )
443 }
444 })
445 }
446 checkResourceConflict(httpuvApp$staticPaths)
447
448 httpuvApp$staticPathOptions <- httpuv::staticPathOptions(
449 html_charset = "utf-8",
450 headers = list("X-UA-Compatible" = "IE=edge,chrome=1"),
451 validation =
452 if (!is.null(getOption("shiny.sharedSecret"))) {
453 sprintf('"Shiny-Shared-Secret" == "%s"', getOption("shiny.sharedSecret"))
454 } else {
455 character(0)
456 }
457 )
458
459 if (is.numeric(port) || is.integer(port)) {
460 if (!quiet) {
461 hostString <- host
462 if (httpuv::ipFamily(host) == 6L)
463 hostString <- paste0("[", hostString, "]")
464 message('\n', 'Listening on http://', hostString, ':', port)
465 }
466 return(startServer(host, port, httpuvApp))
467 } else if (is.character(port)) {
468 if (!quiet) {
469 message('\n', 'Listening on domain socket ', port)
470 }
471 mask <- attr(port, 'mask')
472 if (is.null(mask)) {
473 stop("`port` is not a valid domain socket (missing `mask` attribute). ",
474 "Note that if you're using the default `host` + `port` ",
475 "configuration (and not domain sockets), then `port` must ",
476 "be numeric, not a string.")
477 }
478 return(startPipeServer(port, mask, httpuvApp))
479 }
480 }
481
482 # Run an application that was created by \code{\link{startApp}}. This
483 # function should normally be called in a \code{while(TRUE)} loop.
484 serviceApp <- function() {
485 timerCallbacks$executeElapsed()
486
487 flushReact()
488 flushPendingSessions()
489
490 # If this R session is interactive, then call service() with a short timeout
491 # to keep the session responsive to user input
492 maxTimeout <- ifelse(interactive(), 100, 1000)
493
494 timeout <- max(1, min(maxTimeout, timerCallbacks$timeToNextEvent(), later::next_op_secs()))
495 service(timeout)
496
497 flushReact()
498 flushPendingSessions()
499 }
500
501 .shinyServerMinVersion <- '0.3.4'
502
503 #' Check whether a Shiny application is running
504 #'
505 #' This function tests whether a Shiny application is currently running.
506 #'
507 #' @return `TRUE` if a Shiny application is currently running. Otherwise,
508 #' `FALSE`.
509 #' @export
510 isRunning <- function() {
511 !is.null(getCurrentAppState())
512 }
513
514
515 # Returns TRUE if we're running in Shiny Server or other hosting environment,
516 # otherwise returns FALSE.
517 inShinyServer <- function() {
518 nzchar(Sys.getenv('SHINY_PORT'))
519 }
520
521 # This check was moved out of the main function body because of an issue with
522 # the RStudio debugger. (#1474)
523 isEmptyMessage <- function(msg) {
524 identical(as.raw(c(0x03, 0xe9)), msg)
525 }