tests/testthat/test-update-feed.R

empty_sha512 <- "z4PhNX7vuL3xVChQ1m2AB9Yg5AULVxXcg/SpIdNs6c5H0NE8XYXysP+DGNKHfuwvY7kxvUdBeoGlODJ6+SfaPg=="

write_author_file <- function(path, text) {
  writeBin(charToRaw(text), path)
  path
}

test_that("write_update_feed writes the file each platform asks for, offering the version", {
  dir <- file.path(withr::local_tempdir(), "feed")
  write_update_feed(dir, "2.0.0", "update-check")
  installers <- c(
    "latest.yml" = "update-check-Setup-2.0.0-x64.exe",
    "latest-mac.yml" = "update-check-2.0.0-arm64.dmg",
    "latest-linux.yml" = "update-check-2.0.0-x86_64.AppImage",
    "latest-linux-arm64.yml" = "update-check-2.0.0-arm64.AppImage"
  )
  expect_setequal(list.files(dir), names(installers))
  for (f in names(installers)) {
    feed <- yaml::read_yaml(file.path(dir, f))
    expect_identical(feed$version, "2.0.0")
    expect_equal(feed$files, list(list(url = installers[[f]], sha512 = empty_sha512, size = 0L)))
    expect_identical(feed$path, installers[[f]])
    expect_identical(feed$sha512, empty_sha512)
    expect_match(feed$releaseDate, "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$")
  }
})

test_that("write_update_feed returns the folder invisibly", {
  dir <- file.path(withr::local_tempdir(), "feed")
  expect_invisible(out <- write_update_feed(dir, "2.0.0", "app"))
  expect_identical(out, dir)
})

test_that("write_update_feed writes the version, timestamp and size so a YAML reader takes them as intended", {
  for (v in c("1.10.0", "10.0.0", "2.0.0", "0.0.1")) {
    dir <- file.path(withr::local_tempdir(), "feed")
    write_update_feed(dir, v, "app")
    text <- readLines(file.path(dir, "latest.yml"))
    expect_true(paste0("version: '", v, "'") %in% text)
    expect_true("    size: 0" %in% text)
    expect_match(text[grepl("^releaseDate:", text)], "^releaseDate: '[^']+'$")
    expect_identical(yaml::read_yaml(file.path(dir, "latest.yml"))$version, v)
  }
})

test_that("write_update_feed writes LF line endings", {
  dir <- file.path(withr::local_tempdir(), "feed")
  write_update_feed(dir, "2.0.0", "app")
  bytes <- readBin(file.path(dir, "latest.yml"), "raw", 10000)
  expect_false(as.raw(13) %in% bytes)
})

test_that("write_dev_update_config points the generic provider at the feed and marks the file", {
  app <- withr::local_tempdir()
  path <- write_dev_update_config(app, "http://127.0.0.1:43210/", "update-check")
  expect_identical(readLines(path, n = 1), DEV_UPDATE_CONFIG_MARKER)
  expect_equal(yaml::read_yaml(path), list(provider = "generic",
    url = "http://127.0.0.1:43210/", updaterCacheDirName = "update-check-dev-updater"))
  expect_identical(basename(path), "dev-app-update.yml")
})

test_that("write_dev_update_config keeps names that look like other YAML types as strings", {
  app <- withr::local_tempdir()
  path <- write_dev_update_config(app, "http://127.0.0.1:1/", "true")
  expect_identical(yaml::read_yaml(path)$updaterCacheDirName, "true-dev-updater")
  path <- write_dev_update_config(app, "http://127.0.0.1:1/", "123")
  expect_identical(yaml::read_yaml(path)$updaterCacheDirName, "123-dev-updater")
})

test_that("write_dev_update_config replaces its own file but never an author's", {
  app <- withr::local_tempdir()
  write_dev_update_config(app, "http://127.0.0.1:43210/", "app")
  path <- write_dev_update_config(app, "http://127.0.0.1:43211/", "app")
  expect_identical(yaml::read_yaml(path)$url, "http://127.0.0.1:43211/")

  other <- withr::local_tempdir()
  authors <- "provider: generic\nurl: https://example.org/"
  path <- write_author_file(file.path(other, "dev-app-update.yml"), authors)
  before <- readBin(path, "raw", 10000)
  expect_error(check_dev_update_config_free(other), class = "shinyelectron_dev_update_config_exists")
  expect_error(write_dev_update_config(other, "http://127.0.0.1:1/", "app"),
    class = "shinyelectron_dev_update_config_exists")
  expect_identical(readBin(path, "raw", 10000), before)
})

test_that("check_dev_update_config_free returns the path when free or ours", {
  app <- withr::local_tempdir()
  expect_invisible(p <- check_dev_update_config_free(app))
  expect_identical(p, file.path(app, "dev-app-update.yml"))
  write_dev_update_config(app, "http://127.0.0.1:1/", "app")
  expect_identical(check_dev_update_config_free(app), p)
})

