Skip to contents

rtailcat gives you TCP streams and UDP datagrams between two R processes that can be anywhere, without accounts, port forwarding, or a VPN. That is a low-level building block, so this vignette shows three small things you might build with it, each written as if it were a little package of its own:

  1. wormhole: send an R object to someone else.
  2. progress: watch a long-running job report its progress, live, over UDP.
  3. proxy: open a web app running on another machine in your browser.

Each section first defines the functions and then shows them in use. The usage code always runs in two R sessions, usually on two different machines, and each code block is labeled with the machine it runs on. The code is complete and runnable; the functions are also installed with the package, one file per example, so you can load all of them or just the one you want:

source(system.file("examples/wormhole.R", package = "rtailcat"))
source(system.file("examples/progress.R", package = "rtailcat"))
source(system.file("examples/proxy.R", package = "rtailcat"))

A tailcat address is a secret: anyone who has it can connect to the server. The output below shortens addresses to forms such as tcAbC...xYz, and where code needs an address you paste in the full one that the other side printed.

The output shown was recorded by running the code against a local test relay. It is not computed when the vignette is built, because that needs two R sessions and a network connection.

Sending messages over a stream

A TCP connection is a stream of bytes, not of messages. $read() returns whatever has arrived, at most 64 KiB at a time, so one $write() on one side can turn into several reads on the other, and two writes can arrive in a single read. $read_all() collects everything up to the end of the stream, which is enough when each side sends one thing and then calls $close_write(). For a conversation with several messages in each direction you need to mark where each message ends.

$write_message() and $read_message() do this for you. Each $read_message() returns exactly what one $write_message() on the other side sent, however the bytes were split up on the way. It returns NULL when the other side has ended the stream between two messages, which is how a reader learns that the other side is done. With max_bytes it refuses a message larger than that before reading any of it, so a peer cannot make you allocate an arbitrary amount of memory. On the wire each message is its length as 4 bytes, big-endian, followed by the bytes, so a program written in another language can take part in the same conversation.

The examples below use messages for everything that goes over TCP. To send an R object, send serialize(x, NULL) as a message and call unserialize() on the other side.

wormhole: sending an R object

Sharing a data set with a collaborator usually means email attachments, a shared drive, or uploading it somewhere. With wormhole the sender runs wormhole_send(), which prints an address and waits; the receiver runs wormhole_receive() with that address and gets the object. Neither side needs a public IP address or an open port, and the data is encrypted end to end.

The sender starts a server, listens on a fixed port, and waits for one connection. It sends the serialized object as a single message and waits for the receiver to confirm before it shuts down. Once the receiver has connected, the listener is closed, so nobody else can connect with the same address.

wormhole_port = 4404L

format_bytes = function(n) {
  # Formats a byte count for messages, such as "3.8 kB"

  structure(n, class = "object_size") |>
    format(units = "auto", standard = "SI")
}

wormhole_send = function(x, timeout = 600) {
  # Sends an R object to one receiver, waits until it confirms, and returns the object

  srv = TailcatServer$new()
  on.exit(srv$close(), add = TRUE)
  lst = srv$listen(wormhole_port)
  address = tailcat_reveal(srv$address)
  cli::cli_inform(c(
    "Waiting for the receiver. Give them this address privately:",
    "{address}"
  ))

  conn = lst$accept(timeout = timeout)

  # One transfer per address: nobody else can connect once the receiver has
  lst$close()

  # The protocol: the serialized object, then "ok" from the receiver. The reply is
  # "ok", so a longer one is refused without reading it. A receiver that gives up
  # ends the stream or resets it, so a failure also counts as no confirmation
  payload = serialize(x, NULL)
  reply = tryCatch(
    conn$write_message(payload, timeout = timeout)$read_message(
      timeout = timeout,
      as = "text",
      max_bytes = 16
    ),
    tailcat_failure = \(e) NULL
  )
  if (!identical(reply, "ok")) {
    cli::cli_abort("The receiver did not confirm the transfer.")
  }
  conn$close()
  srv$close(drain = 5)
  cli::cli_inform("Sent {format_bytes(length(payload))}.")
  invisible(x)
}

