R/update-feed.R

Defines functions check_updates_exported check_update_version stop_update_feed start_update_feed stop_update_feed_server try_update_feed_cleanup abort_update_feed_failed read_update_feed_error read_update_feed_address supervise_update_feed_server start_update_feed_server update_feed_server_script remove_dev_update_config write_dev_update_config check_dev_update_config_free dev_update_config_path is_dev_update_config_ours write_update_feed write_lf_lines check_feed_url check_feed_slug check_feed_version check_feed_value yaml_quote

Documented in abort_update_feed_failed check_dev_update_config_free check_feed_value check_updates_exported check_update_version dev_update_config_path is_dev_update_config_ours read_update_feed_address read_update_feed_error remove_dev_update_config start_update_feed start_update_feed_server stop_update_feed stop_update_feed_server supervise_update_feed_server try_update_feed_cleanup update_feed_server_script write_dev_update_config write_lf_lines write_update_feed yaml_quote

#' First line of a `dev-app-update.yml` written by the package
#'
#' Only a file whose first line is exactly this text is ever replaced or
#' removed by the package.
#'
#' @keywords internal
DEV_UPDATE_CONFIG_MARKER <- paste(
  "# Written by shinyelectron::run_electron_app() for a development update",
  "check; removed when the run ends."
)

# SHA-512 of an empty file, which is all the development feed points at
EMPTY_FILE_SHA512 <- paste0(
  "z4PhNX7vuL3xVChQ1m2AB9Yg5AULVxXcg/SpIdNs6c5H0NE8XYXysP+DGNKHfuwvY7kxvUdB",
  "eoGlODJ6+SfaPg=="
)

#' Quote a string as a YAML single-quoted scalar
#'
#' Quoting keeps a reader from taking a slug such as `true` or `123` for a
#' boolean or number, or the `releaseDate` timestamp for a date. It is not an
#' escape: callers validate every value first, because a newline would be
#' folded to a space and a control character would make the reader throw.
#'
#' @param x Character scalar.
#' @return Character scalar.
#' @keywords internal
yaml_quote <- function(x) {
  paste0("'", gsub("'", "''", x, fixed = TRUE), "'")
}

#' Abort unless a value is a single string matching a pattern
#'
#' The match is on bytes with PCRE and `\\z`, so non-ASCII text, a trailing
#' newline and a control character never match.
#'
#' @param x Value to check.
#' @param pattern PCRE pattern, anchored with `^` and `\\z`.
#' @param arg Argument name for the message.
#' @param class Condition class.
#' @param hint Text saying what is accepted.
#' @keywords internal
check_feed_value <- function(x, pattern, arg, class, hint) {
  ok <- is.character(x) && length(x) == 1L && !is.na(x) &&
    grepl(pattern, x, perl = TRUE, useBytes = TRUE)
  if (!ok) {
    shown <- if (is.character(x) && length(x) == 1L && !is.na(x)) {
      encodeString(x, quote = '"')
    } else {
      "a value that is not a single string"
    }
    cli::cli_abort(
      c(
        "{.arg {arg}} is not usable in an update feed: {shown}",
        "i" = hint
      ),
      class = class
    )
  }
  invisible(x)
}

check_feed_version <- function(version) {
  check_feed_value(version, "^[0-9]+\\.[0-9]+\\.[0-9]+(-[0-9A-Za-z.-]+)?\\z",
    "version", "shinyelectron_update_feed_bad_version",
    "Use digits and dots such as {.val 1.2.3}, optionally with a pre-release part such as {.val 1.2.3-beta.1}.")
}

check_feed_slug <- function(app_slug) {
  check_feed_value(app_slug, "^[a-z0-9]([a-z0-9-]*[a-z0-9])?\\z",
    "app_slug", "shinyelectron_update_feed_bad_slug",
    "Use lowercase letters, numbers and inner hyphens.")
}