test_that("a file is the package's only when its first line is exactly the marker", {
  m <- DEV_UPDATE_CONFIG_MARKER
  ours <- list(
    marker_lf = paste0(m, "\nprovider: generic\n"),
    marker_crlf = paste0(m, "\r\nprovider: generic\r\n"),
    only_marker = paste0(m, "\n"),
    only_marker_no_newline = m
  )
  not_ours <- list(
    empty = "",
    trailing_space = paste0(m, " \nprovider: generic\n"),
    trailing_tab_crlf = paste0(m, "\t\r\nprovider: generic\n"),
    lone_cr = paste0(m, "\rprovider: generic\r"),
    marker_then_single_cr = paste0(m, "\r"),
    very_long_first_line = paste0(m, strrep("x", 5000), "\n"),
    double_cr = paste0(m, "\r\r\nprovider: generic\n"),
    second_line = paste0("provider: generic\n", m, "\n"),
    blank_first_line = paste0("\n", m, "\n"),
    bom = paste0("", m, "\n"),
    prefix_only = substr(m, 1, 20),
    marker_continued = paste0(m, " more\n"),
    authors = "provider: generic\n"
  )
  for (nm in names(ours)) {
    app <- withr::local_tempdir()
    path <- write_author_file(file.path(app, "dev-app-update.yml"), ours[[nm]])
    expect_no_error(check_dev_update_config_free(app))
    expect_true(remove_dev_update_config(app), label = nm)
    expect_false(file.exists(path))
  }
  for (nm in names(not_ours)) {
    app <- withr::local_tempdir()
    path <- write_author_file(file.path(app, "dev-app-update.yml"), not_ours[[nm]])
    before <- readBin(path, "raw", 10000)
    expect_error(check_dev_update_config_free(app),
      class = "shinyelectron_dev_update_config_exists")
    expect_error(write_dev_update_config(app, "http://127.0.0.1:1/", "app"),
      class = "shinyelectron_dev_update_config_exists")
    expect_false(remove_dev_update_config(app), label = nm)
    expect_identical(readBin(path, "raw", 10000), before)
  }
})

test_that("a file with a NUL byte or a folder of that name is left alone", {
  app <- withr::local_tempdir()
  path <- file.path(app, "dev-app-update.yml")
  writeBin(as.raw(c(1, 0, 2, 10)), path)
  expect_error(check_dev_update_config_free(app), class = "shinyelectron_dev_update_config_exists")
  expect_false(remove_dev_update_config(app))
  expect_true(file.exists(path))

  app2 <- withr::local_tempdir()
  dir.create(file.path(app2, "dev-app-update.yml"))
  expect_error(check_dev_update_config_free(app2), class = "shinyelectron_dev_update_config_exists")
  expect_false(remove_dev_update_config(app2))
  expect_true(dir.exists(file.path(app2, "dev-app-update.yml")))
})

test_that("the error names the file and asks the author to move it", {
  app <- withr::local_tempdir()
  write_author_file(file.path(app, "dev-app-update.yml"), "provider: generic\n")
  expect_error(check_dev_update_config_free(app), "dev-app-update.yml")
  expect_error(check_dev_update_config_free(app), "[Mm]ove")
})

test_that("remove_dev_update_config removes only the file it wrote", {
  app <- withr::local_tempdir()
  expect_false(remove_dev_update_config(app))
  path <- write_dev_update_config(app, "http://127.0.0.1:1/", "app")
  expect_invisible(removed <- remove_dev_update_config(app))
  expect_true(removed)
  expect_false(file.exists(path))
})

test_that("the written config is found again after Windows turns its line ends into CRLF", {
  app <- withr::local_tempdir()
  path <- write_dev_update_config(app, "http://127.0.0.1:1/", "app")
  text <- readChar(path, file.size(path), useBytes = TRUE)
  expect_false(grepl("\r", text, fixed = TRUE))
  writeBin(charToRaw(gsub("\n", "\r\n", text, fixed = TRUE)), path)
  expect_no_error(check_dev_update_config_free(app))
  expect_true(remove_dev_update_config(app))
})

bad_values <- list(
  quote = "a'b", newline = "a\nb", trailing_newline = "a\n", control = "a\x07b",
  hash = "a#b", space = "a b", non_ascii = "caf\u00e9"
)

test_that("write_update_feed refuses a version that is not x.y.z or x.y.z-pre, writing nothing", {
  for (nm in names(bad_values)) {
    dir <- file.path(withr::local_tempdir(), "feed")
    v <- paste0("1.2.3-", bad_values[[nm]])
    expect_error(write_update_feed(dir, v, "app"),
      class = "shinyelectron_update_feed_bad_version")
    expect_false(dir.exists(dir), label = nm)
  }
  for (v in c("1.2", "v1.2.3", "1.2.3\n", "", NA_character_)) {
    dir <- file.path(withr::local_tempdir(), "feed")
    expect_error(write_update_feed(dir, v, "app"),
      class = "shinyelectron_update_feed_bad_version")
    expect_false(dir.exists(dir))
  }
  dir <- file.path(withr::local_tempdir(), "feed")
  expect_error(write_update_feed(dir, c("1.2.3", "1.2.4"), "app"),
    class = "shinyelectron_update_feed_bad_version")
  expect_false(dir.exists(dir))
  expect_no_error(write_update_feed(dir, "1.2.3-beta.1", "app"))
  expect_identical(yaml::read_yaml(file.path(dir, "latest.yml"))$version, "1.2.3-beta.1")
})