The address is a tailcat_secret, which prints as <redacted>, so wormhole_send() calls tailcat_reveal() to show it deliberately. This is the one place the secret is meant to appear.

Closing a server tears down its connections at once, so the receiver might not see the end of the stream cleanly. Closing the connection first and then calling $close(drain = 5) waits up to five seconds for that shutdown to reach the other side before closing the server. The receiver does the same with its client, and does it in on.exit() so that it also happens when the receiver stops with an error, such as an object over max_bytes. Without that the sender could wait out its whole timeout for a confirmation that is never coming. The sender in turn treats a stream that ends or fails before the "ok" arrives as a transfer that was not confirmed.

The receiver dials the sender, reads the object, and only then confirms. max_bytes is checked against the length at the start of the message, so an object larger than the receiver is willing to accept is refused before any of it is read.

wormhole_receive = function(address, max_bytes = 1e9, timeout = 600) {
  # Receives one R object from the sender at `address` and returns it

  cl = TailcatClient$new(address)
  conn = NULL

  # However this function ends, close the connection and give that time to reach
  # the sender, so a refused transfer does not leave the sender waiting
  on.exit(
    {
      if (!is.null(conn)) {
        conn$close()
      }
      cl$close(drain = 5)
    },
    add = TRUE
  )
  conn = cl$dial(wormhole_port, timeout = 60)

  payload = conn$read_message(timeout = timeout, max_bytes = max_bytes)
  if (is.null(payload)) {
    cli::cli_abort("The sender closed the connection without sending anything.")
  }

  # unserialize() can run code, which is acceptable only because the receiver
  # dialed an address the sender gave them and so knows who is sending
  value = unserialize(payload)
  cli::cli_inform("Received {format_bytes(length(payload))}.")

  conn$write_message("ok", timeout = 60)$close_write()
  value
}

unserialize() can run code while it rebuilds an object, so use wormhole_receive() only with senders you trust. Here that is natural: the receiver connects to an address that the sender gave them, so they already know who is on the other end.

Using it

The sender passes any R object to wormhole_send(), which waits until the transfer is done.

library(rtailcat)
wormhole_send(mtcars)
#> Waiting for the receiver. Give them this address privately:
#> tcAbC...xYz
#> Sent 3.8 kB.

The receiver pastes the address into wormhole_receive():

library(rtailcat)
cars = wormhole_receive("tcAbC...xYz")
#> Received 3.8 kB.
head(cars, 3)
#>                mpg cyl disp  hp drat    wt  qsec vs am gear carb
#> Mazda RX4     21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
#> Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
#> Datsun 710    22.8   4  108  93 3.85 2.320 18.61  1  1    4    1

Each call starts a new server with a new address, so an address that was used once is worthless afterwards.

Extending it to files

Sending a file is mostly a matter of telling the receiver what it is getting. The sender would first send a small header message, for example JSON with the file’s name and size, and then the file’s bytes (read with readBin()) instead of a serialized object. The receiver would read the header with a small max_bytes, since a header is only a few dozen bytes, check the announced size against its own limit, and then read the data with max_bytes set to that size, so the sender cannot send more than it announced. The same header can carry a kind field so that one receiver handles both objects and files.

The file name comes from the sender, so the receiver has to treat it as untrusted: accept it only if it equals its own basename() and is not "." or "..", so it cannot point outside the target folder, and refuse to overwrite a file that already exists. In return, files are written as bytes with writeBin() and never interpreted, so a file transfer does not need the trust that unserialize() does.

progress: watching a long-running job over UDP

A long simulation or model fit on a cluster node or a cloud machine usually reports its progress to a log file, which you then have to go and read. With progress, the job sends small progress reports to your laptop as it runs, and your laptop collects them in the background, while you keep using the R console, or shows them in a Shiny app.

