Debian Codegraph @

R/app.R

raw
1 #' Create or stop a local web application
2 #'
3 #' Create a local web application based on R's internal httpd.
4 #'
5 #' `new_app()` has two modes:
6 #'
7 #' - `name = ''`: start an app behind a lightweight proxy at
8 #' `http://host:PORT/`, forwarding to R's internal httpd path
9 #' `/custom/xfun:PORT/`.
10 #' - `name != ''`: register a legacy app directly on R's internal httpd at
11 #' `http://127.0.0.1:BACKEND/custom/name/` (compatible with older versions).
12 #'
13 #' `stop_app()` deregisters one or more running apps.
14 #' @param name App name (a character string). Use `name = ''` to serve the app
15 #' at the root URL `http://host:PORT/` via the proxy. If `name` is non-empty,
16 #' the app is served directly by R's internal httpd at `/custom/name/`. Each
17 #' name must be unique; calling `new_app()` with an existing name replaces
18 #' that app. For `stop_app()`, a character vector of app names to stop;
19 #' defaults to all running apps.
20 #' @param handler A function with signature `function(path, query, post,
21 #' headers)` that handles HTTP requests and returns a response list.
22 #' @param open Whether to open the app URL in a browser, or a function to open
23 #' it. In non-interactive sessions this also controls whether the call
24 #' blocks: passing `open = FALSE` explicitly suppresses both browser-opening
25 #' and blocking.
26 #' @param host Bind address for the proxy (`"127.0.0.1"` or `"0.0.0.0"`). Only
27 #' used when `name = ''`.
28 #' @param port Candidate proxy ports when `name = ''`. The first available port
29 #' is selected (falling back to [random_port()] if needed). Ignored when
30 #' `name != ''`.
31 #' @return `new_app()` returns the app URL invisibly. `stop_app()` returns
32 #' nothing.
33 #' @export
34 new_app = function(
35 name, handler, open = interactive(), host = '127.0.0.1', port = NULL
36 ) {
37 backend = .httpd_port()
38
39 # Replace any existing app with the same name.
40 if (name %in% names(.proxy$apps)) stop_app(name)
41
42 if (name == '') {
43 port = .find_proxy_port(port, names(.proxy$help))
44 key = paste0('xfun:', port)
45 # register the backend handler before starting the proxy, so the proxy never
46 # forwards a request to a not-yet-registered handler (R's httpd would return
47 # its "httpd error" page, with a 200 status, during that window)
48 assign(key, .make_app_handler(paste0('/custom/xfun:', port), handler, getwd()), envir = .httpd_env())
49 slot = tryCatch(
50 proxy_start(as.integer(port), as.integer(backend), host = host),
51 error = function(e) { rm_vars(key, .httpd_env()); stop(e) }
52 )
53 .proxy$apps[[name]] = list(type = 'proxy', slot = slot, key = key, port = port)
54 url_host = if (host == '0.0.0.0') '127.0.0.1' else host
55 url = sprintf('http://%s:%d/', url_host, port)
56 } else {
57 key = as.character(name)
58 assign(key, .make_app_handler(paste0('/custom/', name), handler, getwd()), envir = .httpd_env())
59 .proxy$apps[[name]] = list(type = 'httpd', key = key)
60 url = sprintf('http://127.0.0.1:%d/custom/%s/', backend, name)
61 }
62
63 if (isTRUE(open)) open = getOption('viewer', browseURL)
64 if (is.function(open)) open(url)
65
66 if (!interactive() && !isFALSE(open)) {
67 on.exit(stop_app(name), add = TRUE)
68 message('Serving at ', url, ' (press Ctrl+C to stop)')
69 tryCatch(
70 while (TRUE) Sys.sleep(1),
71 interrupt = function(e) invisible(NULL)
72 )
73 }
74 invisible(url)
75 }
76
77 #' @rdname new_app
78 #' @export
79 stop_app = function(name = names(.proxy$apps)) {
80 if (!missing(name)) name = intersect(name, names(.proxy$apps))
81 for (n in name) {
82 idx = match(n, names(.proxy$apps))
83 app = .proxy$apps[[idx]]
84 rm_vars(app$key, .httpd_env())
85 .proxy$apps[[idx]] = NULL
86 if (app$type == 'proxy') proxy_stop(app$slot)
87 }
88 }
89
90 # start an internal passthrough proxy for R's help pages.
91 help_proxy = function(port = NULL, host = '0.0.0.0') {
92 p1 = .httpd_port()
93 p2 = .find_proxy_port(port)
94 old = .proxy$help[[as.character(p2)]]
95 if (!is.null(old)) proxy_stop(old)
96 slot = proxy_start(as.integer(p2), as.integer(p1), TRUE, host)
97 .proxy$help[[as.character(p2)]] = slot
98 u = sprintf('http://127.0.0.1:%d/doc/html/index.html', p2)
99 message('Proxy started at ', u)
100 invisible(u)
101 }
102
103 #' Find a random available TCP port
104 #'
105 #' Find an available TCP port, starting with `port`, then sampling from
106 #' 3000--8000 (excluding ports known to be blocked by Chrome).
107 #' @param port Default port to try first.
108 #' @param n Number of additional random ports to try.
109 #' @param exclude Integer vector of ports to exclude from the search.
110 #' @param error Whether to signal an error (default) or return `NULL` when no
111 #' port is found.
112 #' @return An integer port number. When `error = TRUE` (default), signals an
113 #' error if no port is found; when `error = FALSE`, returns `NULL`.
114 #' @export
115 random_port = function(port = 4321L, n = 20L, exclude = NULL, error = TRUE) {
116 # exclude ports considered unsafe by Chrome http://superuser.com/a/188070
117 unsafe = c(3659, 4045, 5060, 5061, 6000, 6566, 6665:6669, 6697)
118 ports = sample(setdiff(3000:8000, unsafe), n)
119 ports = setdiff(c(port, ports), exclude)
120 for (p in ports) if (.port_available(p)) return(p)
121 if (error) stop2("Cannot find an available TCP port")
122 }
123
124 # ---- internal helpers -------------------------------------------------------
125
126 # Start R's internal httpd; return its port (or -1 on failure).
127 .httpd_port = function() {
128 if (is.null(getOption('help.ports'))) {
129 options(help.ports = 4321 + 1:30); on.exit(options(help.ports = NULL))
130 }
131 p = suppressMessages(tools::startDynamicHelp(NA))
132 if (p <= 0L) stop2("Failed to start R's internal httpd.")
133 p
134 }
135
136 # Environment where R's httpd looks up /custom/* handlers.
137 .httpd_env = function() getFromNamespace('.httpd.handlers.env', 'tools')
138
139 # Internal proxy state.
140 .proxy = new.env(parent = emptyenv())
141 .proxy$apps = list() # app name → list(type, key, slot?)
142 .proxy$help = list() # help proxy port → slot index
143
144 # Find an available proxy port without starting the proxy.
145 .proxy_app_ports = function() {
146 vapply(Filter(function(x) x$type == 'proxy', .proxy$apps), `[[`, integer(1), 'port')
147 }
148
149 .find_proxy_port = function(candidates = NULL, exclude = integer()) {
150 if (is.null(candidates)) candidates = 4321 + 1:30
151 exclude = unique(c(as.integer(exclude), .proxy_app_ports(), as.integer(names(.proxy$help))))
152 candidates = setdiff(candidates, exclude)
153 for (p in candidates) if (.port_available(p)) return(as.integer(p))
154 if (!is.null(p <- random_port(error = FALSE, exclude = c(candidates, exclude))))
155 return(p)
156 stop2(
157 "No available proxy port found (tried candidates ",
158 paste(unique(candidates), collapse = ', '),
159 " and random fallback ports)."
160 )
161 }
162
163 # Start a proxy instance on `port` forwarding to `backend_port`.
164 # passthrough = TRUE: forward all request paths verbatim (use this to expose
165 # the full R httpd server, e.g. on host = "0.0.0.0" for LAN access).
166 # passthrough = FALSE (default): rewrite /path to /custom/xfun:PORT/path.
167 # host: bind address; "0.0.0.0" to listen on all interfaces.
168 proxy_start = function(port, backend_port, passthrough = FALSE, host = '127.0.0.1') {
169 port = as.integer(port)
170 backend_port = as.integer(backend_port)
171 passthrough = isTRUE(passthrough)
172 host = as.character(host)[1]
173
174 bg = Rscript_bg(.proxy_run, list(
175 port = port, backend_port = backend_port, passthrough = passthrough, host = host
176 ))
177 if (!.proxy_wait_ready(port, host)) {
178 if (isTRUE(bg$is_alive())) try(proc_kill(bg$pid), silent = TRUE)
179 stop2("Failed to start proxy on port ", port, ".")
180 }
181 paste0('r:', bg$pid)
182 }
183
184 # Stop the proxy instance identified by its slot.
185 proxy_stop = function(slot) {
186 if (is.character(slot) && length(slot) == 1L && startsWith(slot, 'r:')) {
187 pid = sub('^r:', '', slot)
188 if (grepl('^[0-9]+$', pid)) try_silent(proc_kill(as.integer(pid)))
189 }
190 }
191
192 # Coerce body/headers-like argument to a raw vector.
193 .as_raw = function(x) {
194 if (is.null(x) || length(x) == 0L) raw(0) else {
195 if (is.raw(x)) x else charToRaw(x[[1L]])
196 }
197 }
198
199 # Check if a TCP port is truly available: nothing must be listening on it, and
200 # we must be able to bind a server socket. The serverSocket() bind alone is
201 # insufficient because some servers (e.g. httpuv) use SO_REUSEADDR/SO_REUSEPORT,
202 # allowing a second bind to succeed even when they already hold the port.
203 # Probing with a client connection detects any active listener regardless.
204 .port_available = function(port) {
205 port = as.integer(port)
206 if (is.na(port)) return(FALSE)
207 # If a client can connect, something is already listening → not available.
208 con = suppressWarnings(tryCatch(
209 socketConnection('127.0.0.1', port = port, open = 'r+b', blocking = FALSE, timeout = 0.5),
210 error = function(e) NULL
211 ))
212 if (!is.null(con)) { try_silent(close(con)); return(FALSE) }
213 # Confirm we can actually bind the port as a server.
214 server_socket = base::serverSocket
215 s = tryCatch(server_socket(port), error = function(e) NULL)
216 if (is.null(s)) FALSE else { close(s); TRUE }
217 }
218
219 # Build an R httpd handler closure.
220 .make_app_handler = function(prefix, fn, wd) {
221 function(path, query = NULL, body = NULL, headers = NULL) {
222 real = if (startsWith(path, prefix)) substring(path, nchar(prefix) + 1L) else path
223 real = sub('^/', '', real)
224 if (real == '') real = '.'
225 q = if (is.null(query)) .parse_xfun_query(headers) else query
226 in_dir(wd, fn(real, q, .as_raw(body), .as_raw(headers)))
227 }
228 }
229
230 .stop_help_proxy = function(port = names(.proxy$help)) {
231 if (!missing(port)) port = intersect(as.character(port), names(.proxy$help))
232 for (p in port) {
233 proxy_stop(.proxy$help[[p]])
234 .proxy$help[[p]] = NULL
235 }
236 }
237
238 .proxy_connect_host = function(host) {
239 host = as.character(host)[1]
240 # server may bind all interfaces (0.0.0.0), but local readiness checks should
241 # use loopback for a deterministic self-connection target.
242 if (host == '0.0.0.0') '127.0.0.1' else host
243 }
244
245 # Poll until the proxy port is accepting connections (or give up after timeout).
246 .proxy_wait_ready = function(port, host, tries = 100L, delay = 0.1) {
247 host = .proxy_connect_host(host)
248 for (i in seq_len(tries)) {
249 con = tryCatch(
250 socketConnection(host = host, port = port, open = 'r+b', blocking = TRUE, timeout = 1),
251 error = function(e) NULL
252 )
253 if (!is.null(con)) {
254 close(con)
255 return(TRUE)
256 }
257 Sys.sleep(delay)
258 }
259 FALSE
260 }
261
262 # Main proxy loop running in a background R process.
263 .proxy_run = function(port, backend_port, passthrough = FALSE, host = '127.0.0.1') {
264 server_socket = base::serverSocket
265 socket_accept = base::socketAccept
266
267 listener = server_socket(port)
268 on.exit(close(listener), add = TRUE)
269
270 # Exit when the backend httpd is gone (e.g., parent R process died).
271 n_fail = 0L
272 backend_alive = function() {
273 con = suppressWarnings(tryCatch(
274 socketConnection('127.0.0.1', port = backend_port, open = 'r+b',
275 blocking = TRUE, timeout = 1),
276 error = function(e) NULL
277 ))
278 if (is.null(con)) return(FALSE)
279 close(con)
280 TRUE
281 }
282
283 repeat {
284 con = tryCatch(
285 socket_accept(listener, blocking = FALSE, open = 'r+b', timeout = 1),
286 error = function(e) NULL
287 )
288 if (is.null(con)) {
289 n_fail = n_fail + 1L
290 if (n_fail >= 5L && !backend_alive()) break
291 next
292 }
293 n_fail = 0L
294 try_silent(.proxy_forward(con, port, backend_port, passthrough))
295 try_silent(close(con))
296 }
297 }
298
299 # Read a client request, forward it to backend httpd, and relay the response.
300 .proxy_forward = function(client, port, backend_port, passthrough = FALSE) {
301 req = .proxy_read_request(client)
302 if (is.null(req)) return()
303
304 path = req$path
305 path2 = if (isTRUE(passthrough)) path else sprintf('/custom/xfun:%d%s', port, path)
306 q_pos = regexpr('\\?', path)[1L]
307 query = if (q_pos > 0L) substring(path, q_pos + 1L) else ''
308
309 backend = tryCatch(
310 socketConnection(host = '127.0.0.1', port = backend_port, open = 'r+b', blocking = FALSE, timeout = 5),
311 error = function(e) NULL
312 )
313 if (is.null(backend)) return()
314 on.exit(try(close(backend), silent = TRUE), add = TRUE)
315
316 headers = req$headers
317 if (length(headers)) {
318 keep = !grepl('^(connection|keep-alive|proxy-connection):', headers, ignore.case = TRUE)
319 headers = headers[keep]
320 }
321 if (nzchar(query)) headers = c(headers, paste0('X-Xfun-Query: ', query))
322 txt = paste(c(sprintf('%s %s HTTP/1.0', req$method, path2), headers, '', ''), collapse = '\r\n')
323 writeBin(charToRaw(txt), backend)
324 if (length(req$body)) writeBin(req$body, backend)
325 flush(backend)
326
327 buf = raw(0); clen = NA_integer_; sep_end = NA_integer_
328 for (i in seq_len(200L)) {
329 Sys.sleep(0.05)
330 ready = tryCatch(socketSelect(list(backend), write = FALSE, timeout = 0), error = function(e) FALSE)
331 if (!isTRUE(ready[1L])) next
332 x = tryCatch(readBin(backend, raw(), 65536L), error = function(e) raw(0))
333 if (!length(x)) break
334 buf = c(buf, x)
335 if (is.na(sep_end)) {
336 s = tryCatch(rawToChar(buf), error = function(e) '')
337 m = regexpr('\r\n\r\n|\n\n', s, perl = TRUE)
338 if (m[1L] > 0L) {
339 sep_end = m[1L] + attr(m, 'match.length') - 1L
340 cl_m = regexpr('(?i)content-length:[ \t]*([0-9]+)', s, perl = TRUE)
341 if (cl_m[1L] > 0L)
342 clen = as.integer(trimws(sub('(?i).*:', '', regmatches(s, cl_m), perl = TRUE)))
343 }
344 }
345 if (!is.na(sep_end) && !is.na(clen) && (length(buf) - sep_end) >= clen) break
346 }
347 if (length(buf)) { writeBin(buf, client); flush(client) }
348 }
349
350 # Parse one HTTP request from a non-blocking socket connection.
351 # Uses socketSelect() polling so readBin() returns immediately with whatever
352 # bytes are available without blocking for the full buffer size.
353 .proxy_read_request = function(con) {
354 buf = raw(0); head_end = 0L; sep_len = 0L
355 for (i in seq_len(200L)) { # up to 200 * 0.05 s = 10 s
356 Sys.sleep(0.05)
357 ready = tryCatch(socketSelect(list(con), write = FALSE, timeout = 0), error = function(e) FALSE)
358 if (!isTRUE(ready[1L])) next
359 x = tryCatch(readBin(con, raw(), 65536L), error = function(e) raw(0))
360 if (!length(x)) return(NULL)
361 buf = c(buf, x)
362 s = tryCatch(rawToChar(buf), error = function(e) '')
363 m = regexpr('\r\n\r\n|\n\n', s, perl = TRUE)
364 if (m[1L] > 0L) { head_end = m[1L]; sep_len = attr(m, 'match.length'); break }
365 if (length(buf) >= 65536L) return(NULL)
366 }
367 if (head_end == 0L) return(NULL)
368
369 hs = substring(rawToChar(buf), 1L, head_end + sep_len - 1L)
370 hs = sub('\r\n\r\n$|\n\n$', '', hs, perl = TRUE)
371 lines = strsplit(hs, '\r\n|\n', perl = TRUE)[[1L]]
372 if (!length(lines)) return(NULL)
373
374 req = strsplit(lines[[1L]], ' ', fixed = TRUE)[[1L]]
375 req = req[nzchar(req)]
376 if (length(req) < 2L) return(NULL)
377 method = req[[1L]]; path = req[[2L]]; headers = lines[-1L]
378
379 clen = 0L
380 if (length(headers)) {
381 i = grep('^content-length:', headers, ignore.case = TRUE)
382 if (length(i)) {
383 v = trimws(sub('^[^:]*:', '', headers[[i[1L]]]))
384 if (grepl('^[0-9]+$', v)) clen = as.integer(v)
385 }
386 if (is.na(clen) || clen < 0L) clen = 0L
387 }
388 body_start = head_end + sep_len
389 body0 = if (body_start <= length(buf)) buf[body_start:length(buf)] else raw(0)
390 body = if (length(body0) < clen)
391 c(body0, tryCatch(readBin(con, raw(), clen - length(body0)), error = function(e) raw(0)))
392 else body0[seq_len(clen)]
393 list(method = method, path = path, headers = headers, body = body)
394 }
395
396 # Parse the X-Xfun-Query header (added by the proxy) into a named, URL-decoded
397 # character vector. Falls back to character(0) when absent.
398 .parse_xfun_query = function(headers) {
399 if (is.null(headers) || length(headers) == 0L) return(character(0))
400 hs = if (is.raw(headers)) rawToChar(headers) else paste(headers, collapse = '\n')
401 # Find the X-Xfun-Query line.
402 qs = ''
403 for (line in strsplit(hs, '\n', fixed = TRUE)[[1L]]) {
404 line = sub('\r$', '', line)
405 if (startsWith(line, 'X-Xfun-Query: ')) {
406 qs = substring(line, nchar('X-Xfun-Query: ') + 1L)
407 break
408 }
409 }
410 if (qs == '') return(character(0))
411 pairs = Filter(nzchar, strsplit(qs, '&', fixed = TRUE)[[1L]])
412 if (!length(pairs)) return(character(0))
413 keys = vals = character(length(pairs))
414 for (i in seq_along(pairs)) {
415 kv = strsplit(pairs[[i]], '=', fixed = TRUE)[[1L]]
416 keys[[i]] = utils::URLdecode(kv[[1L]])
417 vals[[i]] = if (length(kv) >= 2L)
418 utils::URLdecode(paste(kv[-1L], collapse = '=')) else ''
419 }
420 setNames(vals, keys)
421 }
422
423 #' Get data from a REST API
424 #'
425 #' Read data from a REST API and optionally with an authorization token in the
426 #' request header. The function `rest_api_raw()` returns the raw text of
427 #' the response, and `rest_api()` will parse the response with
428 #' `jsonlite::fromJSON()` (assuming that the response is in the JSON
429 #' format).
430 #'
431 #' These functions are simple wrappers based on [url()] and
432 #' [read_utf8()]. Specifically, the `headers` argument is
433 #' passed to `url()`, and `read_utf8()` will send a \samp{GET} request
434 #' to the API server. This means these functions only support the \samp{GET}
435 #' method. If you need to use other HTTP methods (such as \samp{POST}), you have
436 #' to use other packages such as \pkg{curl} and \pkg{httr}.
437 #' @param ... Arguments to be passed to `rest_api_raw()`.
438 #' @return A character vector (the raw JSON response) or an R object parsed from
439 #' the JSON text.
440 #' @export
441 #' @examplesIf interactive()
442 #' # a normal GET request
443 #' xfun::rest_api('https://mockhttp.org', '/get')
444 #' xfun::rest_api_raw('https://mockhttp.org', '/get')
445 #'
446 #' # send the request with an auth header
447 #' xfun::rest_api('https://mockhttp.org', '/headers', 'OPEN SESAME!')
448 #'
449 #' # with query parameters
450 #' xfun::rest_api('https://mockhttp.org', '/response-headers', params = list(foo = 'bar'))
451 #'
452 #' # get the rate limit info from GitHub
453 #' xfun::github_api('/rate_limit')
454 rest_api = function(...) {
455 res = rest_api_raw(...)
456 jsonlite::fromJSON(res, simplifyVector = FALSE)
457 }
458
459 #' @param root The API root URL.
460 #' @param endpoint The API endpoint.
461 #' @param token A named character string (e.g., `c(token = "xxxx")`), which
462 #' will be used to create an authorization header of the form
463 #' \samp{Authorization: NAME TOKEN} for the API call, where \samp{NAME} is the
464 #' name of the string and \samp{TOKEN} is the string. If the string does not
465 #' have a name, \samp{Basic} will be used as the default name.
466 #' @param params A list of query parameters to be sent with the API call.
467 #' @param headers A named character vector of HTTP headers, e.g., `c(Accept
468 #' = "application/vnd.github.v3+json")`.
469 #' @rdname rest_api
470 #' @export
471 rest_api_raw = function(root, endpoint, token = '', params = list(), headers = NULL) {
472 if (is.null(names(token))) names(token) = 'Basic'
473 endpoint = sub('^/?', '/', endpoint) # make sure it has a leading /
474 url2 = if ('headers' %in% names(formals(url))) url else stop2(
475 "The url() function does not support the 'headers' argument. Please upgrade R (>= 3.6.0)."
476 )
477 con = url2(
478 paste0(root, endpoint, query_params(.list = params)), encoding = 'UTF-8',
479 headers = c(
480 headers, if (token != '') c(Authorization = sprintf('%s %s', names(token), token))
481 )
482 )
483 on.exit(close(con), add = TRUE)
484 raw_string(suppressWarnings(read_utf8(con)))
485 }