test_that("write_update_feed refuses a slug that is not lower-case letters, digits and inner hyphens", {
  for (nm in names(bad_values)) {
    dir <- file.path(withr::local_tempdir(), "feed")
    expect_error(write_update_feed(dir, "2.0.0", bad_values[[nm]]),
      class = "shinyelectron_update_feed_bad_slug")
    expect_false(dir.exists(dir), label = nm)
  }
  for (v in c("", "-app", "app-", "App", NA_character_)) {
    dir <- file.path(withr::local_tempdir(), "feed")
    expect_error(write_update_feed(dir, "2.0.0", v), class = "shinyelectron_update_feed_bad_slug")
    expect_false(dir.exists(dir))
  }
})

test_that("write_dev_update_config refuses a slug or url with unsafe characters, writing nothing", {
  for (nm in names(bad_values)) {
    app <- withr::local_tempdir()
    expect_error(write_dev_update_config(app, "http://127.0.0.1:1/", bad_values[[nm]]),
      class = "shinyelectron_update_feed_bad_slug")
    expect_error(write_dev_update_config(app, paste0("http://127.0.0.1:1/", bad_values[[nm]]), "app"),
      class = "shinyelectron_update_feed_bad_url")
    expect_false(file.exists(file.path(app, "dev-app-update.yml")), label = nm)
  }
  for (u in c("ftp://127.0.0.1/", "127.0.0.1:1/", "http://", "http://127.0.0.1:1/\n", NA_character_)) {
    app <- withr::local_tempdir()
    expect_error(write_dev_update_config(app, u, "app"), class = "shinyelectron_update_feed_bad_url")
    expect_false(file.exists(file.path(app, "dev-app-update.yml")))
  }
  app <- withr::local_tempdir()
  expect_no_error(write_dev_update_config(app, "https://localhost:8080", "app"))
  expect_no_error(write_dev_update_config(app, "http://[::1]:8080/feed/", "app"))
})

test_that("a refused value leaves an existing config byte for byte as it was", {
  app <- withr::local_tempdir()
  path <- write_dev_update_config(app, "http://127.0.0.1:1/", "app")
  before <- readBin(path, "raw", 10000)
  expect_error(write_dev_update_config(app, "http://127.0.0.1:2/ x", "app"),
    class = "shinyelectron_update_feed_bad_url")
  expect_identical(readBin(path, "raw", 10000), before)
})

test_that("a symbolic link at the path is the author's, whatever it points to", {
  skip_on_os("windows")
  m <- DEV_UPDATE_CONFIG_MARKER
  targets <- list(unmarked = "provider: generic\n", marked = paste0(m, "\nprovider: generic\n"))
  for (nm in names(targets)) {
    app <- withr::local_tempdir()
    target <- write_author_file(file.path(withr::local_tempdir(), "target.yml"), targets[[nm]])
    link <- file.path(app, "dev-app-update.yml")
    skip_if_not(file.symlink(target, link), "cannot make symbolic links")
    before <- readBin(target, "raw", 10000)
    expect_error(check_dev_update_config_free(app), class = "shinyelectron_dev_update_config_exists")
    expect_error(write_dev_update_config(app, "http://127.0.0.1:1/", "app"),
      class = "shinyelectron_dev_update_config_exists")
    expect_false(remove_dev_update_config(app), label = nm)
    expect_identical(readBin(target, "raw", 10000), before)
    expect_true(nzchar(Sys.readlink(link)))
  }
  app <- withr::local_tempdir()
  target <- file.path(withr::local_tempdir(), "missing.yml")
  link <- file.path(app, "dev-app-update.yml")
  skip_if_not(file.symlink(target, link), "cannot make symbolic links")
  expect_error(write_dev_update_config(app, "http://127.0.0.1:1/", "app"),
    class = "shinyelectron_dev_update_config_exists")
  expect_false(remove_dev_update_config(app))
  expect_false(file.exists(target))
  expect_true(nzchar(Sys.readlink(link)))
})

test_that("an unreadable file is the author's", {
  skip_on_os("windows")
  skip_if(Sys.info()[["user"]] == "root", "running as root")
  app <- withr::local_tempdir()
  path <- write_author_file(file.path(app, "dev-app-update.yml"),
    paste0(DEV_UPDATE_CONFIG_MARKER, "\n"))
  Sys.chmod(path, "000")
  withr::defer(Sys.chmod(path, "644"))
  expect_error(check_dev_update_config_free(app), class = "shinyelectron_dev_update_config_exists")
  expect_false(remove_dev_update_config(app))
  expect_true(file.exists(path))
})

# The local feed server --------------------------------------------------------

on_windows <- .Platform$OS.type == "windows"

skip_if_no_feed_node <- function() {
  skip_on_cran()
  skip_if_not(nzchar(Sys.which(get_node_command())), "Node.js not available")
}

# An R started as a shell background job (`Rscript ... &`, `nohup`) ignores
# interrupts, and so does every R it starts, so a child R would never see the
# Ctrl+C a test sends it. Asked of a child R, which inherits what the test's
# own child R would.
skip_if_interrupts_ignored <- function() {
  code <- paste0(
    "cat(tryCatch({ tools::pskill(Sys.getpid(), tools::SIGINT); Sys.sleep(2); 'ignored' }, ",
    "interrupt = function(cnd) 'delivered'))"
  )
  rscript <- file.path(R.home("bin"), if (on_windows) "Rscript.exe" else "Rscript")
  probe <- processx::run(rscript, c("--vanilla", "-e", code), error_on_status = FALSE,
    env = c("current", R_TESTS = ""))
  skip_if_not(grepl("delivered", probe$stdout, fixed = TRUE),
    "Interrupts are ignored here, as in an R started as a background job")
}