This is a good fit for UDP. Each report is a single small datagram, and if one is lost the next one is along shortly, so there is no point in waiting for retransmissions or keeping a connection alive. More importantly, sending a datagram never blocks the job for long and never fails because the monitor has gone away: the job should not slow down, or stop, because nobody is watching. Each datagram holds at most 1232 bytes, which is plenty for a few numbers encoded as JSON.

Note that the server runs on the laptop and the job is the client, the reverse of what you might expect. The laptop prints an address and the job dials it, so neither needs to accept connections from the internet.

The monitor listens on a UDP port and calls a handler for each flow, one per job. The handler starts a read loop on the flow, which calls progress_record() with each datagram as it arrives. Nothing blocks: the reports are collected by the later event loop whenever the R console is idle, or while Shiny is running.

progress_record = function(monitor, datagram) {
  # Stores one report, ignoring datagrams that are not JSON objects naming their job

  event = tryCatch(
    datagram |> rawToChar() |> jsonlite::fromJSON(),
    error = \(e) NULL
  )
  if (is.list(event) && is.character(event$job) && length(event$job) == 1) {
    monitor$events[[length(monitor$events) + 1]] = event
    monitor$last_seen[[event$job]] = Sys.time()
  }
  invisible(monitor)
}

progress_monitor = function(port = 9000L) {
  # Starts collecting progress reports in the background and returns the monitor

  srv = TailcatServer$new()
  lst = srv$listen(port, network = "udp")
  monitor = new.env(parent = emptyenv())
  monitor$server = srv
  monitor$listener = lst
  monitor$events = list()
  monitor$last_seen = list()

  # A failed flow is closed anyway and there is no one to tell, so its error is
  # dropped instead of becoming a warning
  lst$serve(\(conn) {
    conn$read_loop(
      \(datagram) progress_record(monitor, datagram),
      on_error = \(e) NULL
    )
  })
  address = tailcat_reveal(srv$address)
  cli::cli_inform(c(
    "Collecting progress reports on UDP port {port}. Address for the jobs:",
    "{address}"
  ))
  structure(monitor, class = "progress_monitor")
}

progress_data = function(monitor) {
  # Returns the reports as a tibble with one row per report, ordered by job and sequence number

  events = monitor$events
  if (length(events) == 0) {
    return(tibble::tibble(job = character(), seq = integer()))
  }

  # Reports may carry different fields
  cols = events |> lapply(names) |> unlist() |> unique()
  rows = lapply(events, \(e) {
    e[setdiff(cols, names(e))] = NA
    tibble::as_tibble(e[cols])
  })
  out = do.call(rbind, rows)
  out[order(out$job, out$seq), ]
}

progress_stop = function(monitor) {
  # Stops collecting reports, closes the monitor's server, and returns the monitor

  monitor$server$close()
  invisible(monitor)
}

print.progress_monitor = function(x, ...) {
  # Shows how many reports have arrived from how many jobs, and whether more can arrive

  n = length(x$events)
  jobs = length(x$last_seen)
  state = if (x$listener$is_serving) "collecting" else "stopped"
  "<progress monitor> {n} report{?s} from {jobs} job{?s} ({state})" |>
    cli::pluralize() |>
    cat("\n", sep = "")
  invisible(x)
}

A report that is malformed, for example one sent by something other than progress_report(), is ignored. Since a monitor accepts reports from anyone who has its address, it does nothing with them other than store them. The monitor also notes when it last heard from each job, which it keeps to itself rather than adding to the reports: progress_data() returns what the jobs said. The print method uses the listener’s $is_serving to say whether the monitor is still collecting. If reading from a flow fails, the read loop closes it; the on_error callback that does nothing keeps that from showing up as a warning.