check_feed_url <- function(url) {
  check_feed_value(url, "^https?://[A-Za-z0-9.:\\[\\]-]+(/[A-Za-z0-9._~/-]*)?\\z",
    "url", "shinyelectron_update_feed_bad_url",
    "Use an http:// or https:// address of plain ASCII characters, without spaces, quotes or {.code #}.")
}

#' Write lines with LF endings on every platform
#'
#' @param lines Character vector.
#' @param path File to write.
#' @keywords internal
write_lf_lines <- function(lines, path) {
  con <- file(path, open = "wb")
  on.exit(close(con), add = TRUE)
  writeLines(lines, con, sep = "\n", useBytes = TRUE)
}

#' Write the update feed files electron-updater's generic provider reads
#'
#' Writes `latest.yml`, `latest-mac.yml`, `latest-linux.yml` and
#' `latest-linux-arm64.yml`, each offering `version` with an installer that is
#' not served, so a check finds the update and a download fails.
#'
#' @param dir Folder to write into, created if needed.
#' @param version Version to offer: three numbers separated by dots, optionally
#'   followed by a hyphen and a pre-release part of letters, digits, dots and
#'   hyphens, such as `"1.2.3"` or `"1.2.3-beta.1"`.
#' @param app_slug App name used in the installer file names. Lowercase
#'   letters, numbers and inner hyphens.
#' @return `dir`, invisibly.
#' @keywords internal
write_update_feed <- function(dir, version, app_slug) {
  check_feed_version(version)
  check_feed_slug(app_slug)
  dir.create(dir, recursive = TRUE, showWarnings = FALSE)
  installers <- c(
    "latest.yml" = paste0(app_slug, "-Setup-", version, "-x64.exe"),
    "latest-mac.yml" = paste0(app_slug, "-", version, "-arm64.dmg"),
    "latest-linux.yml" = paste0(app_slug, "-", version, "-x86_64.AppImage"),
    "latest-linux-arm64.yml" = paste0(app_slug, "-", version, "-arm64.AppImage")
  )
  released <- format(Sys.time(), "%Y-%m-%dT%H:%M:%OS3Z", tz = "UTC")
  for (file in names(installers)) {
    installer <- yaml_quote(installers[[file]])
    sha <- yaml_quote(EMPTY_FILE_SHA512)
    write_lf_lines(c(
      paste0("version: ", yaml_quote(version)),
      "files:",
      paste0("  - url: ", installer),
      paste0("    sha512: ", sha),
      "    size: 0",
      paste0("path: ", installer),
      paste0("sha512: ", sha),
      paste0("releaseDate: ", yaml_quote(released))
    ), file.path(dir, file))
  }
  invisible(dir)
}

#' Is a `dev-app-update.yml` one the package wrote?
#'
#' True only when the file's first line is exactly the marker. A carriage
#' return is accepted only directly before the line feed that ends the line,
#' since a file written on Windows may come back with CRLF. Anything else
#' (trailing spaces, a carriage return with no line feed after it, the marker
#' on a later line, an empty or unreadable file, a folder, a symbolic link) is
#' the author's.
#'
#' @param path Path to the file.
#' @return `TRUE` or `FALSE`.
#' @keywords internal
is_dev_update_config_ours <- function(path) {
  if (!is.na(Sys.readlink(path)) && nzchar(Sys.readlink(path))) {
    return(FALSE)
  }
  if (!file.exists(path) || dir.exists(path)) {
    return(FALSE)
  }
  marker <- charToRaw(DEV_UPDATE_CONFIG_MARKER)
  bytes <- tryCatch(
    readBin(path, "raw", n = length(marker) + 2L),
    error = function(e) raw(0),
    warning = function(w) raw(0)
  )
  end <- match(as.raw(10), bytes, nomatch = 0L)
  if (end == 0L) {
    return(identical(bytes, marker))
  }
  first <- bytes[seq_len(end - 1L)]
  if (length(first) > 0 && first[length(first)] == as.raw(13)) {
    first <- first[-length(first)]
  }
  identical(first, marker)
}