# Whether a process with this id exists. Asked through Node.js, whose
# process.kill(pid, 0) only tests for the process on every platform, where
# tools::pskill() on Windows would end it.
pid_is_running <- function(pid) {
  code <- sprintf(
    "try { process.kill(%d, 0); } catch (e) { process.exit(e.code === 'EPERM' ? 0 : 1); }",
    as.integer(pid)
  )
  processx::run(get_node_command(), c("-e", code), error_on_status = FALSE)$status == 0
}

wait_until <- function(done, seconds) {
  deadline <- Sys.time() + seconds
  repeat {
    if (done()) return(TRUE)
    if (Sys.time() > deadline) return(FALSE)
    Sys.sleep(0.05)
  }
}

# Ends a process and everything it started. Rscript.exe runs R as a child on
# Windows, so ending only the process would leave R and its server running.
end_process_tree <- function(process) {
  tryCatch(process$kill_tree(), error = function(e) process$kill())
}

# Points update_feed_server_script() at a stand-in that runs `js` and then, like
# the real server, waits until its input ends.
local_fake_feed_server <- function(js, env = parent.frame()) {
  path <- file.path(withr::local_tempdir(.local_envir = env), "fake-feed-server.js")
  writeLines(c(js, "process.stdin.on('end', () => process.exit(0));", "process.stdin.resume();"), path)
  local_mocked_bindings(update_feed_server_script = function() path, .env = env)
  invisible(path)
}

# Records every process start_update_feed_server() starts, so a test can check
# that each ended, and kills them all when the test ends. Read them with
# spied_processes().
local_feed_process_spy <- function(env = parent.frame()) {
  recorder <- mockery::mock(NULL, cycle = TRUE)
  read_address <- read_update_feed_address
  local_mocked_bindings(
    read_update_feed_address = function(process, timeout) {
      recorder(process)
      read_address(process, timeout)
    },
    .env = env
  )
  withr::defer(for (process in spied_processes(recorder)) process$kill(), envir = env)
  recorder
}

spied_processes <- function(recorder) {
  lapply(mockery::mock_args(recorder), `[[`, 1)
}

# A GET over a plain socket, so no proxy setting can send it anywhere else.
feed_get <- function(url, file) {
  port <- as.integer(sub("^http://127\\.0\\.0\\.1:([0-9]+)/$", "\\1", url))
  con <- socketConnection("127.0.0.1", port, open = "r+b", blocking = TRUE, timeout = 5)
  on.exit(close(con))
  request <- sprintf("GET /%s HTTP/1.1\r\nHost: 127.0.0.1:%d\r\nConnection: close\r\n\r\n", file, port)
  writeBin(charToRaw(request), con)
  readLines(con, warn = FALSE)
}

feed_folders <- function() {
  list.files(tempdir(), pattern = "^shinyelectron-update-feed-")
}

test_that("start_update_feed_server reports its address and stop_update_feed_server ends it", {
  skip_if_no_feed_node()
  server <- start_update_feed_server(withr::local_tempdir())
  withr::defer(stop_update_feed_server(server))
  expect_match(server$url, "^http://127\\.0\\.0\\.1:[0-9]+/$")
  expect_true(server$process$is_alive())
  expect_invisible(out <- stop_update_feed_server(server))
  expect_null(out)
  expect_false(server$process$is_alive())
})

test_that("the feed server runs from and serves paths with spaces and backslashes", {
  skip_if_no_feed_node()
  native <- function(path) if (on_windows) normalizePath(path, winslash = "\\") else path
  root <- withr::local_tempdir()
  dir.create(file.path(root, "server script"))
  script <- file.path(root, "server script", "update feed server.js")
  expect_true(file.copy(update_feed_server_script(), script))
  script <- native(script)
  local_mocked_bindings(update_feed_server_script = function() script)
  # A backslash separates folders on Windows and is an ordinary character elsewhere.
  dir <- file.path(root, if (on_windows) "feed folder" else "feed \\ folder")
  write_update_feed(dir, "2.0.0", "app")

  server <- start_update_feed_server(native(dir))
  withr::defer(stop_update_feed_server(server))
  response <- feed_get(server$url, "latest.yml")
  expect_identical(response[[1]], "HTTP/1.1 200 OK")
  expect_true("version: '2.0.0'" %in% response)
})

test_that("the feed server ends when R's side of its input closes", {
  skip_if_no_feed_node()
  server <- start_update_feed_server(withr::local_tempdir())
  withr::defer(stop_update_feed_server(server))
  processx::processx_conn_close(server$process$get_input_connection())
  server$process$wait(5000)
  expect_false(server$process$is_alive())
  expect_identical(server$process$get_exit_status(), 0L)
})

test_that("no other child of R holds the feed server's input open", {
  skip_if_no_feed_node()
  server <- start_update_feed_server(withr::local_tempdir())
  withr::defer(stop_update_feed_server(server))
  # Children started after the server, as Electron is: one through processx,
  # one through base R. Each writes a file and exits once that file is gone,
  # so removing the work folder ends the one R has no handle on.
  work <- withr::local_tempdir()
  sleeper <- file.path(work, "sleeper.js")
  writeLines(c(
    "const fs = require('fs');",
    "const file = process.argv[2];",
    "fs.writeFileSync(file, String(process.pid));",
    "setInterval(() => { if (!fs.existsSync(file)) process.exit(0); }, 100);",
    "setTimeout(() => process.exit(0), 60000);"
  ), sleeper)
  other <- processx::process$new(get_node_command(), c(sleeper, file.path(work, "processx.running")))
  withr::defer(other$kill())
  base_running <- file.path(work, "base.running")
  system2(get_node_command(), shQuote(c(sleeper, base_running)), wait = FALSE)
  expect_true(wait_until(function() file.exists(base_running), 10))
  expect_true(other$is_alive())

  processx::processx_conn_close(server$process$get_input_connection())
  server$process$wait(5000)
  expect_false(server$process$is_alive())
})