The job side dials the monitor once and then sends one datagram per report. Each report carries the job name and a sequence number, so the monitor can tell jobs apart and notice lost reports. progress_report() never stops the job because of the network: if the monitor is unreachable the report is simply lost, and a write that cannot complete within a second is abandoned. It returns the reporter, which counts such reports in reporter$unsent, rather than a TRUE or FALSE that a job would have to check after every call.

The fields of a report are whatever the job names in ..., so the reporter argument is called .reporter: without the dot, a field called reporter, or just rep, would be taken for the argument instead of being sent. For the same reason the two names every report already carries, job and seq, are refused.

progress_reporter = function(address, job, port = 9000L) {
  # Connects a job to a monitor and returns a reporter for progress_report()

  cl = TailcatClient$new(address)
  reporter = new.env(parent = emptyenv())
  reporter$client = cl
  reporter$conn = cl$dial(port, network = "udp", timeout = 60)
  reporter$job = job
  reporter$seq = 0L
  reporter$unsent = 0L
  reporter
}

progress_report = function(.reporter, ...) {
  # Sends one report with the fields in `...` and returns the reporter

  fields = list(...)
  reserved = intersect(names(fields), c("job", "seq"))
  if (length(reserved) > 0) {
    cli::cli_abort("A report cannot have {cli::qty(reserved)}field{?s} named {.field {reserved}}.")
  }
  seq = .reporter$seq + 1L
  .reporter$seq = seq
  payload = c(list(job = .reporter$job, seq = seq), fields) |>
    jsonlite::toJSON(auto_unbox = TRUE, digits = NA) |>
    charToRaw()
  limit = tailcat_udp_max_payload()
  if (length(payload) > limit) {
    cli::cli_warn(c(
      "Report {seq} was not sent.",
      "i" = "It is {length(payload)} bytes; a datagram holds at most {limit}."
    ))
    .reporter$unsent = .reporter$unsent + 1L
    return(invisible(.reporter))
  }

  # Monitoring must never slow down or stop the job, so a failed send is
  # given up after a second and only counted
  tryCatch(
    .reporter$conn$write(payload, timeout = 1),
    error = \(e) {
      .reporter$unsent = .reporter$unsent + 1L
    }
  )
  invisible(.reporter)
}

progress_done = function(reporter) {
  # Disconnects the reporter from the monitor and returns the reporter

  reporter$client$close()
  invisible(reporter)
}

Finally, a small Shiny app plots one metric against another, with a line per job, and lists each job’s latest report. It checks for new reports once a second. Shiny runs the later event loop, so the monitor keeps collecting reports while the app is open.

progress_app = function(monitor, x = "iter", y = "loss") {
  # A Shiny app plotting `y` against `x` for each job, with their latest reports

  ui = shiny::fluidPage(
    shiny::titlePanel("Job progress"),
    shiny::plotOutput("plot"),
    shiny::tableOutput("latest")
  )
  server = function(input, output, session) {
    # Polling is enough: the monitor collects reports on its own
    data = shiny::reactivePoll(
      1000,
      session,
      checkFunc = \() length(monitor$events),
      valueFunc = \() progress_data(monitor)
    )
    output$plot = shiny::renderPlot({
      d = data()
      shiny::req(nrow(d) > 0, x %in% names(d), y %in% names(d))
      jobs = unique(d$job)
      graphics::plot(d[[x]], d[[y]], type = "n", xlab = x, ylab = y)
      for (i in seq_along(jobs)) {
        rows = d$job == jobs[i]
        graphics::lines(d[[x]][rows], d[[y]][rows], col = i, lwd = 2)
      }
      graphics::legend(
        "topright",
        legend = jobs,
        col = seq_along(jobs),
        lwd = 2,
        bty = "n"
      )
    })
    output$latest = shiny::renderTable({
      d = data()
      shiny::req(nrow(d) > 0)
      latest = d[!duplicated(d$job, fromLast = TRUE), ]
      seen = do.call(c, monitor$last_seen[latest$job])
      latest$age = difftime(Sys.time(), seen, units = "secs") |>
        as.double() |>
        round() |>
        paste("s")
      latest
    })
  }
  shiny::shinyApp(ui, server)
}

