From 87fc40435d00ec60687c13c3db2cd70a4737314f Mon Sep 17 00:00:00 2001 From: Jacob Woliver Date: Fri, 6 Nov 2026 12:17:32 -0500 Subject: [PATCH 1/5] feat: add get_processes() wrapping GET /v1/system/processes (#531) get_processes() requests the v1 endpoint as CSV and supports its content_guid, owner_guid, and hostname filters. On Connect versions without it (404 with no error code), it falls back to the unversioned /metrics/procs endpoint, maps the columns and placeholder values to the v1 conventions, and applies the filters client-side. get_procs() is deprecated in favor of get_processes(). The shared request logic no longer goes through get_procs(), so the fallback does not raise the deprecation warning. get_procs() now returns the server's pid instead of the row index and parses its datetime columns (#532). endpoint_does_not_exist() now passes an explicit encoding, so falling back on a text/plain 404 no longer prints an encoding message. --- NAMESPACE | 1 + NEWS.md | 9 + R/get.R | 280 ++++++++++++++++++++---- R/utils.R | 2 +- man/get_processes.Rd | 83 +++++++ man/get_procs.Rd | 42 ++-- tests/integrated/test-get.R | 120 ++++++++++- tests/testthat/test-processes.R | 371 ++++++++++++++++++++++++++++++++ 8 files changed, 836 insertions(+), 72 deletions(-) create mode 100644 man/get_processes.Rd create mode 100644 tests/testthat/test-processes.R diff --git a/NAMESPACE b/NAMESPACE index 0512e9b8..fa009af9 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -102,6 +102,7 @@ export(get_my_permission) export(get_oauth_content_credentials) export(get_oauth_credentials) export(get_packages) +export(get_processes) export(get_procs) export(get_runtime_caches) export(get_runtimes) diff --git a/NEWS.md b/NEWS.md index ff518327..e921ad7c 100644 --- a/NEWS.md +++ b/NEWS.md @@ -8,6 +8,15 @@ - Corrected the `get_procs()` documentation, which incorrectly stated that only processes on the responding node of a Highly Available cluster are returned (#529). +- New `get_processes()` returns the processes Connect is running for content, + using the `GET /v1/system/processes` endpoint added in Connect 2026.11.0. It + can filter by `content_guid`, `owner_guid`, and `hostname`. On older Connect + versions, it falls back to the unversioned `GET /metrics/procs` endpoint and + returns the same columns (#531). +- `get_procs()` is deprecated in favor of `get_processes()`. It now returns the + server's `pid` instead of the row index, parses `start_time` and `heartbeat` + as datetimes, and its documentation lists the columns it actually returns + (#532). # connectapi 0.12.1 diff --git a/R/get.R b/R/get.R index c0b5b05c..da21ac2b 100644 --- a/R/get.R +++ b/R/get.R @@ -760,58 +760,266 @@ get_audit_logs <- function( return(out) } -#' Get Real-Time Process Data +#' Get running processes +#' +#' Returns the processes that Connect has started for content and that have +#' not yet finished, with their most recent CPU and memory use. This is the +#' data shown on the **System > Processes** page of the Connect dashboard. It +#' requires administrator privileges. #' -#' `r lifecycle::badge('experimental')` -#' This returns real-time process data from the Posit Connect API. It requires -#' administrator privileges to use. Processes are returned across all nodes in -#' a Highly Available cluster and across execution modes (including off-host -#' execution, e.g. Kubernetes). +#' The results cover every node in a Highly Available cluster and include +#' processes that run with off-host execution (e.g. Kubernetes). #' #' Note that: #' -#' * Usage metrics (e.g. CPU and RAM) are the values most recently reported by -#' each process, so they may be stale, or `NA` if the process has not yet -#' reported any metrics. -#' * Processes that have recently ended but have not yet been finalized may -#' still appear in the results. -#' * This function uses an internal, unversioned API endpoint, so its behavior -#' and the returned columns may change in future versions of Connect. +#' * `cpu_current`, `ram`, and `heartbeat` hold the last measurement each +#' process reported, so they can be a few seconds old. They are `NA` until a +#' process reports its first measurement. +#' * A process that exited recently can still appear until Connect finishes +#' cleaning up after it. #' -#' @param src The source object +#' On Connect versions without the `GET /v1/system/processes` endpoint, this +#' falls back to the older, unversioned `GET /metrics/procs` endpoint. The +#' results are converted to the same columns, and the filters are applied +#' client-side. +#' +#' When more than one filter is given, a process must match all of them. +#' +#' @param src A Connect R6 client object. +#' @param content_guid Optional. Return only processes for the content item +#' with this GUID. +#' @param owner_guid Optional. Return only processes for content owned by the +#' user with this GUID. +#' @param hostname Optional. Return only processes running on the Connect node +#' with this hostname. #' #' @return -#' A tibble with the following columns: +#' A tibble with one row per process and the following columns: +#' +#' * `content_guid`: The GUID of the content item the process belongs to. +#' `NA` when the content item no longer exists. +#' * `content_name`: The title of the content item, or its name when it has +#' no title. +#' * `content_url`: The URL of the content item, including its custom URL if +#' it has one. +#' * `run_as`: The Unix user the process runs as. +#' * `type`: The kind of work the process does, such as `run_app` or +#' `build_report`. +#' * `pid`: The process identifier on the Connect host. `NA` when Connect +#' has not recorded one, such as for off-host execution. +#' * `hostname`: The name of the Connect node that started the process. +#' * `job_key`: The key of the job for this process. +#' * `image`: The container image the process runs in, when using off-host +#' execution. +#' * `start_time`: When the process started. +#' * `heartbeat`: When the last CPU and memory measurement was taken. +#' * `cpu_current`: The fraction of one CPU the process used over the last +#' measurement interval. +#' * `ram`: The resident memory of the process at the last measurement, as +#' [fs::fs_bytes]. #' -#' * `pid`: The PID of the current process -#' * `appId`: The application ID -#' * `appGuid`: The application GUID -#' * `appName`: The application name -#' * `appUrl`: The application URL -#' * `appRunAs`: The application RunAs user -#' * `type`: The type of process -#' * `cpuCurrent`: The current CPU usage -#' * `cpuTotal`: The total CPU usage -#' * `ram`: The current RAM usage +#' @examples +#' \dontrun{ +#' client <- connect() +#' +#' get_processes(client) +#' +#' # Only the processes for one content item +#' get_processes(client, content_guid = "6f300623-1e0c-48e6-a473-ddf630c0c0c3") +#' } #' #' @export +get_processes <- function( + src, + content_guid = NULL, + owner_guid = NULL, + hostname = NULL +) { + validate_R6_class(src, "Connect") + for (arg in c("content_guid", "owner_guid", "hostname")) { + value <- get(arg) + if (!is.null(value) && !is_string(value)) { + stop("`", arg, "` must be a single string or `NULL`.", call. = FALSE) + } + } + + res <- src$GET( + v1_url("system", "processes"), + httr::add_headers(Accept = "text/csv"), + query = list( + content_guid = content_guid, + owner_guid = owner_guid, + hostname = hostname + ), + parser = NULL + ) + + if (endpoint_does_not_exist(res)) { + # Connect versions before the v1 endpoint only have the unversioned one. + out <- legacy_processes(src, content_guid, owner_guid, hostname) + } else { + src$raise_error(res) + out <- parse_processes_csv(httr::content( + res, + as = "text", + encoding = "UTF-8" + )) + } + type_processes(out) +} + +#' Get Real-Time Process Data +#' +#' `r lifecycle::badge('deprecated')` +#' +#' This function is deprecated; please use [get_processes()], which uses the +#' supported `GET /v1/system/processes` endpoint, can filter its results, and +#' returns the same columns across Connect versions. +#' +#' `get_procs()` uses the internal, unversioned `GET /metrics/procs` endpoint, +#' so its behavior and the returned columns may change in future versions of +#' Connect. It requires administrator privileges, and returns processes across +#' all nodes in a Highly Available cluster. +#' +#' @param src The source object +#' +#' @return +#' A tibble with one row per process. The columns are those sent by the server, +#' which in recent versions of Connect are `pid`, `app_id`, `app_guid`, +#' `app_name`, `app_url`, `app_run_as`, `type`, `cpu_current`, `ram`, +#' `hostname`, `job_key`, `image`, `start_time`, and `heartbeat`. +#' +#' @keywords internal +#' @export get_procs <- function(src) { + lifecycle::deprecate_warn("0.13.0", "get_procs()", "get_processes()") validate_R6_class(src, "Connect") - warn_experimental("get_procs") + fetch_legacy_procs(src) +} + +# Columns returned by `GET /v1/system/processes`, in order. +process_columns <- c( + "content_guid", + "content_name", + "content_url", + "run_as", + "type", + "pid", + "hostname", + "job_key", + "image", + "start_time", + "heartbeat", + "cpu_current", + "ram" +) + +# Read the CSV body of `GET /v1/system/processes`. Every column is read as +# character so that types do not depend on the values present; Connect writes +# null values as empty fields, so those become `NA`. +parse_processes_csv <- function(text) { + if (!nzchar(trimws(text))) { + return(tibble::tibble()) + } + df <- utils::read.csv( + text = text, + colClasses = "character", + na.strings = "", + check.names = FALSE, + stringsAsFactors = FALSE, + encoding = "UTF-8" + ) + tibble::as_tibble(df) +} - scoped_experimental_silence() - raw_proc_data <- src$procs() +# Give a processes table its documented column types, adding any missing +# columns so that empty results have the same shape as non-empty ones. Columns +# the server sends that we don't know about are kept at the end. +type_processes <- function(df) { + n <- nrow(df) + for (col in setdiff(process_columns, names(df))) { + df[[col]] <- rep(NA_character_, n) + } + df <- df[c(process_columns, setdiff(names(df), process_columns))] + + chr_cols <- c( + "content_guid", + "content_name", + "content_url", + "run_as", + "type", + "hostname", + "job_key", + "image" + ) + for (col in chr_cols) { + df[[col]] <- as.character(df[[col]]) + } + df$pid <- as.integer(df$pid) + df$cpu_current <- as.double(df$cpu_current) + df$ram <- fs::as_fs_bytes(as.double(df$ram)) + df$start_time <- coerce_datetime(df$start_time) + df$heartbeat <- coerce_datetime(df$heartbeat) + df +} - proc_prep <- purrr::imap( - raw_proc_data, - function(x, y) { - c(list(pid = y), x) - } +# Fetch `GET /metrics/procs` as a tibble with the server's column names. +fetch_legacy_procs <- function(src) { + raw <- src$GET(unversioned_fallback_url("metrics", "procs")) + if (!is.null(names(raw))) { + # Old Connect versions returned an object keyed by PID rather than an + # array of processes that each carry a `pid` field. + raw <- unname(purrr::imap(raw, function(x, pid) c(list(pid = pid), x))) + } + out <- parse_connectapi_typed(raw, datetime_cols = c("start_time", "heartbeat")) + coerce_fs_bytes(out, "ram") +} + +# Fallback for `get_processes()` on Connect versions without +# `GET /v1/system/processes`: fetch `GET /metrics/procs`, convert it to the v1 +# columns and conventions, and apply the filters client-side. +legacy_processes <- function(src, content_guid, owner_guid, hostname) { + df <- fetch_legacy_procs(src) + + renames <- c( + app_guid = "content_guid", + app_name = "content_name", + app_url = "content_url", + app_run_as = "run_as", + appGuid = "content_guid", + appName = "content_name", + appUrl = "content_url", + appRunAs = "run_as", + cpuCurrent = "cpu_current" ) - tbl_data <- parse_connectapi_typed(proc_prep) - tbl_data <- coerce_fs_bytes(tbl_data, "ram") + to_rename <- intersect(names(renames), names(df)) + names(df)[match(to_rename, names(df))] <- renames[to_rename] + df <- df[setdiff(names(df), c("app_id", "appId", "cpuTotal"))] + df <- type_processes(df) + + # The v1 endpoint returns null for values Connect doesn't know, where the + # unversioned endpoint uses placeholders. Match the v1 endpoint, whose CSV + # output also cannot distinguish an empty string from null. + for (col in names(df)[vapply(df, is.character, logical(1))]) { + df[[col]][!is.na(df[[col]]) & df[[col]] == ""] <- NA_character_ + } + df$run_as[df$run_as %in% "unknown"] <- NA_character_ + df$hostname[df$hostname %in% "unknown host"] <- NA_character_ + df$pid[!is.na(df$pid) & df$pid <= 0L] <- NA_integer_ - return(tbl_data) + keep <- rep(TRUE, nrow(df)) + if (!is.null(content_guid)) { + keep <- keep & df$content_guid %in% content_guid + } + if (!is.null(hostname)) { + keep <- keep & df$hostname %in% hostname + } + if (!is.null(owner_guid)) { + owned <- src$content(owner_guid = owner_guid, include = NULL) + owned_guids <- purrr::map_chr(owned, "guid") + keep <- keep & df$content_guid %in% owned_guids + } + df[keep, ] } #' Perform an OAuth credential exchange to obtain a visitor's OAuth access token. diff --git a/R/utils.R b/R/utils.R index eecf0653..d86844ce 100644 --- a/R/utils.R +++ b/R/utils.R @@ -224,7 +224,7 @@ token_hex <- function(n) { # but encountered a 404 for some other reason. endpoint_does_not_exist <- function(res) { httr::status_code(res) == "404" && - !("code" %in% names(httr::content(res, as = "parsed"))) + !("code" %in% names(httr::content(res, as = "parsed", encoding = "UTF-8"))) } # Extract the Connect error code from a response diff --git a/man/get_processes.Rd b/man/get_processes.Rd new file mode 100644 index 00000000..65ecbf41 --- /dev/null +++ b/man/get_processes.Rd @@ -0,0 +1,83 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/get.R +\name{get_processes} +\alias{get_processes} +\title{Get running processes} +\usage{ +get_processes(src, content_guid = NULL, owner_guid = NULL, hostname = NULL) +} +\arguments{ +\item{src}{A Connect R6 client object.} + +\item{content_guid}{Optional. Return only processes for the content item +with this GUID.} + +\item{owner_guid}{Optional. Return only processes for content owned by the +user with this GUID.} + +\item{hostname}{Optional. Return only processes running on the Connect node +with this hostname.} +} +\value{ +A tibble with one row per process and the following columns: +\itemize{ +\item \code{content_guid}: The GUID of the content item the process belongs to. +\code{NA} when the content item no longer exists. +\item \code{content_name}: The title of the content item, or its name when it has +no title. +\item \code{content_url}: The URL of the content item, including its custom URL if +it has one. +\item \code{run_as}: The Unix user the process runs as. +\item \code{type}: The kind of work the process does, such as \code{run_app} or +\code{build_report}. +\item \code{pid}: The process identifier on the Connect host. \code{NA} when Connect +has not recorded one, such as for off-host execution. +\item \code{hostname}: The name of the Connect node that started the process. +\item \code{job_key}: The key of the job for this process. +\item \code{image}: The container image the process runs in, when using off-host +execution. +\item \code{start_time}: When the process started. +\item \code{heartbeat}: When the last CPU and memory measurement was taken. +\item \code{cpu_current}: The fraction of one CPU the process used over the last +measurement interval. +\item \code{ram}: The resident memory of the process at the last measurement, as +\link[fs:fs_bytes]{fs::fs_bytes}. +} +} +\description{ +Returns the processes that Connect has started for content and that have +not yet finished, with their most recent CPU and memory use. This is the +data shown on the \strong{System > Processes} page of the Connect dashboard. It +requires administrator privileges. +} +\details{ +The results cover every node in a Highly Available cluster and include +processes that run with off-host execution (e.g. Kubernetes). + +Note that: +\itemize{ +\item \code{cpu_current}, \code{ram}, and \code{heartbeat} hold the last measurement each +process reported, so they can be a few seconds old. They are \code{NA} until a +process reports its first measurement. +\item A process that exited recently can still appear until Connect finishes +cleaning up after it. +} + +On Connect versions without the \code{GET /v1/system/processes} endpoint, this +falls back to the older, unversioned \code{GET /metrics/procs} endpoint. The +results are converted to the same columns, and the filters are applied +client-side. + +When more than one filter is given, a process must match all of them. +} +\examples{ +\dontrun{ +client <- connect() + +get_processes(client) + +# Only the processes for one content item +get_processes(client, content_guid = "6f300623-1e0c-48e6-a473-ddf630c0c0c3") +} + +} diff --git a/man/get_procs.Rd b/man/get_procs.Rd index 60f672ba..921ad95c 100644 --- a/man/get_procs.Rd +++ b/man/get_procs.Rd @@ -10,36 +10,22 @@ get_procs(src) \item{src}{The source object} } \value{ -A tibble with the following columns: -\itemize{ -\item \code{pid}: The PID of the current process -\item \code{appId}: The application ID -\item \code{appGuid}: The application GUID -\item \code{appName}: The application name -\item \code{appUrl}: The application URL -\item \code{appRunAs}: The application RunAs user -\item \code{type}: The type of process -\item \code{cpuCurrent}: The current CPU usage -\item \code{cpuTotal}: The total CPU usage -\item \code{ram}: The current RAM usage -} +A tibble with one row per process. The columns are those sent by the server, +which in recent versions of Connect are \code{pid}, \code{app_id}, \code{app_guid}, +\code{app_name}, \code{app_url}, \code{app_run_as}, \code{type}, \code{cpu_current}, \code{ram}, +\code{hostname}, \code{job_key}, \code{image}, \code{start_time}, and \code{heartbeat}. } \description{ -\ifelse{html}{\href{https://lifecycle.r-lib.org/articles/stages.html#experimental}{\figure{lifecycle-experimental.svg}{options: alt='[Experimental]'}}}{\strong{[Experimental]}} -This returns real-time process data from the Posit Connect API. It requires -administrator privileges to use. Processes are returned across all nodes in -a Highly Available cluster and across execution modes (including off-host -execution, e.g. Kubernetes). +\ifelse{html}{\href{https://lifecycle.r-lib.org/articles/stages.html#deprecated}{\figure{lifecycle-deprecated.svg}{options: alt='[Deprecated]'}}}{\strong{[Deprecated]}} } \details{ -Note that: -\itemize{ -\item Usage metrics (e.g. CPU and RAM) are the values most recently reported by -each process, so they may be stale, or \code{NA} if the process has not yet -reported any metrics. -\item Processes that have recently ended but have not yet been finalized may -still appear in the results. -\item This function uses an internal, unversioned API endpoint, so its behavior -and the returned columns may change in future versions of Connect. -} +This function is deprecated; please use \code{\link[=get_processes]{get_processes()}}, which uses the +supported \code{GET /v1/system/processes} endpoint, can filter its results, and +returns the same columns across Connect versions. + +\code{get_procs()} uses the internal, unversioned \code{GET /metrics/procs} endpoint, +so its behavior and the returned columns may change in future versions of +Connect. It requires administrator privileges, and returns processes across +all nodes in a Highly Available cluster. } +\keyword{internal} diff --git a/tests/integrated/test-get.R b/tests/integrated/test-get.R index 27b4d847..8113916d 100644 --- a/tests/integrated/test-get.R +++ b/tests/integrated/test-get.R @@ -73,15 +73,121 @@ test_that("get_audit_logs works", { expect_s3_class(audit_list$time, "POSIXct") }) -test_that("get_procs works", { - scoped_experimental_silence() - proc_data <- get_procs(client) +# Deploy a dependency-free Python API and keep a process for it running, so +# the process endpoints have something to return. +deploy_running_python_api <- function(client) { + py <- get_runtimes(client, runtimes = "python") + py_version <- py$version[[nrow(py)]] + + dir <- fs::dir_create(fs::file_temp("python-api")) + writeLines( + c( + "def app(environ, start_response):", + " start_response('200 OK', [('Content-Type', 'text/plain')])", + " return [b'ok']" + ), + fs::path(dir, "app.py") + ) + writeLines(character(), fs::path(dir, "requirements.txt")) + jsonlite::write_json( + list( + version = 1, + metadata = list(appmode = "python-api", entrypoint = "app:app"), + python = list( + version = py_version, + package_manager = list(name = "pip", package_file = "requirements.txt") + ), + files = list( + app.py = list(checksum = unname(tools::md5sum(fs::path(dir, "app.py")))), + requirements.txt = list( + checksum = unname(tools::md5sum(fs::path(dir, "requirements.txt"))) + ) + ) + ), + fs::path(dir, "manifest.json"), + auto_unbox = TRUE + ) - # No long-running processes on a fresh test server, so this is usually empty. - expect_s3_class(proc_data, "tbl_df") - if (nrow(proc_data) > 0) { - expect_true(all(c("pid", "appId", "appGuid") %in% names(proc_data))) + bnd <- bundle_dir(dir, filename = fs::file_temp(ext = ".tar.gz")) + tsk <- deploy(client, bnd, name = create_random_name()) + suppressMessages(poll_task(tsk)) + content <- content_item(client, tsk$content$guid) + content_update(content, min_processes = 1) + + # Visit the content too, in case min_processes is not applied right away. + httr::GET(content$get_url(), client$add_auth()) + content +} + +test_that("get_processes and get_procs return running processes", { + content <- deploy_running_python_api(client) + guid <- content$content$guid + + procs <- NULL + for (i in seq_len(60)) { + procs <- get_processes(client, content_guid = guid) + if (nrow(procs) > 0 && !is.na(procs$heartbeat[[1]])) break + Sys.sleep(2) } + + expect_identical(names(procs)[1:13], c( + "content_guid", "content_name", "content_url", "run_as", "type", "pid", + "hostname", "job_key", "image", "start_time", "heartbeat", "cpu_current", + "ram" + )) + expect_column_types(procs, list( + content_guid = "character", + content_name = "character", + content_url = "character", + run_as = "character", + type = "character", + pid = "integer", + hostname = "character", + job_key = "character", + image = "character", + start_time = "POSIXct", + heartbeat = "POSIXct", + cpu_current = "numeric", + ram = "fs_bytes" + ), exact = FALSE) + + expect_gte(nrow(procs), 1) + proc <- procs[1, ] + expect_identical(proc$content_guid, guid) + expect_identical(proc$content_name, content$content$name) + expect_identical(proc$type, "run_python_api") + expect_false(is.na(proc$pid)) + expect_false(is.na(proc$hostname)) + expect_false(is.na(proc$heartbeat)) + expect_gt(as.numeric(proc$ram), 0) + + # Unfiltered results include it. + all_procs <- get_processes(client) + expect_true(proc$job_key %in% all_procs$job_key) + + # The filters narrow the results, and are ANDed. + me <- client$me() + expect_true( + proc$job_key %in% get_processes(client, owner_guid = me$guid)$job_key + ) + expect_true( + proc$job_key %in% get_processes(client, hostname = proc$hostname)$job_key + ) + expect_equal( + nrow(get_processes(client, content_guid = guid, hostname = "no-such-host")), + 0 + ) + + # get_procs() is deprecated but returns the same process, with the server's + # pid rather than the row index (#532). + lifecycle::expect_deprecated(old <- get_procs(client)) + old_proc <- old[old$job_key == proc$job_key, ] + expect_equal(nrow(old_proc), 1) + expect_identical(old_proc$app_guid, guid) + expect_equal(as.integer(old_proc$pid), proc$pid) + expect_s3_class(old_proc$start_time, "POSIXct") + + content_update(content, min_processes = 0) }) # experimental -------------------------------------------- diff --git a/tests/testthat/test-processes.R b/tests/testthat/test-processes.R new file mode 100644 index 00000000..fd30e41d --- /dev/null +++ b/tests/testthat/test-processes.R @@ -0,0 +1,371 @@ +# A MockConnect that also records the extra arguments (headers, query) passed +# to each request, so tests can check what would be sent to the server. +CapturingConnect <- R6Class( + "CapturingConnect", + inherit = MockConnect, + public = list( + request_args = list(), + request = function(method, url, ..., parser = "parsed", simplify = FALSE) { + self$request_args <- c(self$request_args, list(rlang::list2(...))) + super$request(method, url, ..., parser = parser, simplify = simplify) + } + ) +) + +# Pull the value of a request header out of recorded request arguments. +sent_header <- function(args, name) { + for (arg in args) { + if (inherits(arg, "request")) { + return(unname(arg$headers[name])) + } + } + NULL +} + +# The CSV `GET /v1/system/processes` returns, in the format Connect writes it +# (Go's encoding/csv): null values are empty fields, and fields containing +# commas or quotes are quoted. +processes_csv <- paste0( + "content_guid,content_name,content_url,run_as,type,pid,hostname,job_key,", + "image,start_time,heartbeat,cpu_current,ram\n", + "6f300623-1e0c-48e6-a473-ddf630c0c0c3,\"Sales, by \"\"region\"\"\",", + "https://connect.example/sales/,rstudio-connect,run_app,20253,node-1,", + "tHawGvHZTosJA2Dx,,2026-11-06T10:00:00Z,2026-11-06T10:05:00Z,0.25,104857600\n", + "a1b2c3d4-0000-4000-8000-000000000000,Model API,", + "https://connect.example/content/a1b2c3d4-0000-4000-8000-000000000000/,,", + "run_app,,,Jz3kQ9xYwPq1LmNo,ghcr.io/rstudio/content-base:r4.4.1-jammy,", + "2026-11-06T10:01:00-05:00,,,\n" +) + +processes_csv_header <- paste0( + "content_guid,content_name,content_url,run_as,type,pid,hostname,job_key,", + "image,start_time,heartbeat,cpu_current,ram\n" +) + +# The JSON `GET /metrics/procs` returns for the same two processes. It uses +# placeholders ("unknown", "unknown host", "", 0) where the v1 endpoint uses +# null. +legacy_procs_json <- list( + list( + app_id = "12", + app_guid = "6f300623-1e0c-48e6-a473-ddf630c0c0c3", + app_name = "Sales, by \"region\"", + app_url = "https://connect.example/sales/", + app_run_as = "rstudio-connect", + type = "run_app", + cpu_current = 0.25, + ram = 104857600, + hostname = "node-1", + job_key = "tHawGvHZTosJA2Dx", + image = "", + start_time = "2026-11-06T10:00:00Z", + heartbeat = "2026-11-06T10:05:00Z", + pid = 20253 + ), + list( + app_id = "34", + app_guid = "a1b2c3d4-0000-4000-8000-000000000000", + app_name = "Model API", + app_url = "https://connect.example/content/a1b2c3d4-0000-4000-8000-000000000000/", + app_run_as = "unknown", + type = "run_app", + cpu_current = NULL, + ram = NULL, + hostname = "unknown host", + job_key = "Jz3kQ9xYwPq1LmNo", + image = "ghcr.io/rstudio/content-base:r4.4.1-jammy", + start_time = "2026-11-06T10:01:00-05:00", + heartbeat = NULL, + pid = 0 + ) +) + +mock_v1_processes <- function(client, content = processes_csv) { + client$mock_response( + "GET", + "v1/system/processes", + content = content, + headers = c("Content-Type" = "text/csv") + ) +} + +# How Connect versions without the v1 endpoint answer it: a 404 without a +# Connect error code. +mock_v1_processes_missing <- function(client) { + client$mock_response( + "GET", + "v1/system/processes", + content = "404 page not found", + status_code = 404L, + headers = c("Content-Type" = "text/plain; charset=utf-8") + ) +} + +expect_process_types <- function(df) { + expect_s3_class(df, "tbl_df") + expect_named(df, process_columns) + for (col in c( + "content_guid", + "content_name", + "content_url", + "run_as", + "type", + "hostname", + "job_key", + "image" + )) { + expect_type(df[[col]], "character") + } + expect_type(df$pid, "integer") + expect_type(df$cpu_current, "double") + expect_s3_class(df$ram, "fs_bytes") + expect_s3_class(df$start_time, "POSIXct") + expect_s3_class(df$heartbeat, "POSIXct") +} + +test_that("get_processes() requests CSV from v1/system/processes and parses it", { + client <- CapturingConnect$new() + mock_v1_processes(client) + + procs <- get_processes(client) + + expect_identical( + client$call_log, + "GET https://connect.example/__api__/v1/system/processes" + ) + expect_identical( + sent_header(client$request_args[[1]], "Accept"), + "text/csv" + ) + + expect_process_types(procs) + expect_equal(nrow(procs), 2) + expect_identical( + procs$content_guid, + c("6f300623-1e0c-48e6-a473-ddf630c0c0c3", "a1b2c3d4-0000-4000-8000-000000000000") + ) + expect_identical(procs$content_name, c("Sales, by \"region\"", "Model API")) + expect_identical(procs$run_as, c("rstudio-connect", NA)) + expect_identical(procs$pid, c(20253L, NA)) + expect_identical(procs$hostname, c("node-1", NA)) + expect_identical( + procs$image, + c(NA, "ghcr.io/rstudio/content-base:r4.4.1-jammy") + ) + expect_equal(procs$cpu_current, c(0.25, NA)) + expect_equal(procs$ram, fs::as_fs_bytes(c(104857600, NA))) + expect_equal( + procs$start_time, + as.POSIXct(c("2026-11-06 10:00:00", "2026-11-06 15:01:00"), tz = "UTC"), + ignore_attr = "tzone" + ) + expect_equal( + procs$heartbeat, + as.POSIXct(c("2026-11-06 10:05:00", NA), tz = "UTC"), + ignore_attr = "tzone" + ) +}) + +test_that("get_processes() passes filters as query parameters", { + client <- CapturingConnect$new() + mock_v1_processes(client) + + get_processes( + client, + content_guid = "6f300623-1e0c-48e6-a473-ddf630c0c0c3", + owner_guid = "0d2c5e1a-7b4f-4f3e-9a8b-1c2d3e4f5a6b", + hostname = "node-1" + ) + expect_identical( + client$request_args[[1]]$query, + list( + content_guid = "6f300623-1e0c-48e6-a473-ddf630c0c0c3", + owner_guid = "0d2c5e1a-7b4f-4f3e-9a8b-1c2d3e4f5a6b", + hostname = "node-1" + ) + ) + + # Unset filters are NULL, which httr drops from the query string. + client <- CapturingConnect$new() + mock_v1_processes(client) + get_processes(client, hostname = "node-1") + expect_null(client$request_args[[1]]$query$content_guid) + expect_null(client$request_args[[1]]$query$owner_guid) + expect_identical(client$request_args[[1]]$query$hostname, "node-1") +}) + +test_that("get_processes() validates filters", { + client <- MockConnect$new() + expect_error(get_processes(client, content_guid = 1), "`content_guid`") + expect_error(get_processes(client, hostname = c("a", "b")), "`hostname`") + expect_length(client$call_log, 0) +}) + +test_that("get_processes() returns a typed, zero-row tibble when nothing is running", { + client <- MockConnect$new() + mock_v1_processes(client, processes_csv_header) + procs <- get_processes(client) + expect_equal(nrow(procs), 0) + expect_process_types(procs) +}) + +test_that("get_processes() keeps columns added by newer Connect versions", { + client <- MockConnect$new() + mock_v1_processes( + client, + paste0( + "content_guid,content_name,content_url,run_as,type,pid,hostname,job_key,", + "image,start_time,heartbeat,cpu_current,ram,new_field\n", + "6f300623-1e0c-48e6-a473-ddf630c0c0c3,a,b,c,run_app,1,h,k,,", + "2026-11-06T10:00:00Z,,,,surprise\n" + ) + ) + procs <- get_processes(client) + expect_named(procs, c(process_columns, "new_field")) + expect_identical(procs$new_field, "surprise") +}) + +test_that("get_processes() does not fall back on a 404 with a Connect error code", { + # e.g. an unknown `content_guid`. + client <- MockConnect$new() + client$mock_response( + "GET", + "v1/system/processes", + content = list(code = 4, error = "The requested object does not exist."), + status_code = 404L + ) + expect_error( + get_processes(client, content_guid = "6f300623-1e0c-48e6-a473-ddf630c0c0c3"), + "404" + ) + expect_identical( + client$call_log, + "GET https://connect.example/__api__/v1/system/processes" + ) +}) + +test_that("get_processes() falls back to metrics/procs on older Connect", { + rlang::local_options(lifecycle_verbosity = "warning") + client <- MockConnect$new() + mock_v1_processes_missing(client) + client$mock_response("GET", "metrics/procs", content = legacy_procs_json) + + # The fallback must not raise get_procs()'s deprecation warning. The class is + # needed: without it, expect_no_warning() ignores deprecation warnings. + expect_no_warning( + procs <- get_processes(client), + class = "lifecycle_warning_deprecated" + ) + + expect_identical( + client$call_log, + c( + "GET https://connect.example/__api__/v1/system/processes", + "GET https://connect.example/__api__/metrics/procs" + ) + ) + + # Same columns, types, and values as the v1 endpoint returns for the same + # processes. + v1_client <- MockConnect$new() + mock_v1_processes(v1_client) + expect_equal(procs, get_processes(v1_client)) +}) + +test_that("get_processes() fallback returns a typed, zero-row tibble when nothing is running", { + client <- MockConnect$new() + mock_v1_processes_missing(client) + client$mock_response("GET", "metrics/procs", content = "[]") + procs <- get_processes(client) + expect_equal(nrow(procs), 0) + expect_process_types(procs) +}) + +test_that("get_processes() fallback applies the filters client-side", { + mock_fallback <- function() { + client <- MockConnect$new() + mock_v1_processes_missing(client) + client$mock_response("GET", "metrics/procs", content = legacy_procs_json) + client + } + + client <- mock_fallback() + procs <- get_processes(client, content_guid = "a1b2c3d4-0000-4000-8000-000000000000") + expect_identical(procs$job_key, "Jz3kQ9xYwPq1LmNo") + + client <- mock_fallback() + procs <- get_processes(client, hostname = "node-1") + expect_identical(procs$job_key, "tHawGvHZTosJA2Dx") + + client <- mock_fallback() + procs <- get_processes(client, hostname = "node-2") + expect_equal(nrow(procs), 0) + expect_process_types(procs) + + # owner_guid is resolved to the owner's content items. + client <- mock_fallback() + client$mock_response( + "GET", + "v1/content", + content = list(list(guid = "6f300623-1e0c-48e6-a473-ddf630c0c0c3")) + ) + procs <- get_processes(client, owner_guid = "0d2c5e1a-7b4f-4f3e-9a8b-1c2d3e4f5a6b") + expect_identical(procs$job_key, "tHawGvHZTosJA2Dx") + expect_identical( + client$call_log[[3]], + "GET https://connect.example/__api__/v1/content" + ) + + # Filters are ANDed. + client <- mock_fallback() + procs <- get_processes( + client, + content_guid = "6f300623-1e0c-48e6-a473-ddf630c0c0c3", + hostname = "node-2" + ) + expect_equal(nrow(procs), 0) +}) + +test_that("get_procs() is deprecated in favor of get_processes()", { + client <- MockConnect$new() + client$mock_response("GET", "metrics/procs", content = legacy_procs_json) + lifecycle::expect_deprecated(get_procs(client), "get_processes") +}) + +test_that("get_procs() returns the server's pid and parses datetimes", { + rlang::local_options(lifecycle_verbosity = "quiet") + client <- MockConnect$new() + client$mock_response("GET", "metrics/procs", content = legacy_procs_json) + + procs <- get_procs(client) + + expect_identical( + client$call_log, + "GET https://connect.example/__api__/metrics/procs" + ) + # Previously the pid column held the row index (1, 2) instead (#532). + expect_equal(procs$pid, c(20253, 0)) + expect_identical(procs$app_guid, purrr::map_chr(legacy_procs_json, "app_guid")) + expect_s3_class(procs$start_time, "POSIXct") + expect_s3_class(procs$heartbeat, "POSIXct") + expect_s3_class(procs$ram, "fs_bytes") +}) + +test_that("get_procs() handles the old response keyed by PID", { + rlang::local_options(lifecycle_verbosity = "quiet") + client <- MockConnect$new() + client$mock_response( + "GET", + "metrics/procs", + content = list( + "20253" = list(appGuid = "6f300623-1e0c-48e6-a473-ddf630c0c0c3", type = "run_app"), + "20254" = list(appGuid = "a1b2c3d4-0000-4000-8000-000000000000", type = "run_app") + ) + ) + procs <- get_procs(client) + expect_identical(procs$pid, c("20253", "20254")) + expect_identical( + procs$appGuid, + c("6f300623-1e0c-48e6-a473-ddf630c0c0c3", "a1b2c3d4-0000-4000-8000-000000000000") + ) +}) From add7eeeccc0f3a97be58f038af4b0977e9d15080 Mon Sep 17 00:00:00 2001 From: Jacob Woliver Date: Fri, 6 Nov 2026 15:31:41 -0500 Subject: [PATCH 2/5] fix: make get_processes() fallback reject unknown GUIDs like v1 Address review feedback on #533: - On Connect without GET /v1/system/processes, an unknown content_guid or owner_guid now raises a 404, as the v1 endpoint does, instead of returning no processes. The fallback checks them with GET /v1/content/{guid} and GET /v1/users/{guid} before fetching /metrics/procs. - Deprecate the Connect$procs() R6 method in favor of get_processes(). - Type the result once: the fallback path already calls type_processes(), so get_processes() no longer calls it again. - The integration test stops its process with withr::defer(), so a failing expectation doesn't leave it running, and checks that unknown content and owner GUIDs are errors. --- NEWS.md | 8 +++--- R/connect.R | 9 ++++-- R/get.R | 33 ++++++++++++--------- man/PositConnect.Rd | 3 +- man/get_processes.Rd | 4 +-- tests/integrated/test-get.R | 11 +++++-- tests/testthat/test-processes.R | 51 ++++++++++++++++++++++++++++++--- 7 files changed, 91 insertions(+), 28 deletions(-) diff --git a/NEWS.md b/NEWS.md index e921ad7c..7b8a67c6 100644 --- a/NEWS.md +++ b/NEWS.md @@ -13,10 +13,10 @@ can filter by `content_guid`, `owner_guid`, and `hostname`. On older Connect versions, it falls back to the unversioned `GET /metrics/procs` endpoint and returns the same columns (#531). -- `get_procs()` is deprecated in favor of `get_processes()`. It now returns the - server's `pid` instead of the row index, parses `start_time` and `heartbeat` - as datetimes, and its documentation lists the columns it actually returns - (#532). +- `get_procs()` and the `Connect$procs()` method are deprecated in favor of + `get_processes()`. `get_procs()` now returns the server's `pid` instead of + the row index, parses `start_time` and `heartbeat` as datetimes, and its + documentation lists the columns it actually returns (#532). # connectapi 0.12.1 diff --git a/R/connect.R b/R/connect.R index ac6199f0..f34eaa54 100644 --- a/R/connect.R +++ b/R/connect.R @@ -792,9 +792,14 @@ Connect <- R6::R6Class( self$GET(path, query = query) }, - #' @description Get running processes. + #' @description Get running processes. Deprecated; use + #' [get_processes()] instead. procs = function() { - warn_experimental("procs") + lifecycle::deprecate_warn( + "0.13.0", + I("`Connect$procs()`"), + "get_processes()" + ) path <- unversioned_url("metrics", "procs") self$GET(path) }, diff --git a/R/get.R b/R/get.R index da21ac2b..1c3314d0 100644 --- a/R/get.R +++ b/R/get.R @@ -787,9 +787,9 @@ get_audit_logs <- function( #' #' @param src A Connect R6 client object. #' @param content_guid Optional. Return only processes for the content item -#' with this GUID. +#' with this GUID. It is an error if no content item has this GUID. #' @param owner_guid Optional. Return only processes for content owned by the -#' user with this GUID. +#' user with this GUID. It is an error if no user has this GUID. #' @param hostname Optional. Return only processes running on the Connect node #' with this hostname. #' @@ -856,16 +856,14 @@ get_processes <- function( if (endpoint_does_not_exist(res)) { # Connect versions before the v1 endpoint only have the unversioned one. - out <- legacy_processes(src, content_guid, owner_guid, hostname) - } else { - src$raise_error(res) - out <- parse_processes_csv(httr::content( - res, - as = "text", - encoding = "UTF-8" - )) + return(legacy_processes(src, content_guid, owner_guid, hostname)) } - type_processes(out) + src$raise_error(res) + type_processes(parse_processes_csv(httr::content( + res, + as = "text", + encoding = "UTF-8" + ))) } #' Get Real-Time Process Data @@ -979,6 +977,17 @@ fetch_legacy_procs <- function(src) { # `GET /v1/system/processes`: fetch `GET /metrics/procs`, convert it to the v1 # columns and conventions, and apply the filters client-side. legacy_processes <- function(src, content_guid, owner_guid, hostname) { + # Like the v1 endpoint, reject a content or owner GUID that names nothing + # rather than returning no processes. These requests raise a 404 if so. + if (!is.null(content_guid)) { + src$content(guid = content_guid, include = NULL) + } + if (!is.null(owner_guid)) { + src$user(owner_guid) + owned <- src$content(owner_guid = owner_guid, include = NULL) + owned_guids <- purrr::map_chr(owned, "guid") + } + df <- fetch_legacy_procs(src) renames <- c( @@ -1015,8 +1024,6 @@ legacy_processes <- function(src, content_guid, owner_guid, hostname) { keep <- keep & df$hostname %in% hostname } if (!is.null(owner_guid)) { - owned <- src$content(owner_guid = owner_guid, include = NULL) - owned_guids <- purrr::map_chr(owned, "guid") keep <- keep & df$content_guid %in% owned_guids } df[keep, ] diff --git a/man/PositConnect.Rd b/man/PositConnect.Rd index 9e7cf89b..4e82b3f9 100644 --- a/man/PositConnect.Rd +++ b/man/PositConnect.Rd @@ -1200,7 +1200,8 @@ will be returned. Otherwise, the argument is forwarded to \if{html}{\out{}} \if{latex}{\out{\hypertarget{method-Connect-procs}{}}} \subsection{\code{Connect$procs()}}{ - Get running processes. + Get running processes. Deprecated; use + \code{\link[=get_processes]{get_processes()}} instead. \subsection{Usage}{ \if{html}{\out{
}} \preformatted{Connect$procs()} diff --git a/man/get_processes.Rd b/man/get_processes.Rd index 65ecbf41..eb3521df 100644 --- a/man/get_processes.Rd +++ b/man/get_processes.Rd @@ -10,10 +10,10 @@ get_processes(src, content_guid = NULL, owner_guid = NULL, hostname = NULL) \item{src}{A Connect R6 client object.} \item{content_guid}{Optional. Return only processes for the content item -with this GUID.} +with this GUID. It is an error if no content item has this GUID.} \item{owner_guid}{Optional. Return only processes for content owned by the -user with this GUID.} +user with this GUID. It is an error if no user has this GUID.} \item{hostname}{Optional. Return only processes running on the Connect node with this hostname.} diff --git a/tests/integrated/test-get.R b/tests/integrated/test-get.R index 8113916d..2c06cb14 100644 --- a/tests/integrated/test-get.R +++ b/tests/integrated/test-get.R @@ -121,6 +121,8 @@ deploy_running_python_api <- function(client) { test_that("get_processes and get_procs return running processes", { content <- deploy_running_python_api(client) + # Stop the process even if an expectation below fails. + withr::defer(content_update(content, min_processes = 0)) guid <- content$content$guid procs <- NULL @@ -178,6 +180,13 @@ test_that("get_processes and get_procs return running processes", { 0 ) + # A content or owner GUID that names nothing is an error, as with the v1 + # endpoint, even when falling back. (Not the nil GUID: older Connect rejects + # it as invalid, with a 400.) + unknown_guid <- uuid::UUIDgenerate() + expect_error(get_processes(client, content_guid = unknown_guid), "404") + expect_error(get_processes(client, owner_guid = unknown_guid), "404") + # get_procs() is deprecated but returns the same process, with the server's # pid rather than the row index (#532). lifecycle::expect_deprecated(old <- get_procs(client)) @@ -186,8 +195,6 @@ test_that("get_processes and get_procs return running processes", { expect_identical(old_proc$app_guid, guid) expect_equal(as.integer(old_proc$pid), proc$pid) expect_s3_class(old_proc$start_time, "POSIXct") - - content_update(content, min_processes = 0) }) # experimental -------------------------------------------- diff --git a/tests/testthat/test-processes.R b/tests/testthat/test-processes.R index fd30e41d..9f3803aa 100644 --- a/tests/testthat/test-processes.R +++ b/tests/testthat/test-processes.R @@ -286,12 +286,24 @@ test_that("get_processes() fallback applies the filters client-side", { client <- MockConnect$new() mock_v1_processes_missing(client) client$mock_response("GET", "metrics/procs", content = legacy_procs_json) + for (guid in purrr::map_chr(legacy_procs_json, "app_guid")) { + client$mock_response("GET", paste0("v1/content/", guid), content = list(guid = guid)) + } client } + # content_guid is checked to exist before filtering. client <- mock_fallback() procs <- get_processes(client, content_guid = "a1b2c3d4-0000-4000-8000-000000000000") expect_identical(procs$job_key, "Jz3kQ9xYwPq1LmNo") + expect_identical( + client$call_log, + c( + "GET https://connect.example/__api__/v1/system/processes", + "GET https://connect.example/__api__/v1/content/a1b2c3d4-0000-4000-8000-000000000000", + "GET https://connect.example/__api__/metrics/procs" + ) + ) client <- mock_fallback() procs <- get_processes(client, hostname = "node-1") @@ -302,18 +314,25 @@ test_that("get_processes() fallback applies the filters client-side", { expect_equal(nrow(procs), 0) expect_process_types(procs) - # owner_guid is resolved to the owner's content items. + # owner_guid is checked to exist, then resolved to the owner's content items. + owner <- "0d2c5e1a-7b4f-4f3e-9a8b-1c2d3e4f5a6b" client <- mock_fallback() + client$mock_response("GET", paste0("v1/users/", owner), content = list(guid = owner)) client$mock_response( "GET", "v1/content", content = list(list(guid = "6f300623-1e0c-48e6-a473-ddf630c0c0c3")) ) - procs <- get_processes(client, owner_guid = "0d2c5e1a-7b4f-4f3e-9a8b-1c2d3e4f5a6b") + procs <- get_processes(client, owner_guid = owner) expect_identical(procs$job_key, "tHawGvHZTosJA2Dx") expect_identical( - client$call_log[[3]], - "GET https://connect.example/__api__/v1/content" + client$call_log, + c( + "GET https://connect.example/__api__/v1/system/processes", + paste0("GET https://connect.example/__api__/v1/users/", owner), + "GET https://connect.example/__api__/v1/content", + "GET https://connect.example/__api__/metrics/procs" + ) ) # Filters are ANDed. @@ -326,6 +345,24 @@ test_that("get_processes() fallback applies the filters client-side", { expect_equal(nrow(procs), 0) }) +test_that("get_processes() fallback errors on an unknown content or owner GUID, like v1", { + not_found <- list(code = 4, error = "The requested object does not exist.") + guid <- "00000000-0000-0000-0000-000000000000" + + client <- MockConnect$new() + mock_v1_processes_missing(client) + client$mock_response("GET", paste0("v1/content/", guid), content = not_found, status_code = 404L) + expect_error(get_processes(client, content_guid = guid), "404") + # It fails before fetching the processes. + expect_false(any(grepl("metrics/procs", client$call_log))) + + client <- MockConnect$new() + mock_v1_processes_missing(client) + client$mock_response("GET", paste0("v1/users/", guid), content = not_found, status_code = 404L) + expect_error(get_processes(client, owner_guid = guid), "404") + expect_false(any(grepl("metrics/procs", client$call_log))) +}) + test_that("get_procs() is deprecated in favor of get_processes()", { client <- MockConnect$new() client$mock_response("GET", "metrics/procs", content = legacy_procs_json) @@ -369,3 +406,9 @@ test_that("get_procs() handles the old response keyed by PID", { c("6f300623-1e0c-48e6-a473-ddf630c0c0c3", "a1b2c3d4-0000-4000-8000-000000000000") ) }) + +test_that("Connect$procs() is deprecated in favor of get_processes()", { + client <- MockConnect$new() + client$mock_response("GET", "metrics/procs", content = legacy_procs_json) + lifecycle::expect_deprecated(client$procs(), "get_processes") +}) From 7161be46d9eb2e8bb099cb4da69cd949d13caff3 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Fri, 6 Nov 2026 20:33:51 +0000 Subject: [PATCH 3/5] Update documentation --- man/PositConnect.Rd | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/man/PositConnect.Rd b/man/PositConnect.Rd index 4e82b3f9..c03b3d60 100644 --- a/man/PositConnect.Rd +++ b/man/PositConnect.Rd @@ -1201,7 +1201,7 @@ will be returned. Otherwise, the argument is forwarded to \if{latex}{\out{\hypertarget{method-Connect-procs}{}}} \subsection{\code{Connect$procs()}}{ Get running processes. Deprecated; use - \code{\link[=get_processes]{get_processes()}} instead. +\code{\link[=get_processes]{get_processes()}} instead. \subsection{Usage}{ \if{html}{\out{
}} \preformatted{Connect$procs()} From 23b7e7be5d35d031e9ce7d4e0483d044c7a5d20f Mon Sep 17 00:00:00 2001 From: Jacob Woliver Date: Mon, 9 Nov 2026 09:59:25 -0500 Subject: [PATCH 4/5] refactor: move process code to processes.R, address review - Move get_processes(), get_procs() and helpers from R/get.R to R/processes.R, and their integration test to tests/integrated/test-processes.R. - Use purrr::map_lgl() instead of vapply() in legacy_processes(). - Explain why parse_processes_csv() reads everything as character rather than typing columns via colClasses. - Explain why the integration test deploys a Python API, and skip it when the server has no Python installation. --- DESCRIPTION | 1 + R/get.R | 269 ---------------------------- R/processes.R | 279 ++++++++++++++++++++++++++++++ man/get_processes.Rd | 2 +- man/get_procs.Rd | 2 +- tests/integrated/test-get.R | 124 ------------- tests/integrated/test-processes.R | 131 ++++++++++++++ 7 files changed, 413 insertions(+), 395 deletions(-) create mode 100644 R/processes.R create mode 100644 tests/integrated/test-processes.R diff --git a/DESCRIPTION b/DESCRIPTION index f7e8f3a3..33f6f7f5 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -86,6 +86,7 @@ Collate: 'lazy.R' 'page.R' 'parse.R' + 'processes.R' 'promote.R' 'remote.R' 'runtime-caches.R' diff --git a/R/get.R b/R/get.R index 1c3314d0..35c1c5d5 100644 --- a/R/get.R +++ b/R/get.R @@ -760,275 +760,6 @@ get_audit_logs <- function( return(out) } -#' Get running processes -#' -#' Returns the processes that Connect has started for content and that have -#' not yet finished, with their most recent CPU and memory use. This is the -#' data shown on the **System > Processes** page of the Connect dashboard. It -#' requires administrator privileges. -#' -#' The results cover every node in a Highly Available cluster and include -#' processes that run with off-host execution (e.g. Kubernetes). -#' -#' Note that: -#' -#' * `cpu_current`, `ram`, and `heartbeat` hold the last measurement each -#' process reported, so they can be a few seconds old. They are `NA` until a -#' process reports its first measurement. -#' * A process that exited recently can still appear until Connect finishes -#' cleaning up after it. -#' -#' On Connect versions without the `GET /v1/system/processes` endpoint, this -#' falls back to the older, unversioned `GET /metrics/procs` endpoint. The -#' results are converted to the same columns, and the filters are applied -#' client-side. -#' -#' When more than one filter is given, a process must match all of them. -#' -#' @param src A Connect R6 client object. -#' @param content_guid Optional. Return only processes for the content item -#' with this GUID. It is an error if no content item has this GUID. -#' @param owner_guid Optional. Return only processes for content owned by the -#' user with this GUID. It is an error if no user has this GUID. -#' @param hostname Optional. Return only processes running on the Connect node -#' with this hostname. -#' -#' @return -#' A tibble with one row per process and the following columns: -#' -#' * `content_guid`: The GUID of the content item the process belongs to. -#' `NA` when the content item no longer exists. -#' * `content_name`: The title of the content item, or its name when it has -#' no title. -#' * `content_url`: The URL of the content item, including its custom URL if -#' it has one. -#' * `run_as`: The Unix user the process runs as. -#' * `type`: The kind of work the process does, such as `run_app` or -#' `build_report`. -#' * `pid`: The process identifier on the Connect host. `NA` when Connect -#' has not recorded one, such as for off-host execution. -#' * `hostname`: The name of the Connect node that started the process. -#' * `job_key`: The key of the job for this process. -#' * `image`: The container image the process runs in, when using off-host -#' execution. -#' * `start_time`: When the process started. -#' * `heartbeat`: When the last CPU and memory measurement was taken. -#' * `cpu_current`: The fraction of one CPU the process used over the last -#' measurement interval. -#' * `ram`: The resident memory of the process at the last measurement, as -#' [fs::fs_bytes]. -#' -#' @examples -#' \dontrun{ -#' client <- connect() -#' -#' get_processes(client) -#' -#' # Only the processes for one content item -#' get_processes(client, content_guid = "6f300623-1e0c-48e6-a473-ddf630c0c0c3") -#' } -#' -#' @export -get_processes <- function( - src, - content_guid = NULL, - owner_guid = NULL, - hostname = NULL -) { - validate_R6_class(src, "Connect") - for (arg in c("content_guid", "owner_guid", "hostname")) { - value <- get(arg) - if (!is.null(value) && !is_string(value)) { - stop("`", arg, "` must be a single string or `NULL`.", call. = FALSE) - } - } - - res <- src$GET( - v1_url("system", "processes"), - httr::add_headers(Accept = "text/csv"), - query = list( - content_guid = content_guid, - owner_guid = owner_guid, - hostname = hostname - ), - parser = NULL - ) - - if (endpoint_does_not_exist(res)) { - # Connect versions before the v1 endpoint only have the unversioned one. - return(legacy_processes(src, content_guid, owner_guid, hostname)) - } - src$raise_error(res) - type_processes(parse_processes_csv(httr::content( - res, - as = "text", - encoding = "UTF-8" - ))) -} - -#' Get Real-Time Process Data -#' -#' `r lifecycle::badge('deprecated')` -#' -#' This function is deprecated; please use [get_processes()], which uses the -#' supported `GET /v1/system/processes` endpoint, can filter its results, and -#' returns the same columns across Connect versions. -#' -#' `get_procs()` uses the internal, unversioned `GET /metrics/procs` endpoint, -#' so its behavior and the returned columns may change in future versions of -#' Connect. It requires administrator privileges, and returns processes across -#' all nodes in a Highly Available cluster. -#' -#' @param src The source object -#' -#' @return -#' A tibble with one row per process. The columns are those sent by the server, -#' which in recent versions of Connect are `pid`, `app_id`, `app_guid`, -#' `app_name`, `app_url`, `app_run_as`, `type`, `cpu_current`, `ram`, -#' `hostname`, `job_key`, `image`, `start_time`, and `heartbeat`. -#' -#' @keywords internal -#' @export -get_procs <- function(src) { - lifecycle::deprecate_warn("0.13.0", "get_procs()", "get_processes()") - validate_R6_class(src, "Connect") - fetch_legacy_procs(src) -} - -# Columns returned by `GET /v1/system/processes`, in order. -process_columns <- c( - "content_guid", - "content_name", - "content_url", - "run_as", - "type", - "pid", - "hostname", - "job_key", - "image", - "start_time", - "heartbeat", - "cpu_current", - "ram" -) - -# Read the CSV body of `GET /v1/system/processes`. Every column is read as -# character so that types do not depend on the values present; Connect writes -# null values as empty fields, so those become `NA`. -parse_processes_csv <- function(text) { - if (!nzchar(trimws(text))) { - return(tibble::tibble()) - } - df <- utils::read.csv( - text = text, - colClasses = "character", - na.strings = "", - check.names = FALSE, - stringsAsFactors = FALSE, - encoding = "UTF-8" - ) - tibble::as_tibble(df) -} - -# Give a processes table its documented column types, adding any missing -# columns so that empty results have the same shape as non-empty ones. Columns -# the server sends that we don't know about are kept at the end. -type_processes <- function(df) { - n <- nrow(df) - for (col in setdiff(process_columns, names(df))) { - df[[col]] <- rep(NA_character_, n) - } - df <- df[c(process_columns, setdiff(names(df), process_columns))] - - chr_cols <- c( - "content_guid", - "content_name", - "content_url", - "run_as", - "type", - "hostname", - "job_key", - "image" - ) - for (col in chr_cols) { - df[[col]] <- as.character(df[[col]]) - } - df$pid <- as.integer(df$pid) - df$cpu_current <- as.double(df$cpu_current) - df$ram <- fs::as_fs_bytes(as.double(df$ram)) - df$start_time <- coerce_datetime(df$start_time) - df$heartbeat <- coerce_datetime(df$heartbeat) - df -} - -# Fetch `GET /metrics/procs` as a tibble with the server's column names. -fetch_legacy_procs <- function(src) { - raw <- src$GET(unversioned_fallback_url("metrics", "procs")) - if (!is.null(names(raw))) { - # Old Connect versions returned an object keyed by PID rather than an - # array of processes that each carry a `pid` field. - raw <- unname(purrr::imap(raw, function(x, pid) c(list(pid = pid), x))) - } - out <- parse_connectapi_typed(raw, datetime_cols = c("start_time", "heartbeat")) - coerce_fs_bytes(out, "ram") -} - -# Fallback for `get_processes()` on Connect versions without -# `GET /v1/system/processes`: fetch `GET /metrics/procs`, convert it to the v1 -# columns and conventions, and apply the filters client-side. -legacy_processes <- function(src, content_guid, owner_guid, hostname) { - # Like the v1 endpoint, reject a content or owner GUID that names nothing - # rather than returning no processes. These requests raise a 404 if so. - if (!is.null(content_guid)) { - src$content(guid = content_guid, include = NULL) - } - if (!is.null(owner_guid)) { - src$user(owner_guid) - owned <- src$content(owner_guid = owner_guid, include = NULL) - owned_guids <- purrr::map_chr(owned, "guid") - } - - df <- fetch_legacy_procs(src) - - renames <- c( - app_guid = "content_guid", - app_name = "content_name", - app_url = "content_url", - app_run_as = "run_as", - appGuid = "content_guid", - appName = "content_name", - appUrl = "content_url", - appRunAs = "run_as", - cpuCurrent = "cpu_current" - ) - to_rename <- intersect(names(renames), names(df)) - names(df)[match(to_rename, names(df))] <- renames[to_rename] - df <- df[setdiff(names(df), c("app_id", "appId", "cpuTotal"))] - df <- type_processes(df) - - # The v1 endpoint returns null for values Connect doesn't know, where the - # unversioned endpoint uses placeholders. Match the v1 endpoint, whose CSV - # output also cannot distinguish an empty string from null. - for (col in names(df)[vapply(df, is.character, logical(1))]) { - df[[col]][!is.na(df[[col]]) & df[[col]] == ""] <- NA_character_ - } - df$run_as[df$run_as %in% "unknown"] <- NA_character_ - df$hostname[df$hostname %in% "unknown host"] <- NA_character_ - df$pid[!is.na(df$pid) & df$pid <= 0L] <- NA_integer_ - - keep <- rep(TRUE, nrow(df)) - if (!is.null(content_guid)) { - keep <- keep & df$content_guid %in% content_guid - } - if (!is.null(hostname)) { - keep <- keep & df$hostname %in% hostname - } - if (!is.null(owner_guid)) { - keep <- keep & df$content_guid %in% owned_guids - } - df[keep, ] -} - #' Perform an OAuth credential exchange to obtain a visitor's OAuth access token. #' #' @param connect A Connect R6 object. diff --git a/R/processes.R b/R/processes.R new file mode 100644 index 00000000..8ca78697 --- /dev/null +++ b/R/processes.R @@ -0,0 +1,279 @@ +#' Get running processes +#' +#' Returns the processes that Connect has started for content and that have +#' not yet finished, with their most recent CPU and memory use. This is the +#' data shown on the **System > Processes** page of the Connect dashboard. It +#' requires administrator privileges. +#' +#' The results cover every node in a Highly Available cluster and include +#' processes that run with off-host execution (e.g. Kubernetes). +#' +#' Note that: +#' +#' * `cpu_current`, `ram`, and `heartbeat` hold the last measurement each +#' process reported, so they can be a few seconds old. They are `NA` until a +#' process reports its first measurement. +#' * A process that exited recently can still appear until Connect finishes +#' cleaning up after it. +#' +#' On Connect versions without the `GET /v1/system/processes` endpoint, this +#' falls back to the older, unversioned `GET /metrics/procs` endpoint. The +#' results are converted to the same columns, and the filters are applied +#' client-side. +#' +#' When more than one filter is given, a process must match all of them. +#' +#' @param src A Connect R6 client object. +#' @param content_guid Optional. Return only processes for the content item +#' with this GUID. It is an error if no content item has this GUID. +#' @param owner_guid Optional. Return only processes for content owned by the +#' user with this GUID. It is an error if no user has this GUID. +#' @param hostname Optional. Return only processes running on the Connect node +#' with this hostname. +#' +#' @return +#' A tibble with one row per process and the following columns: +#' +#' * `content_guid`: The GUID of the content item the process belongs to. +#' `NA` when the content item no longer exists. +#' * `content_name`: The title of the content item, or its name when it has +#' no title. +#' * `content_url`: The URL of the content item, including its custom URL if +#' it has one. +#' * `run_as`: The Unix user the process runs as. +#' * `type`: The kind of work the process does, such as `run_app` or +#' `build_report`. +#' * `pid`: The process identifier on the Connect host. `NA` when Connect +#' has not recorded one, such as for off-host execution. +#' * `hostname`: The name of the Connect node that started the process. +#' * `job_key`: The key of the job for this process. +#' * `image`: The container image the process runs in, when using off-host +#' execution. +#' * `start_time`: When the process started. +#' * `heartbeat`: When the last CPU and memory measurement was taken. +#' * `cpu_current`: The fraction of one CPU the process used over the last +#' measurement interval. +#' * `ram`: The resident memory of the process at the last measurement, as +#' [fs::fs_bytes]. +#' +#' @examples +#' \dontrun{ +#' client <- connect() +#' +#' get_processes(client) +#' +#' # Only the processes for one content item +#' get_processes(client, content_guid = "6f300623-1e0c-48e6-a473-ddf630c0c0c3") +#' } +#' +#' @export +get_processes <- function( + src, + content_guid = NULL, + owner_guid = NULL, + hostname = NULL +) { + validate_R6_class(src, "Connect") + for (arg in c("content_guid", "owner_guid", "hostname")) { + value <- get(arg) + if (!is.null(value) && !is_string(value)) { + stop("`", arg, "` must be a single string or `NULL`.", call. = FALSE) + } + } + + res <- src$GET( + v1_url("system", "processes"), + httr::add_headers(Accept = "text/csv"), + query = list( + content_guid = content_guid, + owner_guid = owner_guid, + hostname = hostname + ), + parser = NULL + ) + + if (endpoint_does_not_exist(res)) { + # Connect versions before the v1 endpoint only have the unversioned one. + return(legacy_processes(src, content_guid, owner_guid, hostname)) + } + src$raise_error(res) + type_processes(parse_processes_csv(httr::content( + res, + as = "text", + encoding = "UTF-8" + ))) +} + +#' Get Real-Time Process Data +#' +#' `r lifecycle::badge('deprecated')` +#' +#' This function is deprecated; please use [get_processes()], which uses the +#' supported `GET /v1/system/processes` endpoint, can filter its results, and +#' returns the same columns across Connect versions. +#' +#' `get_procs()` uses the internal, unversioned `GET /metrics/procs` endpoint, +#' so its behavior and the returned columns may change in future versions of +#' Connect. It requires administrator privileges, and returns processes across +#' all nodes in a Highly Available cluster. +#' +#' @param src The source object +#' +#' @return +#' A tibble with one row per process. The columns are those sent by the server, +#' which in recent versions of Connect are `pid`, `app_id`, `app_guid`, +#' `app_name`, `app_url`, `app_run_as`, `type`, `cpu_current`, `ram`, +#' `hostname`, `job_key`, `image`, `start_time`, and `heartbeat`. +#' +#' @keywords internal +#' @export +get_procs <- function(src) { + lifecycle::deprecate_warn("0.13.0", "get_procs()", "get_processes()") + validate_R6_class(src, "Connect") + fetch_legacy_procs(src) +} + +# Columns returned by `GET /v1/system/processes`, in order. +process_columns <- c( + "content_guid", + "content_name", + "content_url", + "run_as", + "type", + "pid", + "hostname", + "job_key", + "image", + "start_time", + "heartbeat", + "cpu_current", + "ram" +) + +# Read the CSV body of `GET /v1/system/processes`. Every column is read as +# character so that types do not depend on the values present; Connect writes +# null values as empty fields, so those become `NA`. +# +# Types are applied afterwards by `type_processes()` rather than through +# `colClasses`, because: +# - `type_processes()` also types the `GET /metrics/procs` fallback, whose +# values arrive from JSON with different types, so it is needed either way. +# - `colClasses` can't produce the `start_time`/`heartbeat` or `ram` types: +# "POSIXct" drops the time from RFC 3339 strings, and there is no class for +# `fs_bytes`. +# - Columns not named in `colClasses` would get their types guessed (all-NA +# columns become logical), and naming a column the server doesn't send is a +# warning. +parse_processes_csv <- function(text) { + if (!nzchar(trimws(text))) { + return(tibble::tibble()) + } + df <- utils::read.csv( + text = text, + colClasses = "character", + na.strings = "", + check.names = FALSE, + stringsAsFactors = FALSE, + encoding = "UTF-8" + ) + tibble::as_tibble(df) +} + +# Give a processes table its documented column types, adding any missing +# columns so that empty results have the same shape as non-empty ones. Columns +# the server sends that we don't know about are kept at the end. +type_processes <- function(df) { + n <- nrow(df) + for (col in setdiff(process_columns, names(df))) { + df[[col]] <- rep(NA_character_, n) + } + df <- df[c(process_columns, setdiff(names(df), process_columns))] + + chr_cols <- c( + "content_guid", + "content_name", + "content_url", + "run_as", + "type", + "hostname", + "job_key", + "image" + ) + for (col in chr_cols) { + df[[col]] <- as.character(df[[col]]) + } + df$pid <- as.integer(df$pid) + df$cpu_current <- as.double(df$cpu_current) + df$ram <- fs::as_fs_bytes(as.double(df$ram)) + df$start_time <- coerce_datetime(df$start_time) + df$heartbeat <- coerce_datetime(df$heartbeat) + df +} + +# Fetch `GET /metrics/procs` as a tibble with the server's column names. +fetch_legacy_procs <- function(src) { + raw <- src$GET(unversioned_fallback_url("metrics", "procs")) + if (!is.null(names(raw))) { + # Old Connect versions returned an object keyed by PID rather than an + # array of processes that each carry a `pid` field. + raw <- unname(purrr::imap(raw, function(x, pid) c(list(pid = pid), x))) + } + out <- parse_connectapi_typed(raw, datetime_cols = c("start_time", "heartbeat")) + coerce_fs_bytes(out, "ram") +} + +# Fallback for `get_processes()` on Connect versions without +# `GET /v1/system/processes`: fetch `GET /metrics/procs`, convert it to the v1 +# columns and conventions, and apply the filters client-side. +legacy_processes <- function(src, content_guid, owner_guid, hostname) { + # Like the v1 endpoint, reject a content or owner GUID that names nothing + # rather than returning no processes. These requests raise a 404 if so. + if (!is.null(content_guid)) { + src$content(guid = content_guid, include = NULL) + } + if (!is.null(owner_guid)) { + src$user(owner_guid) + owned <- src$content(owner_guid = owner_guid, include = NULL) + owned_guids <- purrr::map_chr(owned, "guid") + } + + df <- fetch_legacy_procs(src) + + renames <- c( + app_guid = "content_guid", + app_name = "content_name", + app_url = "content_url", + app_run_as = "run_as", + appGuid = "content_guid", + appName = "content_name", + appUrl = "content_url", + appRunAs = "run_as", + cpuCurrent = "cpu_current" + ) + to_rename <- intersect(names(renames), names(df)) + names(df)[match(to_rename, names(df))] <- renames[to_rename] + df <- df[setdiff(names(df), c("app_id", "appId", "cpuTotal"))] + df <- type_processes(df) + + # The v1 endpoint returns null for values Connect doesn't know, where the + # unversioned endpoint uses placeholders. Match the v1 endpoint, whose CSV + # output also cannot distinguish an empty string from null. + for (col in names(df)[purrr::map_lgl(df, is.character)]) { + df[[col]][!is.na(df[[col]]) & df[[col]] == ""] <- NA_character_ + } + df$run_as[df$run_as %in% "unknown"] <- NA_character_ + df$hostname[df$hostname %in% "unknown host"] <- NA_character_ + df$pid[!is.na(df$pid) & df$pid <= 0L] <- NA_integer_ + + keep <- rep(TRUE, nrow(df)) + if (!is.null(content_guid)) { + keep <- keep & df$content_guid %in% content_guid + } + if (!is.null(hostname)) { + keep <- keep & df$hostname %in% hostname + } + if (!is.null(owner_guid)) { + keep <- keep & df$content_guid %in% owned_guids + } + df[keep, ] +} diff --git a/man/get_processes.Rd b/man/get_processes.Rd index eb3521df..d533526a 100644 --- a/man/get_processes.Rd +++ b/man/get_processes.Rd @@ -1,5 +1,5 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/get.R +% Please edit documentation in R/processes.R \name{get_processes} \alias{get_processes} \title{Get running processes} diff --git a/man/get_procs.Rd b/man/get_procs.Rd index 921ad95c..4d6ee00b 100644 --- a/man/get_procs.Rd +++ b/man/get_procs.Rd @@ -1,5 +1,5 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/get.R +% Please edit documentation in R/processes.R \name{get_procs} \alias{get_procs} \title{Get Real-Time Process Data} diff --git a/tests/integrated/test-get.R b/tests/integrated/test-get.R index 2c06cb14..090c502c 100644 --- a/tests/integrated/test-get.R +++ b/tests/integrated/test-get.R @@ -73,130 +73,6 @@ test_that("get_audit_logs works", { expect_s3_class(audit_list$time, "POSIXct") }) -# Deploy a dependency-free Python API and keep a process for it running, so -# the process endpoints have something to return. -deploy_running_python_api <- function(client) { - py <- get_runtimes(client, runtimes = "python") - py_version <- py$version[[nrow(py)]] - - dir <- fs::dir_create(fs::file_temp("python-api")) - writeLines( - c( - "def app(environ, start_response):", - " start_response('200 OK', [('Content-Type', 'text/plain')])", - " return [b'ok']" - ), - fs::path(dir, "app.py") - ) - writeLines(character(), fs::path(dir, "requirements.txt")) - jsonlite::write_json( - list( - version = 1, - metadata = list(appmode = "python-api", entrypoint = "app:app"), - python = list( - version = py_version, - package_manager = list(name = "pip", package_file = "requirements.txt") - ), - files = list( - app.py = list(checksum = unname(tools::md5sum(fs::path(dir, "app.py")))), - requirements.txt = list( - checksum = unname(tools::md5sum(fs::path(dir, "requirements.txt"))) - ) - ) - ), - fs::path(dir, "manifest.json"), - auto_unbox = TRUE - ) - - bnd <- bundle_dir(dir, filename = fs::file_temp(ext = ".tar.gz")) - tsk <- deploy(client, bnd, name = create_random_name()) - suppressMessages(poll_task(tsk)) - content <- content_item(client, tsk$content$guid) - content_update(content, min_processes = 1) - - # Visit the content too, in case min_processes is not applied right away. - httr::GET(content$get_url(), client$add_auth()) - content -} - -test_that("get_processes and get_procs return running processes", { - content <- deploy_running_python_api(client) - # Stop the process even if an expectation below fails. - withr::defer(content_update(content, min_processes = 0)) - guid <- content$content$guid - - procs <- NULL - for (i in seq_len(60)) { - procs <- get_processes(client, content_guid = guid) - if (nrow(procs) > 0 && !is.na(procs$heartbeat[[1]])) break - Sys.sleep(2) - } - - expect_identical(names(procs)[1:13], c( - "content_guid", "content_name", "content_url", "run_as", "type", "pid", - "hostname", "job_key", "image", "start_time", "heartbeat", "cpu_current", - "ram" - )) - expect_column_types(procs, list( - content_guid = "character", - content_name = "character", - content_url = "character", - run_as = "character", - type = "character", - pid = "integer", - hostname = "character", - job_key = "character", - image = "character", - start_time = "POSIXct", - heartbeat = "POSIXct", - cpu_current = "numeric", - ram = "fs_bytes" - ), exact = FALSE) - - expect_gte(nrow(procs), 1) - proc <- procs[1, ] - expect_identical(proc$content_guid, guid) - expect_identical(proc$content_name, content$content$name) - expect_identical(proc$type, "run_python_api") - expect_false(is.na(proc$pid)) - expect_false(is.na(proc$hostname)) - expect_false(is.na(proc$heartbeat)) - expect_gt(as.numeric(proc$ram), 0) - - # Unfiltered results include it. - all_procs <- get_processes(client) - expect_true(proc$job_key %in% all_procs$job_key) - - # The filters narrow the results, and are ANDed. - me <- client$me() - expect_true( - proc$job_key %in% get_processes(client, owner_guid = me$guid)$job_key - ) - expect_true( - proc$job_key %in% get_processes(client, hostname = proc$hostname)$job_key - ) - expect_equal( - nrow(get_processes(client, content_guid = guid, hostname = "no-such-host")), - 0 - ) - - # A content or owner GUID that names nothing is an error, as with the v1 - # endpoint, even when falling back. (Not the nil GUID: older Connect rejects - # it as invalid, with a 400.) - unknown_guid <- uuid::UUIDgenerate() - expect_error(get_processes(client, content_guid = unknown_guid), "404") - expect_error(get_processes(client, owner_guid = unknown_guid), "404") - - # get_procs() is deprecated but returns the same process, with the server's - # pid rather than the row index (#532). - lifecycle::expect_deprecated(old <- get_procs(client)) - old_proc <- old[old$job_key == proc$job_key, ] - expect_equal(nrow(old_proc), 1) - expect_identical(old_proc$app_guid, guid) - expect_equal(as.integer(old_proc$pid), proc$pid) - expect_s3_class(old_proc$start_time, "POSIXct") -}) - # experimental -------------------------------------------- test_that("content_list_with_permissions works", { diff --git a/tests/integrated/test-processes.R b/tests/integrated/test-processes.R new file mode 100644 index 00000000..69874651 --- /dev/null +++ b/tests/integrated/test-processes.R @@ -0,0 +1,131 @@ +# Deploy a dependency-free Python API and keep a process for it running, so +# the process endpoints have something to return. +# +# This needs content that keeps a process running. Any R content of that kind +# (Shiny, Plumber) depends on packages that Connect would have to install on +# deploy, and the only other content these tests deploy is static. A WSGI app +# with an empty requirements.txt installs nothing. +deploy_running_python_api <- function(client) { + py <- get_runtimes(client, runtimes = "python") + if (is.null(py) || nrow(py) == 0) { + skip("No Python installation available on this Connect server") + } + py_version <- py$version[[nrow(py)]] + + dir <- fs::dir_create(fs::file_temp("python-api")) + writeLines( + c( + "def app(environ, start_response):", + " start_response('200 OK', [('Content-Type', 'text/plain')])", + " return [b'ok']" + ), + fs::path(dir, "app.py") + ) + writeLines(character(), fs::path(dir, "requirements.txt")) + jsonlite::write_json( + list( + version = 1, + metadata = list(appmode = "python-api", entrypoint = "app:app"), + python = list( + version = py_version, + package_manager = list(name = "pip", package_file = "requirements.txt") + ), + files = list( + app.py = list(checksum = unname(tools::md5sum(fs::path(dir, "app.py")))), + requirements.txt = list( + checksum = unname(tools::md5sum(fs::path(dir, "requirements.txt"))) + ) + ) + ), + fs::path(dir, "manifest.json"), + auto_unbox = TRUE + ) + + bnd <- bundle_dir(dir, filename = fs::file_temp(ext = ".tar.gz")) + tsk <- deploy(client, bnd, name = create_random_name()) + suppressMessages(poll_task(tsk)) + content <- content_item(client, tsk$content$guid) + content_update(content, min_processes = 1) + + # Visit the content too, in case min_processes is not applied right away. + httr::GET(content$get_url(), client$add_auth()) + content +} + +test_that("get_processes and get_procs return running processes", { + content <- deploy_running_python_api(client) + # Stop the process even if an expectation below fails. + withr::defer(content_update(content, min_processes = 0)) + guid <- content$content$guid + + procs <- NULL + for (i in seq_len(60)) { + procs <- get_processes(client, content_guid = guid) + if (nrow(procs) > 0 && !is.na(procs$heartbeat[[1]])) break + Sys.sleep(2) + } + + expect_identical(names(procs)[1:13], c( + "content_guid", "content_name", "content_url", "run_as", "type", "pid", + "hostname", "job_key", "image", "start_time", "heartbeat", "cpu_current", + "ram" + )) + expect_column_types(procs, list( + content_guid = "character", + content_name = "character", + content_url = "character", + run_as = "character", + type = "character", + pid = "integer", + hostname = "character", + job_key = "character", + image = "character", + start_time = "POSIXct", + heartbeat = "POSIXct", + cpu_current = "numeric", + ram = "fs_bytes" + ), exact = FALSE) + + expect_gte(nrow(procs), 1) + proc <- procs[1, ] + expect_identical(proc$content_guid, guid) + expect_identical(proc$content_name, content$content$name) + expect_identical(proc$type, "run_python_api") + expect_false(is.na(proc$pid)) + expect_false(is.na(proc$hostname)) + expect_false(is.na(proc$heartbeat)) + expect_gt(as.numeric(proc$ram), 0) + + # Unfiltered results include it. + all_procs <- get_processes(client) + expect_true(proc$job_key %in% all_procs$job_key) + + # The filters narrow the results, and are ANDed. + me <- client$me() + expect_true( + proc$job_key %in% get_processes(client, owner_guid = me$guid)$job_key + ) + expect_true( + proc$job_key %in% get_processes(client, hostname = proc$hostname)$job_key + ) + expect_equal( + nrow(get_processes(client, content_guid = guid, hostname = "no-such-host")), + 0 + ) + + # A content or owner GUID that names nothing is an error, as with the v1 + # endpoint, even when falling back. (Not the nil GUID: older Connect rejects + # it as invalid, with a 400.) + unknown_guid <- uuid::UUIDgenerate() + expect_error(get_processes(client, content_guid = unknown_guid), "404") + expect_error(get_processes(client, owner_guid = unknown_guid), "404") + + # get_procs() is deprecated but returns the same process, with the server's + # pid rather than the row index (#532). + lifecycle::expect_deprecated(old <- get_procs(client)) + old_proc <- old[old$job_key == proc$job_key, ] + expect_equal(nrow(old_proc), 1) + expect_identical(old_proc$app_guid, guid) + expect_equal(as.integer(old_proc$pid), proc$pid) + expect_s3_class(old_proc$start_time, "POSIXct") +}) From 2ff5230647ddea14281da32fa66f221166bf3197 Mon Sep 17 00:00:00 2001 From: Jacob Woliver Date: Mon, 9 Nov 2026 10:19:21 -0500 Subject: [PATCH 5/5] fix: reject empty-string filters in get_processes() - get_processes() now errors on an empty content_guid, owner_guid, or hostname. Before, "" passed validation: the fallback's GUID checks requested the v1/content/ and v1/users/ list endpoints, so no 404 was raised, and the v1 endpoint was sent an empty query parameter. - Correct the integration test comment on why it deploys a Python API: other tests also deploy R Markdown, and the Shiny example is used by test-run-as.R but pins R 3.6.3. --- R/processes.R | 9 +++++++-- tests/integrated/test-processes.R | 8 +++++--- tests/testthat/test-processes.R | 6 ++++++ 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/R/processes.R b/R/processes.R index 8ca78697..2a77aaa3 100644 --- a/R/processes.R +++ b/R/processes.R @@ -76,8 +76,13 @@ get_processes <- function( validate_R6_class(src, "Connect") for (arg in c("content_guid", "owner_guid", "hostname")) { value <- get(arg) - if (!is.null(value) && !is_string(value)) { - stop("`", arg, "` must be a single string or `NULL`.", call. = FALSE) + if (!is.null(value) && !(is_string(value) && nzchar(value))) { + stop( + "`", + arg, + "` must be a single non-empty string or `NULL`.", + call. = FALSE + ) } } diff --git a/tests/integrated/test-processes.R b/tests/integrated/test-processes.R index 69874651..b71c69f9 100644 --- a/tests/integrated/test-processes.R +++ b/tests/integrated/test-processes.R @@ -1,10 +1,12 @@ # Deploy a dependency-free Python API and keep a process for it running, so # the process endpoints have something to return. # -# This needs content that keeps a process running. Any R content of that kind +# This needs content that keeps a process running. The other content these +# tests deploy is static or rendered (R Markdown), so no process stays up after +# deploying it. The Shiny example (used by test-run-as.R) pins R 3.6.3, which +# newer images don't have, and any R content that keeps a process running # (Shiny, Plumber) depends on packages that Connect would have to install on -# deploy, and the only other content these tests deploy is static. A WSGI app -# with an empty requirements.txt installs nothing. +# deploy. A WSGI app with an empty requirements.txt installs nothing. deploy_running_python_api <- function(client) { py <- get_runtimes(client, runtimes = "python") if (is.null(py) || nrow(py) == 0) { diff --git a/tests/testthat/test-processes.R b/tests/testthat/test-processes.R index 9f3803aa..ac518a63 100644 --- a/tests/testthat/test-processes.R +++ b/tests/testthat/test-processes.R @@ -198,6 +198,12 @@ test_that("get_processes() validates filters", { client <- MockConnect$new() expect_error(get_processes(client, content_guid = 1), "`content_guid`") expect_error(get_processes(client, hostname = c("a", "b")), "`hostname`") + # An empty string would request the list endpoints when checking GUIDs in + # the fallback, and an empty query parameter on the v1 endpoint. + expect_error(get_processes(client, content_guid = ""), "`content_guid`") + expect_error(get_processes(client, owner_guid = ""), "`owner_guid`") + expect_error(get_processes(client, hostname = ""), "`hostname`") + expect_error(get_processes(client, content_guid = NA_character_), "`content_guid`") expect_length(client$call_log, 0) })