test_that("a feed server is killed when its handle is garbage collected, not left running", {
  skip_if_no_feed_node()
  dir <- withr::local_tempdir()
  held <- start_update_feed_server(dir)
  withr::defer(stop_update_feed_server(held))
  # Only a weak reference is kept, which does not stop collection; if the
  # process object survives, it is ended through its own handle.
  dropped <- local({
    server <- start_update_feed_server(dir)
    list(pid = server$process$get_pid(), ref = rlang::new_weakref(server$process))
  })
  withr::defer({
    process <- rlang::wref_key(dropped$ref)
    if (!is.null(process)) process$kill()
  })
  gc()
  expect_null(rlang::wref_key(dropped$ref))
  expect_true(wait_until(function() !pid_is_running(dropped$pid), 5))
  expect_true(held$process$is_alive())
})

test_that("start_update_feed_server stops with the server's error when it cannot start", {
  skip_if_no_feed_node()
  spy <- local_feed_process_spy()
  missing <- file.path(withr::local_tempdir(), "no-such-feed")
  err <- expect_error(start_update_feed_server(missing), class = "shinyelectron_update_feed_failed")
  expect_match(conditionMessage(err), "Feed folder not found", fixed = TRUE)
  expect_match(conditionMessage(err), "exited with status 1")
  expect_match(err$stderr, "no-such-feed", fixed = TRUE)

  local_mocked_bindings(update_feed_server_script = function() file.path(tempdir(), "no-such-server.js"))
  err <- expect_error(start_update_feed_server(withr::local_tempdir()),
    class = "shinyelectron_update_feed_failed")
  expect_match(conditionMessage(err), "no-such-server.js", fixed = TRUE)

  processes <- spied_processes(spy)
  expect_length(processes, 2)
  for (process in processes) expect_false(process$is_alive())
})

test_that("start_update_feed_server stops with a classed error when Node.js cannot run", {
  local_mocked_bindings(get_node_command = function(...) file.path(tempdir(), "no-such-node"))
  expect_error(start_update_feed_server(withr::local_tempdir()),
    class = "shinyelectron_update_feed_failed")
})

test_that("a server that cannot be supervised is ended, and the error says supervision failed", {
  skip_if_no_feed_node()
  supervise <- mockery::mock(stop("blocked by antivirus software"))
  local_mocked_bindings(supervise_update_feed_server = supervise)
  withr::defer(for (args in mockery::mock_args(supervise)) args[[1]]$kill())
  err <- expect_error(start_update_feed_server(withr::local_tempdir()), "supervisor",
    class = "shinyelectron_update_feed_failed")
  expect_match(conditionMessage(err$parent), "blocked by antivirus software", fixed = TRUE)
  mockery::expect_called(supervise, 1)
  expect_false(mockery::mock_args(supervise)[[1]][[1]]$is_alive())
})

test_that("start_update_feed_server stops at once when the package has no server script", {
  start <- mockery::mock()
  local_mocked_bindings(update_feed_server_script = function() "", get_node_command = start)
  expect_error(start_update_feed_server(withr::local_tempdir()), "update-feed-server.js",
    class = "shinyelectron_update_feed_failed")
  mockery::expect_called(start, 0)
})

test_that("the address is read when its whole line arrives, without waiting for the timeout", {
  skip_if_no_feed_node()
  # Half the line first, the rest later, ending in CRLF.
  local_fake_feed_server(c(
    "process.stdout.write('http://127.0.0.1:');",
    "setTimeout(() => process.stdout.write('4321/\\r\\n'), 500);"
  ))
  started <- Sys.time()
  server <- start_update_feed_server(withr::local_tempdir(), timeout = 60)
  withr::defer(stop_update_feed_server(server))
  expect_identical(server$url, "http://127.0.0.1:4321/")
  expect_lt(as.numeric(difftime(Sys.time(), started, units = "secs")), 30)
  expect_true(server$process$is_alive())
})

test_that("a partial line is never taken for the address", {
  skip_if_no_feed_node()
  local_fake_feed_server("process.stdout.write('http://127.0.0.1:4321/');")
  spy <- local_feed_process_spy()
  expect_error(start_update_feed_server(withr::local_tempdir(), timeout = 1),
    "within 1 second", class = "shinyelectron_update_feed_failed")
  mockery::expect_called(spy, 1)
  expect_false(spied_processes(spy)[[1]]$is_alive())
})