Using it

Start the monitor on your laptop. It returns at once and keeps collecting in the background.

library(rtailcat)
m = progress_monitor()
#> Collecting progress reports on UDP port 9000. Address for the jobs:
#> tcAbC...xYz

Give the job the address, for example through an environment variable, or a file only you can read written with tailcat_address_write(m$server, path) and read in the job with tailcat_address_read(path), and call progress_report() wherever the job has something to say. Here a loop that shrinks a number stands in for the real work.

library(rtailcat)
reporter = progress_reporter("tcAbC...xYz", job = "fit-1")
loss = 1
for (i in 1:20) {
  Sys.sleep(0.1)
  loss = loss * 0.8
  progress_report(reporter, iter = i, loss = loss)
}
progress_done(reporter)

Back on the laptop the reports have arrived. Missing sequence numbers would show lost reports.

m
#> <progress monitor> 20 reports from 1 job (collecting)
d = progress_data(m)
d
#> # A tibble: 20 × 4
#>    job     seq  iter   loss
#>    <chr> <int> <int>  <dbl>
#>  1 fit-1     1     1 0.8
#>  2 fit-1     2     2 0.64
#>  3 fit-1     3     3 0.512
#>  4 fit-1     4     4 0.410
#>  5 fit-1     5     5 0.328
#>  6 fit-1     6     6 0.262
#>  7 fit-1     7     7 0.210
#>  8 fit-1     8     8 0.168
#>  9 fit-1     9     9 0.134
#> 10 fit-1    10    10 0.107
#> 11 fit-1    11    11 0.0859
#> 12 fit-1    12    12 0.0687
#> 13 fit-1    13    13 0.0550
#> 14 fit-1    14    14 0.0440
#> 15 fit-1    15    15 0.0352
#> 16 fit-1    16    16 0.0281
#> 17 fit-1    17    17 0.0225
#> 18 fit-1    18    18 0.0180
#> 19 fit-1    19    19 0.0144
#> 20 fit-1    20    20 0.0115
setdiff(seq_len(max(d$seq)), d$seq)
#> integer(0)

While jobs are running, progress_app() shows their progress live. Any number of jobs can report to one monitor, each under its own name.

shiny::runApp(progress_app(m))
progress_stop(m)

The monitor’s address changes every time it starts. To keep one address for all your jobs, create keys once with tailcat_keygen(path), which saves them securely and loads them on later calls, and pass them to TailcatServer$new(key = keys) in progress_monitor().

In an R script run with Rscript, rather than at the console, nothing runs the event loop while the script waits, so call tailcat_run() to keep collecting reports, for example tailcat_run(timeout = 3600) for an hour.

proxy: opening a web app on another machine

R is good at serving small web apps and APIs, with plumber or httpuv, but an app started on a workstation, a cluster node, or a cloud machine usually listens only on that machine. With proxy, the machine running the app calls proxy_share(), which prints an address; on your own machine proxy_open() takes that address and gives you a local URL, and requests to it reach the app as if you were sitting at the other machine.

Each request goes over its own tailcat connection, as two messages: a small JSON head with the method, path, and headers, then the body as raw bytes. The response comes back the same way, with the status and headers in the head. Keeping the body out of the JSON means it needs no encoding and its size limit can be checked before it is read. Both sides use the same two functions to send and receive one of these pairs.

proxy_port = 4406L

proxy_send = function(conn, head, body) {
  # Sends one request or response: a JSON head, then the body as its own message

  head$headers = I(head$headers)
  head = jsonlite::toJSON(head, auto_unbox = TRUE)
  conn$write_message(head, timeout = 60)$write_message(body, timeout = 60)
}

