Debian Codegraph @

R/server.R

raw
1 # nanonext - HTTP/WebSocket Server Interface ------------------------------------
2
3 #' Create HTTP/WebSocket Server
4 #'
5 #' Creates a server that can handle HTTP requests and WebSocket connections.
6 #'
7 #' @param url URL to listen on (e.g., "http://127.0.0.1:8080").
8 #' @param handlers A handler or list of handlers created with [handler()], [handler_ws()], etc.
9 #' @param tls TLS configuration for HTTPS/WSS, created via [tls_config()].
10 #'
11 #' @return A nanoServer object with methods:
12 #'
13 #' - `$start()` - Start accepting connections
14 #' - `$close()` - Stop and release all resources
15 #' - `$serve()` - Start and block, processing requests via the \pkg{later}
16 #' event loop until interrupted (e.g., Ctrl+C). The server is automatically
17 #' closed on exit
18 #' - `$url` - The server URL
19 #'
20 #' @details
21 #' This function leverages NNG's shared HTTP server architecture. When both
22 #' HTTP handlers and WebSocket handlers are provided, they share the same
23 #' underlying server and port. WebSocket handlers automatically handle
24 #' the HTTP upgrade handshake and all WebSocket framing (RFC 6455).
25 #'
26 #' WebSocket and streaming callbacks are executed on R's main thread via the
27 #' \pkg{later} package. To process callbacks, you must run the event loop
28 #' (e.g., using `later::run_now()` in a loop), or use `$serve()` which
29 #' handles this automatically.
30 #'
31 #' Requires the \pkg{later} package.
32 #'
33 #' @examplesIf interactive() && requireNamespace("later", quietly = TRUE)
34 #' # Simple HTTP server
35 #' server <- http_server(
36 #' url = "http://127.0.0.1:8080",
37 #' handlers = list(
38 #' handler("/", function(req) {
39 #' list(status = 200L, body = "Hello, World!")
40 #' }),
41 #' handler("/api/data", function(req) {
42 #' list(
43 #' status = 200L,
44 #' headers = c("Content-Type" = "application/json"),
45 #' body = '{"value": 42}'
46 #' )
47 #' })
48 #' )
49 #' )
50 #' server$start()
51 #' # Run event loop: repeat later::run_now(Inf)
52 #' server$close()
53 #'
54 #' # HTTP + WebSocket server
55 #' server <- http_server(
56 #' url = "http://127.0.0.1:8080",
57 #' handlers = list(
58 #' handler("/", function(req) {
59 #' list(status = 200L, body = "<html>...</html>")
60 #' }),
61 #' handler_ws("/ws", function(ws, data) {
62 #' ws$send(data) # Echo
63 #' }, textframes = TRUE)
64 #' )
65 #' )
66 #'
67 #' # Multiple WebSocket endpoints
68 #' server <- http_server(
69 #' url = "http://127.0.0.1:8080",
70 #' handlers = list(
71 #' handler_ws("/echo", function(ws, data) ws$send(data)),
72 #' handler_ws("/upper", function(ws, data) ws$send(toupper(data)), textframes = TRUE)
73 #' )
74 #' )
75 #'
76 #' # HTTPS server with self-signed certificate
77 #' cert <- write_cert(cn = "127.0.0.1")
78 #' cfg <- tls_config(server = cert$server)
79 #' server <- http_server(
80 #' url = "https://127.0.0.1:8443",
81 #' handlers = list(
82 #' handler("/", function(req) list(status = 200L, body = "Secure!"))
83 #' ),
84 #' tls = cfg
85 #' )
86 #' server$start()
87 #'
88 #' # Send async request and run event loop
89 #' aio <- ncurl_aio(
90 #' "https://127.0.0.1:8443/",
91 #' tls = tls_config(client = cert$client),
92 #' timeout = 2000
93 #' )
94 #' while (unresolved(aio)) later::run_now(0.1)
95 #'
96 #' aio$status
97 #' aio$data
98 #'
99 #' server$close()
100 #'
101 #' @export
102 #'
103 http_server <- function(url, handlers = list(), tls = NULL) {
104 if (is.integer(handlers$type))
105 handlers <- list(handlers)
106 srv <- .Call(rnng_http_server_create, url, handlers, tls)
107 attr(srv, "start") <- function() {
108 invisible(.Call(rnng_http_server_start, srv))
109 }
110 attr(srv, "close") <- function() {
111 invisible(.Call(rnng_http_server_close, srv))
112 }
113 attr(srv, "serve") <- function() {
114 on.exit(.Call(rnng_http_server_close, srv))
115 .Call(rnng_http_server_start, srv)
116 cat(sprintf("Serving at %s - press Ctrl+C to stop\n", attr(srv, "url")))
117 repeat later::run_now(Inf)
118 }
119 srv
120 }
121
122 #' Create HTTP Handler
123 #'
124 #' Creates an HTTP route handler for use with [http_server()].
125 #'
126 #' @param path URI path to match (e.g., "/api/data", "/users").
127 #' @param callback Function to handle requests. Receives a list with:
128 #'
129 #' - `method` - HTTP method (character)
130 #' - `uri` - Request URI (character)
131 #' - `headers` - Named character vector of headers
132 #' - `body` - Request body (raw vector)
133 #'
134 #' Should return a list with:
135 #'
136 #' - `status` - HTTP status code (integer, default 200)
137 #' - `headers` - Response headers as a named character vector, e.g.
138 #' `c("Content-Type" = "application/json")` (optional)
139 #' - `body` - Response body (character or raw)
140 #' @param method \[default "GET"\] HTTP method to match (e.g., "GET", "POST",
141 #' "PUT", "DELETE"). Use `"*"` to match any method.
142 #' @param prefix \[default FALSE\] Logical, if TRUE matches path as a prefix
143 #' (e.g., "/api" will match "/api/users", "/api/items", etc.).
144 #'
145 #' @return A handler object for use with [http_server()].
146 #'
147 #' @details If the callback throws an error, a 500 Internal Server Error
148 #' response is returned to the client.
149 #'
150 #' @seealso [handler_ws()] for WebSocket handlers. Static handlers:
151 #' [handler_file()], [handler_directory()], [handler_inline()],
152 #' [handler_redirect()].
153 #'
154 #' @examples
155 #' # Simple GET handler
156 #' h1 <- handler("/hello", function(req) {
157 #' list(status = 200L, body = "Hello!")
158 #' })
159 #'
160 #' # POST handler that echoes the request body
161 #' h2 <- handler("/echo", function(req) {
162 #' list(status = 200L, body = req$body)
163 #' }, method = "POST")
164 #'
165 #' # Catch-all handler for a path prefix
166 #' h3 <- handler("/static", function(req) {
167 #' # Serve static files under /static/*
168 #' }, method = "*", prefix = TRUE)
169 #'
170 #' @export
171 #'
172 handler <- function(path, callback, method = "GET", prefix = FALSE) {
173 list(type = 1L, path = path, callback = callback, method = method, prefix = prefix)
174 }
175
176 #' Create WebSocket Handler
177 #'
178 #' Creates a WebSocket handler for use with [http_server()].
179 #'
180 #' @param path URI path for WebSocket connections (e.g., "/ws").
181 #' @param on_message Function called when a message is received.
182 #' Signature: `function(ws, data)` where `ws` is the connection
183 #' object and `data` is the message. Use `ws$send()` to send
184 #' responses; the return value is ignored.
185 #' @param on_open \[default NULL\] Function called when a connection opens.
186 #' Signature: `function(ws, req)` where `req` is a list with `uri`
187 #' (character) and `headers` (named character vector) from the HTTP upgrade
188 #' request.
189 #' @param on_close \[default NULL\] Function called when a connection closes.
190 #' Signature: `function(ws)`
191 #' @param textframes \[default FALSE\] Logical, use text frames instead of binary.
192 #' When TRUE: incoming `data` is character, outgoing data should be character.
193 #' When FALSE: incoming `data` is raw vector, outgoing data should be raw vector.
194 #'
195 #' @return A handler object for use with [http_server()].
196 #'
197 #' @section Connection Object:
198 #' The `ws` object passed to callbacks has the following fields and methods:
199 #'
200 #' - `ws$send(data)`: Send a message to the client. `data` can be
201 #' a raw vector or character string. Returns 0 on success, or an error code
202 #' on failure (e.g., if the connection is closed).
203 #' - `ws$close()`: Close the connection.
204 #' - `ws$id`: Unique integer identifier for this connection. No two
205 #' connections on the same server will share an ID, even across different
206 #' handlers, making IDs safe to use as keys in a shared data structure.
207 #'
208 #' @examples
209 #' # Simple echo server
210 #' h <- handler_ws("/ws", function(ws, data) ws$send(data))
211 #'
212 #' # With connection tracking
213 #' clients <- list()
214 #' h <- handler_ws(
215 #' "/chat",
216 #' on_message = function(ws, data) {
217 #' # Broadcast to all
218 #' for (client in clients) client$send(data)
219 #' },
220 #' on_open = function(ws, req) {
221 #' clients[[as.character(ws$id)]] <<- ws
222 #' },
223 #' on_close = function(ws) {
224 #' clients[[as.character(ws$id)]] <<- NULL
225 #' },
226 #' textframes = TRUE
227 #' )
228 #'
229 #' @export
230 #'
231 handler_ws <- function(path, on_message, on_open = NULL, on_close = NULL,
232 textframes = FALSE) {
233 list(type = 2L, path = path, on_message = on_message, on_open = on_open,
234 on_close = on_close, textframes = textframes)
235 }
236
237 #' Create Static File Handler
238 #'
239 #' Creates an HTTP handler that serves a single file. NNG handles MIME type
240 #' detection automatically.
241 #'
242 #' @param path URI path to match (e.g., "/favicon.ico").
243 #' @param file Path to the file to serve.
244 #' @param prefix \[default FALSE\] Logical, if TRUE matches path as a prefix.
245 #'
246 #' @return A handler object for use with [http_server()].
247 #'
248 #' @examplesIf interactive()
249 #' h <- handler_file("/favicon.ico", "~/favicon.ico")
250 #'
251 #' @export
252 #'
253 handler_file <- function(path, file, prefix = FALSE) {
254 if (!file.exists(file))
255 warning("file does not exist: ", file)
256 list(type = 3L, path = path, file = normalizePath(file, mustWork = FALSE),
257 prefix = prefix)
258 }
259
260 #' Create Static Directory Handler
261 #'
262 #' Creates an HTTP handler that serves files from a directory tree. NNG handles
263 #' MIME type detection automatically.
264 #'
265 #' @param path URI path prefix (e.g., "/static"). Requests to "/static/foo.js"
266 #' will serve "directory/foo.js".
267 #' @param directory Path to the directory to serve.
268 #'
269 #' @return A handler object for use with [http_server()].
270 #'
271 #' @details
272 #' Directory handlers automatically match all paths under the prefix (prefix
273 #' matching is implicit). The URI path is mapped to the filesystem:
274 #'
275 #' - Request to "/static/css/style.css" serves "directory/css/style.css"
276 #' - Request to "/static/" serves "directory/index.html" if it exists
277 #'
278 #' Note: The trailing slash behavior depends on how clients make requests.
279 #' A request to "/static" (no trailing slash) will not automatically redirect
280 #' to "/static/". Consider using [handler_redirect()] if you need this behavior.
281 #'
282 #' @examplesIf interactive()
283 #' h <- handler_directory("/static", "www/assets")
284 #'
285 #' @export
286 #'
287 handler_directory <- function(path, directory) {
288 if (!dir.exists(directory))
289 warning("directory does not exist: ", directory)
290 list(type = 4L, path = path,
291 directory = normalizePath(directory, mustWork = FALSE))
292 }
293
294 #' Create Inline Static Content Handler
295 #'
296 #' Creates an HTTP handler that serves in-memory static content. Useful for
297 #' small files like robots.txt or inline JSON/HTML.
298 #'
299 #' @param path URI path to match (e.g., "/robots.txt").
300 #' @param data Content to serve. Character data is converted to raw bytes.
301 #' @param content_type MIME type (e.g., "text/plain", "application/json").
302 #' Defaults to "application/octet-stream" if NULL.
303 #' @param prefix \[default FALSE\] Logical, if TRUE matches path as a prefix.
304 #'
305 #' @return A handler object for use with [http_server()].
306 #'
307 #' @examples
308 #' h1 <- handler_inline("/robots.txt", "User-agent: *\nDisallow:",
309 #' content_type = "text/plain")
310 #' h2 <- handler_inline("/health", '{"status":"ok"}',
311 #' content_type = "application/json")
312 #'
313 #' @export
314 #'
315 handler_inline <- function(path, data, content_type = NULL, prefix = FALSE) {
316 list(type = 5L, path = path, data = data, content_type = content_type,
317 prefix = prefix)
318 }
319
320 #' Create HTTP Redirect Handler
321 #'
322 #' Creates an HTTP handler that returns a redirect response.
323 #'
324 #' @param path URI path to match (e.g., "/old-page").
325 #' @param location URL to redirect to. Can be relative (e.g., "/new-page") or
326 #' absolute (e.g., "https://example.com/page").
327 #' @param status HTTP redirect status code. Must be one of:
328 #'
329 #' - 301 - Moved Permanently
330 #' - 302 - Found (default)
331 #' - 303 - See Other
332 #' - 307 - Temporary Redirect
333 #' - 308 - Permanent Redirect
334 #' @param prefix \[default FALSE\] Logical, if TRUE matches path as a prefix.
335 #'
336 #' @return A handler object for use with [http_server()].
337 #'
338 #' @examples
339 #' # Permanent redirect
340 #' h1 <- handler_redirect("/old", "/new", status = 301L)
341 #'
342 #' # Redirect bare path to trailing slash
343 #' h2 <- handler_redirect("/app", "/app/")
344 #'
345 #' @export
346 #'
347 handler_redirect <- function(path, location, status = 302L, prefix = FALSE) {
348 status <- as.integer(status)
349 if (!status %in% c(301L, 302L, 303L, 307L, 308L))
350 stop("redirect status must be 301, 302, 303, 307, or 308")
351 list(type = 6L, path = path, location = location, status = status, prefix = prefix)
352 }
353
354 #' @rdname close
355 #' @method close nanoServer
356 #' @export
357 #'
358 close.nanoServer <- function(con, ...) invisible(.Call(rnng_http_server_close, con))
359
360 #' @export
361 #'
362 print.nanoServer <- function(x, ...) {
363 cat("< nanoServer >\n")
364 cat(" - url:", attr(x, "url"), "\n")
365 cat(" - state:", attr(x, "state"), "\n")
366 invisible(x)
367 }
368
369 #' @export
370 #'
371 print.nanoWsConn <- function(x, ...) {
372 cat("< nanoWsConn >\n")
373 cat(" - id:", attr(x, "id"), "\n")
374 invisible(x)
375 }
376
377 #' @export
378 #'
379 `$.nanoWsConn` <- function(x, name) {
380 switch(name,
381 send = function(data) .Call(rnng_ws_send, x, data),
382 close = function() .Call(rnng_ws_close, x),
383 id = attr(x, "id"),
384 attr(x, name, exact = TRUE))
385 }
386
387 #' Create HTTP Streaming Handler
388 #'
389 #' Creates an HTTP streaming handler using chunked transfer encoding. Supports
390 #' any streaming HTTP protocol including Server-Sent Events (SSE), newline-
391 #' delimited JSON (NDJSON), and custom streaming formats.
392 #'
393 #' @param path URI path to match (e.g., "/stream").
394 #' @param on_request Function called when a request arrives. Signature:
395 #' `function(conn, req)` where `conn` is the connection object and `req`
396 #' is a list with `method`, `uri`, `headers`, `body`.
397 #' @param on_close \[default NULL\] Function called when the connection closes.
398 #' Signature: `function(conn)`
399 #' @param method \[default "*"\] HTTP method to match (e.g., "GET", "POST").
400 #' Use `"*"` to match any method.
401 #' @param prefix \[default FALSE\] Logical, if TRUE matches path as a prefix.
402 #'
403 #' @return A handler object for use with [http_server()].
404 #'
405 #' @section Connection Object:
406 #' The `conn` object passed to callbacks has these methods:
407 #'
408 #' - `conn$send(data)`: Send data chunk to client.
409 #' - `conn$close()`: Close the connection (sends terminal chunk).
410 #' - `conn$set_status(code)`: Set HTTP status code (before first send).
411 #' - `conn$set_header(name, value)`: Set response header (before first send).
412 #' - `conn$id`: Unique connection identifier.
413 #'
414 #' @details
415 #' HTTP streaming uses chunked transfer encoding (RFC 9112). The first
416 #' `$send()` triggers writing of HTTP headers with `Transfer-Encoding: chunked`.
417 #' Headers cannot be modified after the first send.
418 #'
419 #' Set an appropriate `Content-Type` header for your streaming format:
420 #' - NDJSON: `application/x-ndjson`
421 #' - JSON stream: `application/stream+json`
422 #' - SSE: `text/event-stream` (see [format_sse()])
423 #' - Plain text: `text/plain`
424 #'
425 #' **SSE Reconnection:** When an SSE client reconnects after a disconnect, it
426 #' sends a `Last-Event-ID` header containing the last event ID it received.
427 #' Access this via `req$headers["Last-Event-ID"]` in `on_request` to resume
428 #' the event stream from the correct position.
429 #'
430 #' To broadcast to multiple clients, store connection objects in a list and
431 #' iterate over them (e.g., `lapply(conns, function(c) c$send(data))`).
432 #'
433 #' @seealso [format_sse()] for formatting Server-Sent Events.
434 #'
435 #' @examples
436 #' # NDJSON streaming endpoint
437 #' h <- handler_stream("/stream", function(conn, req) {
438 #' conn$set_header("Content-Type", "application/x-ndjson")
439 #' conn$send('{"status":"connected"}\n')
440 #' })
441 #'
442 #' # SSE endpoint with reconnection support
443 #' h <- handler_stream("/events", function(conn, req) {
444 #' conn$set_header("Content-Type", "text/event-stream")
445 #' conn$set_header("Cache-Control", "no-cache")
446 #' last_id <- req$headers["Last-Event-ID"]
447 #' # Resume from last_id if client is reconnecting
448 #' conn$send(format_sse(data = "connected", id = "1"))
449 #' })
450 #'
451 #' # Long-lived streaming with broadcast triggered by POST
452 #' conns <- list()
453 #' handlers <- list(
454 #' handler_stream("/stream",
455 #' on_request = function(conn, req) {
456 #' conn$set_header("Content-Type", "application/x-ndjson")
457 #' conns[[as.character(conn$id)]] <<- conn
458 #' conn$send('{"status":"connected"}\n')
459 #' },
460 #' on_close = function(conn) {
461 #' conns[[as.character(conn$id)]] <<- NULL
462 #' }
463 #' ),
464 #' # POST endpoint triggers broadcast to all streaming clients
465 #' handler("/broadcast", function(req) {
466 #' msg <- paste0('{"msg":"', rawToChar(req$body), '"}\n')
467 #' lapply(conns, function(c) c$send(msg))
468 #' list(status = 200L, body = "sent")
469 #' }, method = "POST")
470 #' )
471 #'
472 #' @export
473 #'
474 handler_stream <- function(path, on_request, on_close = NULL,
475 method = "*", prefix = FALSE) {
476 list(type = 7L, path = path, on_request = on_request, on_close = on_close,
477 method = method, prefix = prefix)
478 }
479
480 #' Format Server-Sent Event
481 #'
482 #' Helper function to format messages according to the Server-Sent Events (SSE)
483 #' specification. Use with [handler_stream()] to create SSE endpoints.
484 #'
485 #' @param data The data payload. Will be prefixed with "data: " on each line.
486 #' @param event \[default NULL\] Optional event type (e.g., "message", "error").
487 #' @param id \[default NULL\] Optional event ID for client reconnection.
488 #' @param retry \[default NULL\] Optional retry interval in milliseconds.
489 #'
490 #' @return A character string formatted as an SSE message, ready to pass to
491 #' `conn$send()`.
492 #'
493 #' @details
494 #' Server-Sent Events is a W3C standard for server-to-client streaming over
495 #' HTTP, supported natively by browsers via the `EventSource` API. SSE is
496 #' commonly used for real-time updates, notifications, and LLM token streaming.
497 #'
498 #' SSE messages have this format:
499 #'
500 #' ```
501 #' event: <event-type>
502 #' id: <event-id>
503 #' retry: <milliseconds>
504 #' data: <data-line-1>
505 #' data: <data-line-2>
506 #'
507 #' ```
508 #'
509 #' Each message ends with two newlines. Multi-line data is split and each
510 #' line prefixed with "data: ".
511 #'
512 #' When using SSE with [handler_stream()], set the appropriate headers:
513 #' - `Content-Type: text/event-stream`
514 #' - `Cache-Control: no-cache`
515 #' - `X-Accel-Buffering: no` (prevents proxy buffering)
516 #'
517 #' @seealso [handler_stream()] for creating streaming HTTP endpoints.
518 #'
519 #' @examples
520 #' format_sse(data = "Hello")
521 #' #> "data: Hello\n\n"
522 #'
523 #' format_sse(data = "Hello", event = "greeting")
524 #' #> "event: greeting\ndata: Hello\n\n"
525 #'
526 #' format_sse(data = "Line 1\nLine 2")
527 #' #> "data: Line 1\ndata: Line 2\n\n"
528 #'
529 #' # Typical SSE endpoint setup
530 #' h <- handler_stream("/events", function(conn, req) {
531 #' conn$set_header("Content-Type", "text/event-stream")
532 #' conn$set_header("Cache-Control", "no-cache")
533 #' conn$set_header("X-Accel-Buffering", "no")
534 #' conn$send(format_sse(data = "connected", id = "1"))
535 #' })
536 #'
537 #' @export
538 #'
539 format_sse <- function(data, event = NULL, id = NULL, retry = NULL) {
540 parts <- character()
541 if (!is.null(event)) parts <- c(parts, paste0("event: ", event))
542 if (!is.null(id)) parts <- c(parts, paste0("id: ", id))
543 if (!is.null(retry)) parts <- c(parts, paste0("retry: ", as.integer(retry)))
544 lines <- strsplit(as.character(data), "\n", fixed = TRUE)[[1L]]
545 parts <- c(parts, paste0("data: ", lines))
546 paste0(paste(parts, collapse = "\n"), "\n\n")
547 }
548
549 #' @export
550 #'
551 print.nanoStreamConn <- function(x, ...) {
552 cat("< nanoStreamConn >\n")
553 cat(" - id:", attr(x, "id"), "\n")
554 invisible(x)
555 }
556
557 #' @export
558 #'
559 `$.nanoStreamConn` <- function(x, name) {
560 switch(name,
561 send = function(data) .Call(rnng_stream_conn_send, x, data),
562 close = function() .Call(rnng_conn_close, x),
563 set_status = function(code) .Call(rnng_stream_conn_set_status, x, as.integer(code)),
564 set_header = function(name, value) .Call(rnng_stream_conn_set_header, x, name, value),
565 id = attr(x, "id"),
566 attr(x, name, exact = TRUE))
567 }
568