test_that("a line that is not the address stops the server at once", {
  skip_if_no_feed_node()
  check <- function(line) {
    js <- jsonlite::toJSON(paste0(line, "\n"), auto_unbox = TRUE)
    local_fake_feed_server(paste0("process.stdout.write(", js, ");"))
    spy <- local_feed_process_spy()
    started <- Sys.time()
    err <- expect_error(start_update_feed_server(withr::local_tempdir(), timeout = 60),
      class = "shinyelectron_update_feed_failed")
    expect_lt(as.numeric(difftime(Sys.time(), started, units = "secs")), 30)
    expect_match(conditionMessage(err), trimws(line), fixed = TRUE)
    mockery::expect_called(spy, 1)
    expect_false(spied_processes(spy)[[1]]$is_alive(), label = line)
  }
  check("Listening on 4321")
  check("http://localhost:4321/")
  check("http://127.0.0.1:4321")
  check("http://127.0.0.1:4321/ ")
  check("http://127.0.0.1:/")
  check("{not an address}")
})

test_that("an error or interrupt after the server started kills it", {
  skip_if_no_feed_node()
  dir <- withr::local_tempdir()
  failing <- mockery::mock(stop("boom"))
  local_mocked_bindings(read_update_feed_address = failing)
  expect_error(start_update_feed_server(dir), "boom")
  process <- mockery::mock_args(failing)[[1]][[1]]
  withr::defer(process$kill())
  expect_false(process$is_alive())

  interrupted <- mockery::mock(rlang::interrupt())
  local_mocked_bindings(read_update_feed_address = interrupted)
  result <- tryCatch(start_update_feed_server(dir), interrupt = function(cnd) "interrupted")
  expect_identical(result, "interrupted")
  process <- mockery::mock_args(interrupted)[[1]][[1]]
  withr::defer(process$kill())
  expect_false(process$is_alive())
})

test_that("stop_update_feed_server is quiet without a server, after the server died, and twice", {
  expect_null(stop_update_feed_server(NULL))
  expect_silent(stop_update_feed_server(list(process = NULL, url = "http://127.0.0.1:1/")))
  skip_if_no_feed_node()
  server <- start_update_feed_server(withr::local_tempdir())
  withr::defer(stop_update_feed_server(server))
  # The server ends on its own during the run, as if it crashed.
  tools::pskill(server$process$get_pid())
  server$process$wait(5000)
  expect_false(server$process$is_alive())
  expect_silent(stop_update_feed_server(server))
  expect_silent(stop_update_feed_server(server))
})

# The feed around a run ---------------------------------------------------------

test_that("start_update_feed writes the feed and dev config; stop_update_feed undoes both", {
  app <- withr::local_tempdir()
  server <- list(process = NULL, url = "http://127.0.0.1:43210/")
  start_server <- mockery::mock(server)
  stop_server <- mockery::mock(NULL)
  local_mocked_bindings(start_update_feed_server = start_server, stop_update_feed_server = stop_server)

  feed <- start_update_feed(app, "2.0.0", "update-check")
  mockery::expect_args(start_server, 1, feed$dir)
  expect_identical(feed$app_dir, app)
  expect_identical(feed$server, server)
  expect_identical(yaml::read_yaml(file.path(feed$dir, "latest.yml"))$version, "2.0.0")
  config <- file.path(app, "dev-app-update.yml")
  expect_identical(yaml::read_yaml(config)$url, server$url)

  expect_invisible(out <- stop_update_feed(feed))
  expect_null(out)
  expect_false(dir.exists(feed$dir))
  expect_false(file.exists(config))
  mockery::expect_args(stop_server, 1, server)
})

test_that("start_update_feed stops before starting a server when the author has a dev-app-update.yml", {
  app <- withr::local_tempdir()
  path <- write_author_file(file.path(app, "dev-app-update.yml"), "provider: generic\n")
  before <- readBin(path, "raw", 10000)
  folders <- feed_folders()
  start_server <- mockery::mock(list(process = NULL, url = "http://127.0.0.1:43210/"))
  local_mocked_bindings(start_update_feed_server = start_server)

  expect_error(start_update_feed(app, "2.0.0", "app"), "dev-app-update.yml",
    class = "shinyelectron_dev_update_config_exists")
  mockery::expect_called(start_server, 0)
  expect_identical(readBin(path, "raw", 10000), before)
  expect_setequal(feed_folders(), folders)
})

test_that("start_update_feed stops the server and removes the feed when writing the dev config fails", {
  app <- withr::local_tempdir()
  start_server <- mockery::mock(list(process = NULL, url = "http://127.0.0.1:43210/"))
  stop_server <- mockery::mock(NULL)
  local_mocked_bindings(
    start_update_feed_server = start_server,
    stop_update_feed_server = stop_server,
    write_dev_update_config = function(...) base::stop("disk full")
  )
  expect_error(start_update_feed(app, "2.0.0", "app"), "disk full")
  mockery::expect_called(stop_server, 1)
  expect_false(dir.exists(mockery::mock_args(start_server)[[1]][[1]]))
})

test_that("start_update_feed leaves nothing behind when the version is refused", {
  app <- withr::local_tempdir()
  folders <- feed_folders()
  start_server <- mockery::mock(list(process = NULL, url = "http://127.0.0.1:43210/"))
  local_mocked_bindings(start_update_feed_server = start_server)
  expect_error(start_update_feed(app, "2.0", "app"), class = "shinyelectron_update_feed_bad_version")
  mockery::expect_called(start_server, 0)
  expect_setequal(feed_folders(), folders)
  expect_false(file.exists(file.path(app, "dev-app-update.yml")))
})