proxy_receive = function(conn, max_bytes) {
  # Reads one request or response sent with proxy_send(), or NULL if the other side closed the
  # connection first

  head = conn$read_message(timeout = 60, as = "text", max_bytes = 65536)
  if (is.null(head)) {
    return(NULL)
  }
  head = jsonlite::fromJSON(head)
  head$headers = as.character(unlist(head$headers))
  head$body = conn$read_message(timeout = 60, max_bytes = max_bytes)
  head
}

Headers travel as "Name: value" lines, as in HTTP itself, which keeps repeated headers such as Set-Cookie intact. A few headers describe a single connection rather than the request, such as Content-Length and Connection; each side’s HTTP library sets those itself, so they are dropped on the way. So is compression: curl asks the app for compressed responses and decompresses them itself, so the encoding headers would no longer match the body.

proxy_drop_headers = c(
  "connection",
  "keep-alive",
  "transfer-encoding",
  "content-length",
  "host",
  "upgrade",
  "accept-encoding",
  "content-encoding"
)

proxy_clean_headers = function(lines) {
  # Drops the headers that each side's HTTP library sets for itself

  names = lines |> sub(pattern = ":.*", replacement = "") |> tolower()
  lines[!names %in% proxy_drop_headers]
}

proxy_header_list = function(lines) {
  # Turns "Name: value" lines into the named list that curl and httpuv take

  values = sub("^[^:]*:[[:space:]]*", "", lines)
  stats::setNames(as.list(values), sub(":.*", "", lines))
}

proxy_error = function(e) {
  # A 502 response saying why the proxy could not get an answer

  list(
    status = 502L,
    headers = "Content-Type: text/plain; charset=utf-8",
    body = charToRaw(paste("The proxy could not reach the app:", conditionMessage(e)))
  )
}

On the machine with the app, a server accepts one connection per request, replays the request against the app on 127.0.0.1 with curl, and sends back whatever the app answered.

proxy_forward = function(request, app_port) {
  # Replays a request against the app on this machine and returns the app's response

  # The path comes from the other side; a path that does not start with "/", such as
  # "@example.com/", would change the host the request goes to
  if (!startsWith(request$path, "/")) {
    stop("The request path must start with \"/\".")
  }
  handle = curl::new_handle(customrequest = request$method, followlocation = FALSE)
  curl::handle_setheaders(handle, .list = proxy_header_list(request$headers))
  if (length(request$body) > 0) {
    curl::handle_setopt(handle, copypostfields = request$body)
  }
  url = paste0("http://127.0.0.1:", app_port, request$path)
  res = curl::curl_fetch_memory(url, handle = handle)
  headers = curl::parse_headers(res$headers)[-1]
  list(status = res$status_code, headers = proxy_clean_headers(headers), body = res$content)
}

proxy_answer = function(conn, app_port, max_bytes) {
  # Answers one request that arrived on `conn` and closes the connection

  on.exit(conn$close())
  request = proxy_receive(conn, max_bytes)
  if (is.null(request)) {
    return(invisible())
  }
  response = tryCatch(proxy_forward(request, app_port), error = proxy_error)
  proxy_send(conn, response[c("status", "headers")], response$body)
}

proxy_share = function(app_port, max_bytes = 1e8) {
  # Makes the app listening on `app_port` of this machine reachable through a new address

  srv = TailcatServer$new()
  lst = srv$listen(proxy_port)
  lst$serve(\(conn) proxy_answer(conn, app_port, max_bytes))
  address = tailcat_reveal(srv$address)
  cli::cli_inform(c(
    "Sharing the app on port {app_port}. Address for the other machine:",
    "{address}"
  ))
  new_proxy(srv, paste("sharing the app on port", app_port))
}

new_proxy = function(node, what, http = NULL) {
  # One end of a proxy: its tailcat server or client, and on the opening side the local web server

  structure(list(node = node, what = what, http = http), class = "proxy")
}

print.proxy = function(x, ...) {
  # Shows what the proxy does, and whether it has been closed

  state = if (x$node$is_closed) " (closed)" else ""
  cat("<proxy> ", x$what, state, "\n", sep = "")
  invisible(x)
}

