Debian Codegraph @

inst/doc/v04-web.Rmd

raw
1 ---
2 title: "nanonext - Web Toolkit"
3 vignette: >
4 %\VignetteIndexEntry{nanonext - Web Toolkit}
5 %\VignetteEngine{litedown::vignette}
6 %\VignetteEncoding{UTF-8}
7 ---
8
9
10
11
12 ``` r
13 library(nanonext)
14 ```
15
16 nanonext provides high-performance HTTP/WebSocket client and server capabilities built on NNG's networking stack with Mbed TLS for secure connections.
17
18 ### 1. HTTP Client
19
20 #### ncurl: Basic Requests
21
22 `ncurl()` is a minimalist HTTP(S) client. Basic usage requires only a URL.
23
24
25 ``` r
26 ncurl("https://postman-echo.com/get")
27 #> $status
28 #> [1] 200
29 #>
30 #> $headers
31 #> NULL
32 #>
33 #> $data
34 #> [1] "{\"args\":{},\"headers\":{\"host\":\"postman-echo.com\",\"accept-encoding\":\"gzip, br\",\"x-forwarded-proto\":\"https\"},\"url\":\"https://postman-echo.com/get\"}"
35 ```
36
37 Advanced usage supports all HTTP methods (POST, PUT, DELETE, etc.), custom headers, and request bodies.
38
39
40 ``` r
41 ncurl("https://postman-echo.com/post",
42 method = "POST",
43 headers = c(`Content-Type` = "application/json", Authorization = "Bearer APIKEY"),
44 data = '{"key": "value"}',
45 response = "date")
46 #> $status
47 #> [1] 200
48 #>
49 #> $headers
50 #> $headers$date
51 #> [1] "Mon, 30 Mar 2026 22:16:56 GMT"
52 #>
53 #>
54 #> $data
55 #> [1] "{\"args\":{},\"data\":{\"key\":\"value\"},\"files\":{},\"form\":{},\"headers\":{\"host\":\"postman-echo.com\",\"accept-encoding\":\"gzip, br\",\"content-length\":\"16\",\"authorization\":\"Bearer APIKEY\",\"content-type\":\"application/json\",\"x-forwarded-proto\":\"https\"},\"json\":{\"key\":\"value\"},\"url\":\"https://postman-echo.com/post\"}"
56 ```
57
58 Specify `response = TRUE` to return all response headers.
59
60
61 ``` r
62 ncurl("https://postman-echo.com/get",
63 response = TRUE)
64 #> $status
65 #> [1] 200
66 #>
67 #> $headers
68 #> $headers$Date
69 #> [1] "Mon, 30 Mar 2026 22:16:56 GMT"
70 #>
71 #> $headers$`Content-Type`
72 #> [1] "application/json; charset=utf-8"
73 #>
74 #> $headers$`Content-Length`
75 #> [1] "143"
76 #>
77 #> $headers$Connection
78 #> [1] "close"
79 #>
80 #> $headers$etag
81 #> [1] "W/\"8f-7zN8nSad8A9WlFJjKQZB04z5nHE\""
82 #>
83 #> $headers$vary
84 #> [1] "Accept-Encoding"
85 #>
86 #> $headers$`x-envoy-upstream-service-time`
87 #> [1] "5"
88 #>
89 #> $headers$`cf-cache-status`
90 #> [1] "DYNAMIC"
91 #>
92 #> $headers$`Set-Cookie`
93 #> [1] "sails.sid=s%3AtfbN2TazlwshVuIc_Y-l_CKCt7WScK3s.5Z30lz615FemZ1kCseuVIUD4G%2BEAGJfIiYaJhfFDiGU; Path=/; HttpOnly, __cf_bm=mX8EtQ27DKZ2X6uAi8_krT8AN00Bf9rEnI4aauRi_.Q-1774909016.466189-1.0.1.1-Wtzs3qUkHi8sLuARpkSeFbJ8vXysEL7bXJdqKa3EqeWEanTLfzrcxvOudXHbpT8moKuZq5KuQXmZr0dSvqRdXUuc_yS8Ms47TY9OL3jb0muL_3gxejNDW7cDvtDcmLKh; HttpOnly; Secure; Path=/; Domain=postman-echo.com; Expires=Mon, 30 Mar 2026 22:46:56 GMT, _cfuvid=PgOu7XWt97qqSBedwhgeqXxkMVIYi18WzlBWroe865k-1774909016.466189-1.0.1.1-z9Y3X8DXI.zgMtblcU7939qcoMyvq2dQUGtA9Mbi59o; HttpOnly; SameSite=None; Secure; Path=/; Domain=postman-echo.com"
94 #>
95 #> $headers$Server
96 #> [1] "cloudflare"
97 #>
98 #> $headers$`CF-RAY`
99 #> [1] "9e4a7b48ed31cd3a-LHR"
100 #>
101 #>
102 #> $data
103 #> [1] "{\"args\":{},\"headers\":{\"host\":\"postman-echo.com\",\"accept-encoding\":\"gzip, br\",\"x-forwarded-proto\":\"https\"},\"url\":\"https://postman-echo.com/get\"}"
104 ```
105
106 #### ncurl_aio: Async Requests
107
108 `ncurl_aio()` performs asynchronous requests, returning immediately with an 'ncurlAio' object that resolves when the response arrives.
109
110
111 ``` r
112 res <- ncurl_aio("https://postman-echo.com/post",
113 method = "POST",
114 headers = c(`Content-Type` = "application/json"),
115 data = '{"async": true}',
116 response = "date")
117 res
118 #> < ncurlAio | $status $headers $data >
119
120 call_aio(res)$headers
121 #> $date
122 #> [1] "Mon, 30 Mar 2026 22:16:56 GMT"
123
124 res$status
125 #> [1] 200
126
127 res$data
128 #> [1] "{\"args\":{},\"data\":{\"async\":true},\"files\":{},\"form\":{},\"headers\":{\"host\":\"postman-echo.com\",\"accept-encoding\":\"gzip, br\",\"content-type\":\"application/json\",\"content-length\":\"15\",\"x-forwarded-proto\":\"https\"},\"json\":{\"async\":true},\"url\":\"https://postman-echo.com/post\"}"
129 ```
130
131 ##### Promises Integration
132
133 'ncurlAio' objects work anywhere that accepts a 'promise' from the promises package, including Shiny ExtendedTask.
134
135
136 ``` r
137 library(promises)
138
139 p <- ncurl_aio("https://postman-echo.com/get") |> then(\(x) cat(x$data))
140 is.promise(p)
141 #> [1] TRUE
142 ```
143
144 #### ncurl_session: Persistent Connections
145
146 `ncurl_session()` creates a reusable connection for efficient repeated requests to an API endpoint. Use `transact()` to send requests over the session.
147
148
149 ``` r
150 sess <- ncurl_session("https://postman-echo.com/get",
151 convert = FALSE,
152 headers = c(`Content-Type` = "application/json"),
153 response = c("Date", "Content-Type"))
154 sess
155 #> < ncurlSession > - transact() to return data
156
157 transact(sess)
158 #> $status
159 #> [1] 200
160 #>
161 #> $headers
162 #> $headers$Date
163 #> [1] "Mon, 30 Mar 2026 22:16:57 GMT"
164 #>
165 #> $headers$`Content-Type`
166 #> [1] "application/json; charset=utf-8"
167 #>
168 #>
169 #> $data
170 #> [1] 7b 22 61 72 67 73 22 3a 7b 7d 2c 22 68 65 61 64 65 72 73 22 3a 7b 22 68 6f
171 #> [26] 73 74 22 3a 22 70 6f 73 74 6d 61 6e 2d 65 63 68 6f 2e 63 6f 6d 22 2c 22 63
172 #> [51] 6f 6e 74 65 6e 74 2d 74 79 70 65 22 3a 22 61 70 70 6c 69 63 61 74 69 6f 6e
173 #> [76] 2f 6a 73 6f 6e 22 2c 22 78 2d 66 6f 72 77 61 72 64 65 64 2d 70 72 6f 74 6f
174 #> [101] 22 3a 22 68 74 74 70 73 22 2c 22 61 63 63 65 70 74 2d 65 6e 63 6f 64 69 6e
175 #> [126] 67 22 3a 22 67 7a 69 70 2c 20 62 72 22 7d 2c 22 75 72 6c 22 3a 22 68 74 74
176 #> [151] 70 73 3a 2f 2f 70 6f 73 74 6d 61 6e 2d 65 63 68 6f 2e 63 6f 6d 2f 67 65 74
177 #> [176] 22 7d
178
179 close(sess)
180
181 ```
182
183 ### 2. WebSocket Client
184
185 `stream()` provides a low-level byte stream interface for communicating with WebSocket servers and other non-NNG endpoints.
186
187 Use `textframes = TRUE` for servers that expect text frames (most WebSocket servers).
188
189
190 ``` r
191 s <- stream(dial = "wss://echo.websocket.org/", textframes = TRUE)
192 s
193 #> < nanoStream >
194 #> - mode: dialer text frames
195 #> - state: opened
196 #> - url: wss://echo.websocket.org/
197 ```
198
199 `send()` and `recv()`, along with their async counterparts `send_aio()` and `recv_aio()`, work on Streams just like Sockets.
200
201
202 ``` r
203 s |> recv()
204 #> [1] "Request served by 4d896d95b55478"
205
206 s |> send("hello websocket")
207 #> [1] 0
208
209 s |> recv()
210 #> [1] "hello websocket"
211
212 s |> recv_aio() -> r
213
214 s |> send("async message")
215 #> [1] 0
216
217 r[]
218 #> [1] "async message"
219
220 close(s)
221
222 ```
223
224 ### 3. Unified HTTP/WebSocket Server
225
226 `http_server()` creates a single server that can handle HTTP requests, WebSocket connections, and HTTP streaming, all on the same port.
227
228 A single call to `http_server()` sets up one NNG server instance with a list of handlers. HTTP routes, WebSocket endpoints, streaming endpoints, and static file handlers all share the same underlying server -- there is no need to run separate processes or bind additional ports. WebSocket clients connect via the standard HTTP upgrade mechanism, so a browser can load a page over HTTP and open a WebSocket connection to the same origin without any cross-origin configuration.
229
230
231 ``` r
232 server <- http_server(
233 url = "http://127.0.0.1:8080",
234 handlers = list(
235 handler("/", function(req) {
236 list(status = 200L, body = "Hello from nanonext!")
237 }),
238 handler("/api/data", function(req) {
239 list(
240 status = 200L,
241 headers = c("Content-Type" = "application/json"),
242 body = '{"value": 42}'
243 )
244 }, method = "GET")
245 )
246 )
247 server$serve()
248
249 ```
250
251 `$serve()` is a blocking call that starts the server, runs the event loop to process requests, and automatically closes the server on interrupt (Ctrl+C). For non-blocking use, call `$start()` and `$close()` separately, with `repeat later::run_now(Inf)` to run the event loop manually.
252
253 Specifying port `0` in the URL lets the OS assign an available port. The actual port is reflected in `server$url` after `$start()` or `$serve()`, making it easy to set up test servers without port conflicts.
254
255 #### Handler Types
256
257 All handler types can be freely mixed in a single server's handler list:
258
259 | Handler | Purpose |
260 |:--------|:--------|
261 | `handler()` | HTTP request/response with R callback |
262 | `handler_ws()` | WebSocket with `on_message`, `on_open`, `on_close` callbacks |
263 | `handler_stream()` | Chunked HTTP streaming (SSE, NDJSON, custom) |
264 | `handler_file()` | Serve a single static file |
265 | `handler_directory()` | Serve a directory tree with automatic MIME types |
266 | `handler_inline()` | Serve in-memory content |
267 | `handler_redirect()` | HTTP redirect |
268
269 #### HTTP Request Handlers
270
271 `handler()` creates HTTP route handlers. The callback receives a request list with `method`, `uri`, `headers`, and `body`, and returns a response list with `status`, optional `headers`, and `body`.
272
273
274 ``` r
275 # GET endpoint
276 h1 <- handler("/hello", function(req) {
277 list(status = 200L, body = "Hello!")
278 })
279
280 # POST endpoint echoing the request body
281 h2 <- handler("/echo", function(req) {
282 list(status = 200L, body = req$body)
283 }, method = "POST")
284
285 # Catch-all for any method under a path prefix
286 h3 <- handler("/api", function(req) {
287 list(
288 status = 200L,
289 headers = c("Content-Type" = "application/json"),
290 body = sprintf('{"method":"%s","uri":"%s"}', req$method, req$uri)
291 )
292 }, method = "*", prefix = TRUE)
293
294 ```
295
296 #### Static Content Handlers
297
298
299 ``` r
300 # Serve a single file
301 h_file <- handler_file("/favicon.ico", "path/to/favicon.ico")
302
303 # Serve a directory tree (automatic MIME type detection)
304 h_dir <- handler_directory("/static", "www/assets")
305
306 # Serve inline content
307 h_inline <- handler_inline("/robots.txt", "User-agent: *\nDisallow:",
308 content_type = "text/plain")
309
310 # Redirect requests
311 h_redirect <- handler_redirect("/old-page", "/new-page", status = 301L)
312
313 ```
314
315 #### WebSocket Handlers
316
317 WebSockets provide full bidirectional communication -- the server can push messages to the client, and the client can send messages back.
318
319 `handler_ws()` creates WebSocket endpoints. NNG handles the HTTP upgrade handshake and all WebSocket framing (RFC 6455) automatically. Because WebSocket handlers share the same server as HTTP handlers, the browser can load a page and open a WebSocket to the same host and port with no additional setup.
320
321
322 ``` r
323 clients <- list()
324
325 server <- http_server(
326 url = "http://127.0.0.1:8080",
327 handlers = list(
328 handler_ws(
329 "/chat",
330 on_message = function(ws, data) {
331 # Broadcast to all connected clients
332 for (client in clients) client$send(data)
333 },
334 on_open = function(ws, req) {
335 clients[[as.character(ws$id)]] <<- ws
336 },
337 on_close = function(ws) {
338 clients[[as.character(ws$id)]] <<- NULL
339 },
340 textframes = TRUE
341 )
342 )
343 )
344 server$serve()
345
346 ```
347
348 The `ws` connection object provides:
349
350 - `ws$send(data)` - Send a message to the client
351 - `ws$close()` - Close the connection
352 - `ws$id` - Unique integer connection identifier
353
354 Multiple WebSocket endpoints can coexist on the same server, each with independent callbacks and connection tracking. Connection IDs are unique across the entire server, so they are safe to use as keys in a shared data structure spanning multiple handlers.
355
356 #### HTTP Streaming Handlers
357
358 When you only need to push data in one direction -- server to client -- streaming is a lighter-weight alternative to WebSockets. It works over plain HTTP, so any client that speaks HTTP can consume the stream without needing a WebSocket library.
359
360 `handler_stream()` enables HTTP streaming using chunked transfer encoding, supporting Server-Sent Events (SSE), newline-delimited JSON (NDJSON), and custom streaming formats. Like WebSocket handlers, streaming endpoints share the same server as all other handlers.
361
362
363 ``` r
364 conns <- list()
365
366 server <- http_server(
367 url = "http://127.0.0.1:8080",
368 handlers = list(
369 # SSE endpoint
370 handler_stream("/events",
371 on_request = function(conn, req) {
372 conn$set_header("Content-Type", "text/event-stream")
373 conn$set_header("Cache-Control", "no-cache")
374 conns[[as.character(conn$id)]] <<- conn
375 conn$send(format_sse(data = "connected", id = "1"))
376 },
377 on_close = function(conn) {
378 conns[[as.character(conn$id)]] <<- NULL
379 }
380 ),
381 # Trigger broadcast via POST
382 handler("/broadcast", function(req) {
383 msg <- format_sse(data = rawToChar(req$body), event = "message")
384 lapply(conns, function(c) c$send(msg))
385 list(status = 200L, body = "sent")
386 }, method = "POST")
387 )
388 )
389 server$serve()
390
391 ```
392
393 #### Server-Sent Events
394
395 `format_sse()` formats messages according to the SSE specification for browser `EventSource` clients.
396
397
398 ``` r
399 format_sse(data = "Hello")
400 #> [1] "data: Hello\n\n"
401
402 format_sse(data = "Update available", event = "notification", id = "42")
403 #> [1] "event: notification\nid: 42\ndata: Update available\n\n"
404
405 format_sse(data = "Line 1\nLine 2")
406 #> [1] "data: Line 1\ndata: Line 2\n\n"
407 ```
408
409 The streaming connection object provides:
410
411 - `conn$send(data)` - Send a data chunk
412 - `conn$close()` - Close the connection
413 - `conn$set_status(code)` - Set HTTP status (before first send)
414 - `conn$set_header(name, value)` - Set response header (before first send)
415 - `conn$id` - Unique connection identifier
416
417 ### 4. Secure Connections (TLS)
418
419 All web functions support TLS for secure HTTPS/WSS connections via `tls_config()`.
420
421 #### Public Internet HTTPS
422
423 When making HTTPS requests over the public internet, you should supply a TLS configuration to validate server certificates.
424
425 Root CA certificates in PEM format may be found at:
426
427 - Linux: `/etc/ssl/certs/ca-certificates.crt` or `/etc/pki/tls/certs/ca-bundle.crt`
428 - macOS: `/etc/ssl/cert.pem`
429 - Windows: download from the [Common CA Database](https://www.ccadb.org/resources) site run by Mozilla (select the Server Authentication SSL/TLS certificates text file). *This link is not endorsed; use at your own risk.*
430
431
432 ``` r
433 tls <- tls_config(client = "/etc/ssl/cert.pem")
434 ncurl("https://www.google.com", tls = tls)
435
436 ```
437
438 #### Self-Signed Certificates
439
440 For internal services or testing, generate self-signed certificates using `write_cert()`.
441
442
443 ``` r
444 # Generate self-signed certificate for testing
445 cert <- write_cert(cn = "127.0.0.1")
446
447 # Server TLS configuration
448 ser <- tls_config(server = cert$server)
449
450 # Client TLS configuration
451 cli <- tls_config(client = cert$client)
452
453 ```
454
455 Use the configurations with servers and clients:
456
457
458 ``` r
459 # HTTPS server
460 server <- http_server(
461 url = "https://127.0.0.1:0",
462 handlers = list(
463 handler("/", function(req) list(status = 200L, body = "Secure!"))
464 ),
465 tls = ser
466 )
467 server$start()
468 server
469 #> < nanoServer >
470 #> - url: https://127.0.0.1:55055
471 #> - state: started
472
473 # HTTPS client request
474 aio <- ncurl_aio(paste0(server$url, "/"), tls = cli)
475 while (unresolved(aio)) later::run_now(1)
476 #> {"args":{},"headers":{"host":"postman-echo.com","accept-encoding":"gzip, br","x-forwarded-proto":"https"},"url":"https://postman-echo.com/get"}
477 aio$status
478 #> [1] 200
479 aio$data
480 #> [1] "Secure!"
481
482 server$close()
483
484 ```
485
486 ### 5. Client Example: Shiny ExtendedTask
487
488 This example demonstrates using `ncurl_aio()` with Shiny's ExtendedTask for non-blocking HTTP requests.
489
490 If your Shiny app calls an external API, a slow or unresponsive endpoint will block the R process and freeze the app for *all* users, not just the one who triggered the request.
491 `ncurl_aio()` avoids this -- it performs the HTTP call on a background thread and returns a promise, so the R process stays free to serve other sessions.
492 It works anywhere that accepts a promise, including Shiny's ExtendedTask:
493
494
495 ``` r
496 library(shiny)
497 library(bslib)
498 library(nanonext)
499
500 ui <- page_fluid(
501 p("The time is ", textOutput("current_time", inline = TRUE)),
502 hr(),
503 input_task_button("btn", "Fetch data"),
504
505 verbatimTextOutput("result")
506 )
507
508 server <- function(input, output, session) {
509 output$current_time <- renderText({
510 invalidateLater(1000)
511 format(Sys.time(), "%H:%M:%S %p")
512 })
513
514 task <- ExtendedTask$new(
515 function() ncurl_aio("https://postman-echo.com/get", response = TRUE)
516 ) |> bind_task_button("btn")
517
518 observeEvent(input$btn, task$invoke())
519 output$result <- renderPrint(task$result()$headers)
520 }
521
522 shinyApp(ui, server)
523
524 ```
525
526 ### 6. Server Example: Quarto Site with Dynamic API
527
528 This example shows how the unified server architecture makes it straightforward to combine HTTP or WebSocket handlers to serve different content over the same port.
529
530 If you've rendered a Quarto website and want to serve it locally -- but also expose a dynamic API endpoint alongside it, that's possible with a single `http_server()` call:
531
532
533 ``` r
534 library(nanonext)
535
536 server <- http_server(
537 url = "http://127.0.0.1:0",
538 handlers = list(
539 # Serve your rendered Quarto site
540 handler_directory("/", "_site"),
541
542 # Add a prediction API endpoint
543 handler("/api/predict", function(req) {
544 input <- secretbase::jsondec(req$body)
545 pred <- predict(model, newdata = input)
546 list(
547 status = 200L,
548 headers = c("Content-Type" = "application/json"),
549 body = secretbase::jsonenc(list(prediction = pred))
550 )
551 }, method = "POST")
552 )
553 )
554
555 server$start()
556 server$url
557 # Browse to the URL to see your Quarto site with a live API behind it
558 ```
559
560 Static pages are served at native speed by NNG while the prediction endpoint is handled by R -- no separate processes or ports required. Adding TLS is a single argument.