#' Path of the development update config in an app folder
#'
#' @param app_dir App folder.
#' @return Path string.
#' @keywords internal
dev_update_config_path <- function(app_dir) {
  file.path(app_dir, "dev-app-update.yml")
}

#' Stop when the app folder holds a `dev-app-update.yml` the package did not write
#'
#' @param app_dir App folder.
#' @return The path of `dev-app-update.yml`, invisibly.
#' @keywords internal
check_dev_update_config_free <- function(app_dir) {
  path <- dev_update_config_path(app_dir)
  # A link (even a dangling one) is tested with Sys.readlink(), since
  # file.exists() follows it.
  occupied <- file.exists(path) || (!is.na(Sys.readlink(path)) && nzchar(Sys.readlink(path)))
  if (occupied && !is_dev_update_config_ours(path)) {
    cli::cli_abort(
      c(
        "{.path {path}} already exists and was not written by shinyelectron.",
        "i" = "Move or rename it, then run again. It is not changed or removed."
      ),
      class = "shinyelectron_dev_update_config_exists"
    )
  }
  invisible(path)
}

#' Write `dev-app-update.yml`, pointing an unpackaged app at a local feed
#'
#' Replaces a file the package wrote earlier; stops on any other. The updater
#' cache folder is `<app_slug>-dev-updater`, not the `<app_slug>-updater` that
#' an installed copy of the app uses, so a download tried in a development run
#' never touches an update the installed copy has already downloaded.
#'
#' @param app_dir App folder.
#' @param url Address of the feed, such as `"http://127.0.0.1:43210/"`.
#' @param app_slug Name of the app's `package.json`, as a slug.
#' @return The path written, invisibly.
#' @keywords internal
write_dev_update_config <- function(app_dir, url, app_slug) {
  check_feed_url(url)
  check_feed_slug(app_slug)
  # The check and the write are not atomic: R cannot create a file
  # exclusively, and the window is the time between these two adjacent calls.
  path <- check_dev_update_config_free(app_dir)
  write_lf_lines(c(
    DEV_UPDATE_CONFIG_MARKER,
    "provider: generic",
    paste0("url: ", yaml_quote(url)),
    paste0("updaterCacheDirName: ", yaml_quote(paste0(app_slug, "-dev-updater")))
  ), path)
  invisible(path)
}

#' Remove `dev-app-update.yml` if the package wrote it
#'
#' @param app_dir App folder.
#' @return `TRUE` invisibly if a file was removed, otherwise `FALSE`.
#' @keywords internal
remove_dev_update_config <- function(app_dir) {
  path <- dev_update_config_path(app_dir)
  if (!is_dev_update_config_ours(path)) {
    return(invisible(FALSE))
  }
  invisible(file.remove(path))
}

#' Path of the local update feed server script
#'
#' @return Path to `update-feed-server.js`, or `""` if it cannot be found.
#' @keywords internal
update_feed_server_script <- function() {
  system.file("electron", "tools", "update-feed-server.js", package = "shinyelectron")
}