test_that("start_update_feed ends a real server when a later step fails or is interrupted", {
  skip_if_no_feed_node()
  start_server <- start_update_feed_server
  check <- function(failure, kind) {
    app <- withr::local_tempdir()
    # Records each folder served and the server started on it.
    started <- mockery::mock(NULL, cycle = TRUE)
    local_mocked_bindings(
      start_update_feed_server = function(dir) {
        server <- start_server(dir)
        started(dir, server)
        server
      },
      write_dev_update_config = failure
    )
    withr::defer(for (args in mockery::mock_args(started)) stop_update_feed_server(args[[2]]))
    result <- tryCatch(start_update_feed(app, "2.0.0", "app"),
      error = function(cnd) "error", interrupt = function(cnd) "interrupt")
    expect_identical(result, kind)
    mockery::expect_called(started, 1)
    args <- mockery::mock_args(started)[[1]]
    expect_false(args[[2]]$process$is_alive(), label = kind)
    expect_false(dir.exists(args[[1]]), label = kind)
    expect_false(file.exists(file.path(app, "dev-app-update.yml")), label = kind)
  }
  check(function(...) base::stop("disk full"), "error")
  check(function(...) rlang::interrupt(), "interrupt")
})

test_that("an interrupt during the run still tears the feed down from on.exit", {
  skip_if_no_feed_node()
  app <- withr::local_tempdir()
  running <- mockery::mock(NULL, cycle = TRUE)
  # The pattern start_update_feed() documents for its callers.
  run <- function() {
    feed <- NULL
    on.exit(stop_update_feed(feed), add = TRUE)
    feed <- start_update_feed(app, "2.0.0", "app")
    running(feed)
    rlang::interrupt()
  }
  withr::defer(for (args in mockery::mock_args(running)) stop_update_feed(args[[1]]))
  expect_identical(tryCatch(run(), interrupt = function(cnd) "interrupted"), "interrupted")
  mockery::expect_called(running, 1)
  feed <- mockery::mock_args(running)[[1]][[1]]
  expect_false(feed$server$process$is_alive())
  expect_false(dir.exists(feed$dir))
  expect_false(file.exists(file.path(app, "dev-app-update.yml")))
})

test_that("stop_update_feed leaves an author's replacement file alone and is safe to repeat", {
  skip_if_no_feed_node()
  app <- withr::local_tempdir()
  feed <- start_update_feed(app, "2.0.0", "app")
  withr::defer(stop_update_feed(feed))
  expect_true(feed$server$process$is_alive())
  expect_identical(yaml::read_yaml(file.path(app, "dev-app-update.yml"))$url, feed$server$url)
  expect_identical(feed_get(feed$server$url, "latest.yml")[[1]], "HTTP/1.1 200 OK")

  # The author puts their own file in its place during the run.
  path <- write_author_file(file.path(app, "dev-app-update.yml"), "provider: generic\n")
  before <- readBin(path, "raw", 10000)
  expect_silent(stop_update_feed(feed))
  expect_identical(readBin(path, "raw", 10000), before)
  expect_false(feed$server$process$is_alive())
  expect_false(dir.exists(feed$dir))
  expect_silent(stop_update_feed(feed))
})

test_that("stop_update_feed is quiet on a feed that never started or is already gone", {
  expect_null(stop_update_feed(NULL))
  app <- withr::local_tempdir()
  gone <- file.path(withr::local_tempdir(), "feed")
  expect_silent(stop_update_feed(list(app_dir = app, dir = gone, server = NULL)))
  write_dev_update_config(app, "http://127.0.0.1:1/", "app")
  expect_silent(stop_update_feed(list(app_dir = app, dir = gone, server = NULL)))
  expect_false(file.exists(file.path(app, "dev-app-update.yml")))
})

test_that("a second interrupt during teardown waits until every step has run", {
  skip_if_no_feed_node()
  app <- withr::local_tempdir()
  feed <- start_update_feed(app, "2.0.0", "app")
  withr::defer(stop_update_feed(feed))
  local_mocked_bindings(remove_dev_update_config = function(app_dir) rlang::interrupt())
  # The interrupt is held until teardown ends, then lands at the next check.
  result <- tryCatch({
    stop_update_feed(feed)
    Sys.sleep(0.05)
    "not interrupted"
  }, interrupt = function(cnd) "interrupted")
  expect_identical(result, "interrupted")
  expect_false(feed$server$process$is_alive())
  expect_false(dir.exists(feed$dir))
})

test_that("a cleanup step that fails is reported and the others still run", {
  skip_if_no_feed_node()
  app <- withr::local_tempdir()
  feed <- start_update_feed(app, "2.0.0", "app")
  withr::defer(stop_update_feed(feed))
  local_mocked_bindings(remove_dev_update_config = function(app_dir) base::stop("permission denied"))
  expect_no_error(expect_message(stop_update_feed(feed), "permission denied"))
  expect_false(feed$server$process$is_alive())
  expect_false(dir.exists(feed$dir))
})

# R going away -------------------------------------------------------------------