proxy_close = function(proxy) {
  # Stops either end of a proxy and returns it

  if (!is.null(proxy$http)) {
    httpuv::stopServer(proxy$http)
  }
  proxy$node$close()
  invisible(proxy)
}

Both ends of a proxy are the same kind of object, so one proxy_close() stops either, and printing one says what it is doing.

Anyone with the address can use the app through it, so share the address only with people who may use the app. The proxy only ever connects to the one port it was given on 127.0.0.1, and it checks the path because a path that does not start with / would turn the URL into one for another host.

On your machine, proxy_open() starts a small httpuv server on 127.0.0.1 whose only job is to pass each request on: it dials the other side, sends the request, and hands the response back to httpuv. If anything fails on the way, the browser gets a 502 response that says why.

proxy_fetch = function(cl, req) {
  # Sends one request from httpuv to the other machine and returns the response for httpuv

  request = list(
    method = req$REQUEST_METHOD,
    path = paste0(req$PATH_INFO, req$QUERY_STRING),
    headers = proxy_clean_headers(paste0(names(req$HEADERS), ": ", req$HEADERS))
  )
  body = req$rook.input$read()
  response = tryCatch(
    {
      conn = cl$dial(proxy_port, timeout = 30)
      on.exit(conn$close())
      proxy_send(conn, request, body)
      response = proxy_receive(conn, max_bytes = Inf)
      if (is.null(response)) {
        stop("The other side closed the connection.")
      }
      response
    },
    error = proxy_error
  )
  list(
    status = as.integer(response$status),
    headers = proxy_header_list(response$headers),
    body = response$body
  )
}

proxy_open = function(address, port = 8080L) {
  # Serves the app shared at `address` on http://127.0.0.1:`port` of this machine

  cl = TailcatClient$new(address)
  http = httpuv::startServer("127.0.0.1", port, list(call = \(req) proxy_fetch(cl, req)))
  cli::cli_inform("Open {.url http://127.0.0.1:{port}} to use the app on the other machine.")
  new_proxy(cl, paste0("serving http://127.0.0.1:", port), http)
}

The functions handle one request at a time on each side, which is plenty for one person using an app; an app that keeps many requests in flight would call for the _async() methods and returning promises to httpuv. Only plain HTTP is forwarded. WebSockets, which Shiny apps use, need the connection to stay open in both directions, which would mean forwarding raw bytes instead of requests.

Using it

On the machine with the app, the app has to run in its own R process: proxy_share() waits for the app while it answers a request, and an app in the same process could not answer at that moment. Here a tiny httpuv app, started in the background with callr, stands in for a real one such as a plumber API.

library(rtailcat)
app = callr::r_bg(\() {
  httpuv::runServer("127.0.0.1", 8000, list(call = \(req) {
    list(
      status = 200L,
      headers = list("Content-Type" = "text/plain"),
      body = paste("Hello from the app; you asked for", req$PATH_INFO)
    )
  }))
})
shared = proxy_share(8000)
#> Sharing the app on port 8000. Address for the other machine:
#> tcAbC...xYz
shared
#> <proxy> sharing the app on port 8000

On your machine, open the proxy with that address. Then point a browser at the URL it prints.

library(rtailcat)
p = proxy_open("tcAbC...xYz", port = 8080)
#> Open <http://127.0.0.1:8080> to use the app on the other machine.
browseURL("http://127.0.0.1:8080/hello")

From R the request has to come from another process, for the same reason as on the other side: the proxy answers it in this session, while the session waits.

fetch = callr::r_bg(\() readLines("http://127.0.0.1:8080/hello", warn = FALSE))
tailcat_run(until = \() !fetch$is_alive(), timeout = 30)
fetch$get_result()
#> [1] "Hello from the app; you asked for /hello"
proxy_close(p)
proxy_close(shared)
invisible(app$kill())