#' Start the local update feed server
#'
#' Runs `update-feed-server.js` with Node.js to serve `dir` on `127.0.0.1` at
#' a free port, and waits for the address it prints.
#'
#' The server does not outlive the R session that started it. It is started
#' and held with interrupts suspended, so from then on an error or an
#' interrupt before its address arrives kills it here, and
#' [stop_update_feed_server()] kills it later. Supervision is set up after
#' that, since it can take a moment the first time and can fail; a failure
#' ends the server and is reported as such. If the returned list is garbage
#' collected, processx kills the server, so keep the list for as long as the
#' feed is in use. If R exits or dies without running exit handlers,
#' processx's supervisor kills the server, and the server also exits by itself
#' once R's end of its standard input closes. Only R holds that end: processx
#' keeps it from being inherited by any other child process.
#'
#' @param dir Folder to serve.
#' @param timeout Seconds to wait for the address.
#' @return A list with `process`, the [processx::process] running the server,
#'   and `url`, its address, such as `"http://127.0.0.1:43210/"`.
#' @keywords internal
start_update_feed_server <- function(dir, timeout = 10) {
  frame <- rlang::current_env()
  script <- update_feed_server_script()
  # Node.js reads its program from standard input when given an empty path,
  # and would wait there until the timeout.
  if (!nzchar(script)) {
    cli::cli_abort(
      "Could not find {.file update-feed-server.js} in the shinyelectron installation.",
      class = "shinyelectron_update_feed_failed"
    )
  }
  server <- list(process = NULL, url = NULL)
  started <- FALSE
  on.exit(if (!started) stop_update_feed_server(server), add = TRUE)
  suspendInterrupts(
    server$process <- tryCatch(
      processx::process$new(
        get_node_command(),
        c(script, dir),
        stdin = "|", stdout = "|", stderr = "|",
        cleanup = TRUE, supervise = FALSE
      ),
      error = function(e) {
        cli::cli_abort(
          "Could not run Node.js to serve the local update feed.",
          parent = e, class = "shinyelectron_update_feed_failed", call = frame
        )
      }
    )
  )
  tryCatch(
    supervise_update_feed_server(server$process),
    error = function(e) {
      cli::cli_abort(
        "Could not register the local update feed server with the processx supervisor.",
        parent = e, class = "shinyelectron_update_feed_failed", call = frame
      )
    }
  )
  server$url <- read_update_feed_address(server$process, timeout)
  started <- TRUE
  server
}

#' Register the update feed server with the processx supervisor
#'
#' The supervisor kills the server if R exits or dies without running exit
#' handlers. Registering can fail, for example when antivirus software blocks
#' the supervisor on Windows; [start_update_feed_server()] then ends the
#' server and reports it.
#'
#' @param process The [processx::process] running the server.
#' @keywords internal
supervise_update_feed_server <- function(process) {
  process$supervise(TRUE)
}

#' Wait for the update feed server's address
#'
#' Reads the server's standard output until a whole line arrives, the output
#' ends, or `timeout` seconds pass, and returns as soon as one of these
#' happens. The line is the address only if it is exactly
#' `http://127.0.0.1:<port>/` once a carriage return before its line feed is
#' dropped. Anything else aborts, quoting the server's standard error.
#'
#' @param process The [processx::process] running the server.
#' @param timeout Seconds to wait.
#' @return The address.
#' @keywords internal
read_update_feed_address <- function(process, timeout) {
  call <- rlang::caller_env()
  out <- ""
  err <- ""
  deadline <- Sys.time() + timeout
  repeat {
    out <- paste0(out, process$read_output())
    err <- paste0(err, process$read_error())
    newline <- regexpr("\n", out, fixed = TRUE)
    if (newline > 0) {
      line <- sub("\r$", "", substr(out, 1, newline - 1))
      if (grepl("^http://127\\.0\\.0\\.1:[0-9]+/$", line)) {
        return(line)
      }
      abort_update_feed_failed(
        cli::format_inline("It printed {.val {line}} instead of its address."),
        err, call
      )
    }
    if (!process$is_incomplete_output()) {
      err <- read_update_feed_error(process, err)
      process$wait(1000)
      status <- process$get_exit_status()
      problem <- if (is.null(status)) {
        "It closed its output without printing its address."
      } else {
        cli::format_inline("It exited with status {status} before printing its address.")
      }
      abort_update_feed_failed(problem, err, call)
    }
    left <- as.numeric(difftime(deadline, Sys.time(), units = "secs"))
    if (left <= 0) {
      abort_update_feed_failed(
        cli::format_inline("It printed no address within {timeout} second{?s}."),
        err, call
      )
    }
    pipes <- list(process$get_output_connection(), process$get_error_connection())
    processx::poll(
      Filter(processx::processx_conn_is_incomplete, pipes),
      as.integer(ceiling(left * 1000))
    )
  }
}