child_r_script <- c(
  "setup <- readRDS(commandArgs(trailingOnly = TRUE)[[1]])",
  ".libPaths(setup$lib_paths)",
  "list2env(setup$fns, globalenv())",
  "note <- function(name, value) {",
  "  path <- file.path(setup$work, name)",
  "  writeLines(as.character(value), paste0(path, '.tmp'))",
  "  file.rename(paste0(path, '.tmp'), path)",
  "}",
  "note('r-pid', Sys.getpid())",
  "note('tempdir', normalizePath(tempdir()))",
  "if (setup$mode == 'interrupt') {",
  "  result <- tryCatch({",
  "    start_update_feed_server(setup$dir, timeout = 60)",
  "    'returned'",
  "  }, interrupt = function(cnd) 'interrupted')",
  "  note('result', result)",
  "} else {",
  "  server <- start_update_feed_server(setup$dir)",
  "  note('server-pid', server$process$get_pid())",
  "  if (setup$mode == 'exit') quit(save = 'no')",
  "}",
  "Sys.sleep(60)"
)

# Runs start_update_feed_server() in a separate R, which holds only the feed
# server functions copied from this package, with Node.js and the script fixed.
# Modes: "wait" starts the server and sleeps; "exit" starts it and quits without
# stopping it; "interrupt" waits for an address until interrupted.
start_feed_in_child_r <- function(mode, script = update_feed_server_script(), env = parent.frame()) {
  work <- withr::local_tempdir(.local_envir = env)
  dir.create(file.path(work, "feed"))
  node <- get_node_command()
  fns <- mget(c("start_update_feed_server", "supervise_update_feed_server", "stop_update_feed_server",
    "read_update_feed_address", "read_update_feed_error", "abort_update_feed_failed",
    "try_update_feed_cleanup"),
    envir = asNamespace("shinyelectron"))
  fns$get_node_command <- eval(bquote(function(...) .(node)))
  fns$update_feed_server_script <- eval(bquote(function() .(script)))
  fns <- lapply(fns, function(f) {
    f <- utils::removeSource(f)
    environment(f) <- globalenv()
    f
  })
  setup <- file.path(work, "setup.rds")
  saveRDS(list(fns = fns, lib_paths = .libPaths(), dir = file.path(work, "feed"),
    mode = mode, work = work), setup)
  writeLines(child_r_script, file.path(work, "child.R"))
  # The child's session folder, which a killed R never removes, goes with the
  # work folder.
  tmp <- file.path(work, "tmp")
  dir.create(tmp)
  rscript <- file.path(R.home("bin"), if (on_windows) "Rscript.exe" else "Rscript")
  child <- processx::process$new(rscript, c("--vanilla", file.path(work, "child.R"), setup),
    stdout = file.path(work, "log.txt"), stderr = "2>&1",
    env = c("current", R_TESTS = "", TMPDIR = tmp, TMP = tmp, TEMP = tmp))
  # Registered after the work folder, so it runs first: the child R and
  # everything it started end before their folder is removed.
  withr::defer(end_process_tree(child), envir = env)
  list(child = child, work = work)
}

# Waits for a file the child writes, and returns its first line.
read_child_note <- function(run, name, seconds = 60) {
  path <- file.path(run$work, name)
  wait_until(function() file.exists(path) || !run$child$is_alive(), seconds)
  if (!file.exists(path)) {
    log <- file.path(run$work, "log.txt")
    stop("The child R wrote no ", name, ". Its output:\n",
      paste(if (file.exists(log)) readLines(log, warn = FALSE), collapse = "\n"))
  }
  readLines(path, warn = FALSE)[[1]]
}

test_that("the feed server ends when the R that started it is killed", {
  skip_if_no_feed_node()
  run <- start_feed_in_child_r("wait")
  r_pid <- as.integer(read_child_note(run, "r-pid"))
  server_pid <- as.integer(read_child_note(run, "server-pid"))
  # A killed R leaves its session folder, so it must be one the test removes.
  expect_true(startsWith(read_child_note(run, "tempdir"), normalizePath(run$work)))
  expect_true(pid_is_running(server_pid))
  # Killed outright: R runs no exit handlers and no finalizers.
  tools::pskill(r_pid, if (on_windows) tools::SIGTERM else tools::SIGKILL)
  expect_true(wait_until(function() !pid_is_running(server_pid), 10))
})

test_that("the feed server ends when the R that started it exits without stopping it", {
  skip_if_no_feed_node()
  run <- start_feed_in_child_r("exit")
  server_pid <- as.integer(read_child_note(run, "server-pid"))
  run$child$wait(30000)
  expect_false(run$child$is_alive())
  expect_true(wait_until(function() !pid_is_running(server_pid), 10))
})

test_that("Ctrl+C while waiting for the address stops the server, with R still running", {
  skip_if_no_feed_node()
  skip_on_os("windows")
  skip_if_interrupts_ignored()
  silent <- file.path(withr::local_tempdir(), "silent-feed-server.js")
  writeLines(c(
    "const fs = require('fs');",
    "const file = require('path').join(process.argv[2], 'pid');",
    "fs.writeFileSync(file + '.tmp', String(process.pid));",
    "fs.renameSync(file + '.tmp', file);",
    "process.stdin.resume();"
  ), silent)
  run <- start_feed_in_child_r("interrupt", script = silent)
  r_pid <- as.integer(read_child_note(run, "r-pid"))
  server_pid <- as.integer(read_child_note(run, file.path("feed", "pid")))
  expect_true(pid_is_running(server_pid))
  tools::pskill(r_pid, tools::SIGINT)
  expect_identical(read_child_note(run, "result"), "interrupted")
  expect_true(wait_until(function() !pid_is_running(server_pid), 10))
  # R is still running, so its exit handlers ended the server, not R exiting.
  expect_true(run$child$is_alive())
})

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.