#' Read what is left of the update feed server's standard error
#'
#' @param process The [processx::process] running the server.
#' @param err Standard error read so far.
#' @param wait Seconds to wait for the end of the output.
#' @return `err` with the rest appended.
#' @keywords internal
read_update_feed_error <- function(process, err, wait = 2) {
  deadline <- Sys.time() + wait
  while (process$is_incomplete_error() && Sys.time() < deadline) {
    processx::poll(list(process$get_error_connection()), 100L)
    err <- paste0(err, process$read_error())
  }
  err
}

#' Abort because the update feed server did not start
#'
#' @param problem What went wrong, as text already formatted.
#' @param stderr What the server wrote to standard error.
#' @param call Call to name in the error.
#' @keywords internal
abort_update_feed_failed <- function(problem, stderr, call) {
  lines <- strsplit(stderr, "\r?\n")[[1]]
  lines <- lines[nzchar(trimws(lines))]
  shown <- utils::head(lines, 20)
  hidden <- length(lines) - length(shown)
  # Each line is inserted as a value, so braces in it are not read as markup.
  details <- if (length(shown) == 0) {
    c("i" = "It wrote nothing to standard error.")
  } else {
    c(
      "i" = "Its standard error:",
      stats::setNames(sprintf("{shown[[%d]]}", seq_along(shown)), rep(" ", length(shown))),
      if (hidden > 0) c(" " = "and {hidden} more line{?s}")
    )
  }
  cli::cli_abort(
    c("The local update feed server did not start.", "x" = "{problem}", details),
    class = "shinyelectron_update_feed_failed",
    stderr = stderr,
    call = call
  )
}

#' Run one step of tearing down a development update feed
#'
#' A failure is reported as a message instead of an error, so the other steps
#' still run and an exit handler never hides the error that ended the run.
#'
#' @param expr The step.
#' @param what What the step does, as plain text.
#' @return `NULL`, invisibly.
#' @keywords internal
try_update_feed_cleanup <- function(expr, what) {
  report <- function(cnd) {
    cli::cli_alert_warning("Could not {what}: {conditionMessage(cnd)}")
  }
  tryCatch(expr, error = report, warning = report)
  invisible(NULL)
}

#' Stop the local update feed server
#'
#' Kills the server if it is still running and closes R's ends of its pipes.
#' A server that already exited, for whatever reason, is only let go of. Safe
#' to call more than once and on `NULL`, and never throws, since it runs from
#' exit handlers. An interrupt that arrives meanwhile is held until it is done.
#'
#' @param server A list from [start_update_feed_server()], or `NULL`.
#' @return `NULL`, invisibly.
#' @keywords internal
stop_update_feed_server <- function(server) {
  process <- if (is.list(server)) server$process
  if (inherits(process, "process")) {
    suspendInterrupts(
      try_update_feed_cleanup(process$kill(), "stop the local update feed server")
    )
  }
  invisible(NULL)
}

#' Set up a development update feed for an app
#'
#' Checks that the app folder holds no `dev-app-update.yml` of the author's
#' before anything is written or started, then writes the feed files to a new
#' temporary folder, starts the server on it, and writes `dev-app-update.yml`
#' pointing at the server. If a later step fails or is interrupted, the earlier
#' ones are undone.
#'
#' The result holds the server's process object, and a collected process
#' object ends the server, so keep the result referenced until
#' [stop_update_feed()] is called on it. Register that call with `on.exit()`
#' before starting the feed, with the variable set to `NULL` first, which
#' [stop_update_feed()] accepts:
#'
#' ```r
#' feed <- NULL
#' on.exit(stop_update_feed(feed), add = TRUE)
#' feed <- start_update_feed(app_dir, version, app_slug)
#' ```
#'
#' @param app_dir App folder.
#' @param version Version the feed offers, such as `"2.0.0"`.
#' @param app_slug Name of the app's `package.json`, as a slug.
#' @return A list with `app_dir`, `dir` (the feed folder) and `server` (from
#'   [start_update_feed_server()]).
#' @keywords internal
start_update_feed <- function(app_dir, version, app_slug) {
  check_dev_update_config_free(app_dir)
  feed <- list(app_dir = app_dir, dir = tempfile("shinyelectron-update-feed-"), server = NULL)
  ready <- FALSE
  on.exit(if (!ready) stop_update_feed(feed), add = TRUE)
  write_update_feed(feed$dir, version, app_slug)
  feed$server <- start_update_feed_server(feed$dir)
  write_dev_update_config(app_dir, feed$server$url, app_slug)
  ready <- TRUE
  feed
}

#' Tear down a development update feed
#'
#' Removes `dev-app-update.yml` if the package wrote it, stops the server and
#' removes the feed folder. An author's own `dev-app-update.yml`, including one
#' put in place during the run, is left alone. Safe in any state: twice, on
#' `NULL`, on a feed whose server never started or already exited, and with
#' the folder already gone. A step that fails is reported as a message and the
#' others still run, so it never throws from an exit handler. The steps run
#' with interrupts suspended, so a second Ctrl+C during teardown is held until
#' every step has run.
#'
#' @param feed A list from [start_update_feed()], or `NULL`.
#' @return `NULL`, invisibly.
#' @keywords internal
stop_update_feed <- function(feed) {
  if (!is.list(feed)) {
    return(invisible(NULL))
  }
  suspendInterrupts({
    if (!is.null(feed$app_dir)) {
      try_update_feed_cleanup(remove_dev_update_config(feed$app_dir), "remove dev-app-update.yml")
    }
    stop_update_feed_server(feed$server)
    if (!is.null(feed$dir)) {
      try_update_feed_cleanup(unlink(feed$dir, recursive = TRUE), "remove the update feed folder")
    }
  })
  invisible(NULL)
}

#' Abort unless a version can be offered by a development update feed
#'
#' Accepts one string of three numbers separated by dots, such as `"2.0.0"`,
#' and nothing else: no leading `v`, no pre-release part, no `NA`.
#'
#' @param version Value given as `update_version` to [run_electron_app()].
#' @return `version`, invisibly.
#' @keywords internal
check_update_version <- function(version) {
  check_feed_value(version, "^[0-9]+\\.[0-9]+\\.[0-9]+\\z",
    "update_version", "shinyelectron_invalid_update_version",
    "Use three numbers separated by dots, such as {.val 2.0.0}, with no {.val v} in front and no pre-release part.")
}

#' Abort unless an app was exported with auto-updates on, by this version
#'
#' An app exported without them does not depend on electron-updater and has no
#' update check to try. An app exported with them by an earlier shinyelectron
#' has a `main.js` that never turns on electron-updater's
#' `forceDevUpdateConfig`, so it would not read the local feed.
#'
#' @param package_json The app's `package.json`, as a list.
#' @param app_dir App folder, named in the message.
#' @return `package_json`, invisibly.
#' @keywords internal
check_updates_exported <- function(package_json, app_dir) {
  dependencies <- package_json$dependencies
  if (!is.list(dependencies) || is.null(dependencies[["electron-updater"]])) {
    cli::cli_abort(
      c(
        "{.path {app_dir}} was exported without auto-updates, so it has no update check to try.",
        "i" = "Turn them on with {.fn enable_auto_updates}, then run {.fn export} again."
      ),
      class = "shinyelectron_updates_not_exported"
    )
  }
  main_js <- file.path(app_dir, "main.js")
  reads_dev_feed <- file.exists(main_js) && !dir.exists(main_js) && any(grepl(
    "forceDevUpdateConfig",
    tryCatch(readLines(main_js, warn = FALSE), error = function(e) character(0)),
    fixed = TRUE, useBytes = TRUE
  ))
  if (!reads_dev_feed) {
    cli::cli_abort(
      c(
        "{.path {app_dir}} was exported by an earlier version of shinyelectron, so it cannot read a local update feed.",
        "i" = "Run {.fn export} again with this version."
      ),
      class = "shinyelectron_updates_not_exported"
    )
  }
  invisible(package_json)
}

Try the shinyelectron package in your browser

Any scripts or data that you put into this service are public.

shinyelectron documentation built on Dec. 3, 2026, 9:07 a.m.