diff --git a/R/tests/attach_sess.R b/R/tests/attach_sess.R index 26c19ba16..217522c79 100644 --- a/R/tests/attach_sess.R +++ b/R/tests/attach_sess.R @@ -142,6 +142,7 @@ writeLines( " connection_test <- new.env(parent=globalenv())", " connection_test$.sess_env <- new.env(parent=emptyenv())", " connection_test$.session_id <- function() 'fixture-session'", + " connection_test$`%||%` <- function(x, y) if (is.null(x)) y else x", " connection_test$.resolve_plot_backend <- function(x) 'standard'", " connection_test$.resolve_endpoint <- function(endpoint=NULL, ...) {", " if (is.null(endpoint)) '' else endpoint", @@ -176,19 +177,25 @@ writeLines( " metadata <- connection_test$.session_attach_metadata()", " stopifnot(!('attachment_id' %in% names(metadata)),", " !('auto_activate' %in% names(metadata)))", - " Sys.setenv(SESS_DISCOVERY_FILE=file.path(root, 'fixture-discovery'))", - " connection_test$.resolve_endpoint <- function(endpoint=NULL, ...) 'fixture-endpoint'", - " connection_test$.read_discovery <- function(path) list(endpoint='fixture-endpoint')", + " discovery <- file.path(root, 'fixture-discovery')", + " endpoint <- tempfile(fileext='.sock')", + " Sys.setenv(SESS_DISCOVERY_FILE=discovery)", + " Sys.unsetenv('SESS_ENDPOINT')", + " old_startup <- options(vscodeR.terminalStartup=list(", + " file=paste0(discovery, '.startup'), pid=Sys.getpid(), endpoint=endpoint,", + " run=function(endpoint, setup) setup()))", + " connection_test$.read_discovery <- function(path) list(endpoint=endpoint)", " connection_test$.configure_discovery_jgd <- function(discovery, enabled) NULL", - " result <- connection_test$connect(endpoint='fixture-endpoint',", - " attachment_id='console_8', auto_activate=FALSE)", - " options <- connection_test$.sess_env$reconnect$options", - " stopifnot(identical(options$attachment_id, 'console_8'),", - " identical(options$auto_activate, FALSE))", - " result <- connection_test$connect(endpoint='fixture-endpoint')", - " options <- connection_test$.sess_env$reconnect$options", - " stopifnot(is.null(options$attachment_id), identical(options$auto_activate, TRUE),", + " retry <- NULL", + " connection_test$.schedule_reconnect <- function(settings) retry <<- settings", + " result <- connection_test$connect(attachment_id='console_8', auto_activate=FALSE)", + " stopifnot(identical(result, FALSE), identical(retry$options$attachment_id, 'console_8'),", + " identical(retry$options$auto_activate, FALSE))", + " result <- connection_test$connect()", + " stopifnot(identical(result, FALSE), is.null(retry$options$attachment_id),", + " identical(retry$options$auto_activate, TRUE),", " is.null(connection_test$.sess_env$attachment_id))", + " options(old_startup)", " Sys.unsetenv('SESS_DISCOVERY_FILE')", "}", "publish_result <- function(value) {", diff --git a/R/tests/prepare-jgd.R b/R/tests/prepare-jgd.R index 2854131d8..8150e79d0 100644 --- a/R/tests/prepare-jgd.R +++ b/R/tests/prepare-jgd.R @@ -356,10 +356,13 @@ local({ "environment(connect_env$.schedule_reconnect) <- connect_env;", "connect_env$.reconnect_with_startup <- sess_ns$.reconnect_with_startup;", "environment(connect_env$.reconnect_with_startup) <- connect_env;", - "connect_env$poll_connection <- function(...) {", + "connect_env$poll_connection <- function(...) NULL;", + "connect_env$.await_attach <- function(con, id, ...) {", " processx::poll(list(server), 1000L); processx::conn_accept_unix_socket(server);", " processx::poll(list(server), 1000L); message <- processx::conn_read_chars(server);", - " stopifnot(grepl('\\\"method\\\":\\\"attach\\\"', message)); invisible(NULL)", + " request <- jsonlite::fromJSON(message);", + " stopifnot(identical(request$method, 'attach'), identical(request$id, id));", + " list(status='accepted', lines=character(), tail='')", "};", "answer <- vscode_r_with_jgd('jgd', function(allow_jgd=TRUE)", " connect_env$connect(endpoint=endpoint, use_rstudioapi=FALSE,", diff --git a/sess/R/dispatch.R b/sess/R/dispatch.R index 4dbc4bea3..52e5e1edd 100644 --- a/sess/R/dispatch.R +++ b/sess/R/dispatch.R @@ -9,7 +9,7 @@ ipc_json <- function(data) { #' Write a JSON object to the IPC pipe as a NDJSON line (internal) #' @keywords internal -ipc_write <- function(data) { +ipc_write <- function(data, disconnect_on_error = TRUE) { # Forked workers must never interleave frames on the parent Interactive socket. if ( isTRUE(.sess_env$interactive_connected) && !identical(.sess_env$interactive_pid, Sys.getpid()) @@ -36,8 +36,12 @@ ipc_write <- function(data) { invisible(TRUE) }, error = function(e) { - warning("[sess] Failed to send IPC message: ", e$message) - .transport_disconnect(silent = TRUE, reconnect = TRUE) + if (disconnect_on_error) { + .transport_lost() + warning("[sess] Failed to send IPC message: ", e$message) + } else { + message("[sess] Failed to send session attachment request: ", e$message) + } invisible(FALSE) } ) @@ -105,7 +109,7 @@ rpc_send <- function(method, params = list(), request = FALSE) { #' @param params A list containing the arguments for the command #' @export notify_client <- function(method, params = list()) { - if (isTRUE(.sess_env$interactive_connected) && method != "attach") { + if (isTRUE(.sess_env$interactive_connected)) { return(.interactive_event("notification", list(method = method, params = params))) } rpc_send(method, params, request = FALSE) diff --git a/sess/R/handlers.R b/sess/R/handlers.R index 5a892cffa..e0a212c8d 100644 --- a/sess/R/handlers.R +++ b/sess/R/handlers.R @@ -1518,15 +1518,16 @@ handle_dataview_dispose <- function(params) { if (!owned && !identical(connection$state, "disconnected")) { return(FALSE) } - # Callers that cannot wait for a reply (an inspection being answered) pass it in. if (is.null(address)) { - # While R answers a VS Code request, the reply could not be read. Only a - # session that no other client can take control of keeps the connection - # that sess already has. - if (isTRUE(.sess_env$answering_request)) { - return(owned && !isTRUE(.sess_env$interactive_connected)) + if (isTRUE(.sess_env$interactive_connected)) { + # Interactive resolves the current controller's viewer host. + if (isTRUE(.sess_env$answering_request)) { + return(FALSE) + } + address <- request_client("jdv/address")$address + } else { + address <- .sess_env$attach_jdv[["address"]] } - address <- request_client("jdv/address")$address } if (!is.character(address) || length(address) != 1L || is.na(address) || !nzchar(address)) { return(FALSE) diff --git a/sess/R/interactive.R b/sess/R/interactive.R index 1c06367e4..9aef118cf 100644 --- a/sess/R/interactive.R +++ b/sess/R/interactive.R @@ -157,8 +157,11 @@ interactive_start <- function(config, managed = FALSE) { options(sess.quiet = TRUE) .sess_env$interactive_token <- cfg$token Sys.setenv(JGD_SOCKET = cfg$jgd, SESS_ENDPOINT = cfg$sess) - connect(endpoint = cfg$sess, plot_backend = if (isTRUE(cfg$useJgd)) "jgd" else "standard") - if (is.null(.sess_env$con)) { + attached <- connect( + endpoint = cfg$sess, + plot_backend = if (isTRUE(cfg$useJgd)) "jgd" else "standard" + ) + if (!isTRUE(attached)) { stop("Could not connect to the session agent") } .sess_env$interactive_pid <- Sys.getpid() diff --git a/sess/R/server.R b/sess/R/server.R index 626ae9816..f74b44a1a 100644 --- a/sess/R/server.R +++ b/sess/R/server.R @@ -90,13 +90,14 @@ connect <- function( # endpoints from the generated attach script. Never redirect an unrelated client. discovery <- if (nzchar(discovery_file)) .read_discovery(discovery_file) else NULL endpoint <- if (managed_startup) discovery$endpoint %||% "" else .resolve_endpoint(endpoint) + reconnect_settings <- NULL if (managed_startup || (!is.null(discovery) && identical(discovery$endpoint, endpoint))) { .configure_discovery_jgd(discovery, allow_jgd && plot_backend %in% c("auto", "jgd")) - .sess_env$reconnect <- list( + reconnect_settings <- list( path = discovery_file, # The first handshake can lose its socket during the attach write or poll. # Until startup succeeds, even the same endpoint is eligible for retry. - endpoint = if (managed_startup) NULL else endpoint, + endpoint = NULL, startup_run = if (managed_startup) registration$run, options = list( use_rstudioapi = use_rstudioapi, @@ -109,10 +110,11 @@ connect <- function( ) } + rejected <- FALSE retry_startup <- function() { if (managed_startup) { message("[sess] Waiting for VS Code to accept the terminal connection.") - .schedule_reconnect(.sess_env$reconnect) + .schedule_reconnect(reconnect_settings) } invisible(FALSE) } @@ -152,27 +154,50 @@ connect <- function( } ) if (is.null(con)) { - return(retry_startup()) + return(FALSE) } .sess_env$con <- con - - # session_id is stable across reconnects during this R process lifetime. - notify_client("attach", .session_attach_metadata()) - - if (is.null(.sess_env$con)) { - return(FALSE) + generation <- .sess_env$transport_generation + .sess_env$attaching_generation <- generation + current <- function() { + identical(.sess_env$con, con) && identical(.sess_env$transport_generation, generation) } + success <- FALSE + on.exit({ + if (!success && current()) { + .transport_disconnect(silent = TRUE, preserve_plots = TRUE) + } + }) - if (!isTRUE(getOption("sess.quiet"))) { - print_async_msg("[sess] Connected to VS Code") + id <- basename(tempfile("attach_", tmpdir = .sess_env$tempdir)) + if ( + !ipc_write( + list(jsonrpc = "2.0", id = id, method = "attach", params = .session_attach_metadata()), + disconnect_on_error = FALSE + ) + ) { + return(FALSE) } - - # Start the polling loop - poll_connection(.sess_env$transport_generation) - if (is.null(.sess_env$con)) { + acknowledgement <- .await_attach(con, id) + if (!identical(acknowledgement$status, "accepted")) { + rejected <<- identical(acknowledgement$status, "rejected") + if (rejected) { + print_async_msg(paste0( + "[sess] VS Code rejected the session attachment: ", + acknowledgement$message + )) + signalCondition(structure( + list(message = acknowledgement$message), + class = c("sess_attach_rejected", "condition") + )) + } else if (!identical(.sess_env$reconnecting, "startup")) { + print_async_msg(paste0("[sess] ", acknowledgement$message)) + } return(FALSE) } + + .sess_env$attach_jdv <- acknowledgement$jdv if (is.na(use_rstudioapi)) { use_rstudioapi <- TRUE } @@ -202,25 +227,42 @@ connect <- function( conditionMessage(e), call_suffix ) - .transport_disconnect(silent = TRUE) stop(e) }, finally = { .sess_env$runtime_start_phase <- NULL } ) - if (!is.null(.sess_env$con) && managed_startup) { - .sess_env$reconnect$endpoint <- discovery_endpoint - .sess_env$reconnect$startup_run <- NULL + if (!current()) { + return(FALSE) + } + .sess_env$read_buffer <- acknowledgement$tail + poll_connection(generation, acknowledgement$lines) + if (!current()) { + return(FALSE) + } + .sess_env$attaching_generation <- NULL + if (is.null(.sess_env$reconnecting) && !is.null(reconnect_settings)) { + reconnect_settings$endpoint <- discovery_endpoint + reconnect_settings$startup_run <- NULL + .sess_env$reconnect <- reconnect_settings } - invisible(!is.null(.sess_env$con)) + success <- TRUE + if (!isTRUE(getOption("sess.quiet"))) { + print_async_msg("[sess] Connected to VS Code") + } + invisible(TRUE) } - if (managed_startup && !identical(registration$endpoint, discovery_endpoint)) { - # The editor replaced discovery before the revived profile reached sess. + attached <- if (managed_startup && !identical(registration$endpoint, discovery_endpoint)) { # Publish readiness for the actual endpoint, superseding the saved attempt. - return(.reconnect_with_startup(discovery_endpoint, do_connect)) + .reconnect_with_startup(discovery_endpoint, do_connect) + } else { + do_connect() + } + if (!isTRUE(attached) && !rejected) { + return(retry_startup()) } - do_connect() + invisible(isTRUE(attached)) } # Resolve the direct argument, environment variables, then discovery data. @@ -354,7 +396,7 @@ connect <- function( host <- "" } metadata <- list( - protocol_version = 2L, + protocol_version = 3L, interactive_token = .sess_env$interactive_token, sess_version = as.character(utils::packageVersion("sess")), session_id = .session_id(), @@ -431,24 +473,28 @@ connect <- function( isTRUE(allow_jgd) && settings$options$plot_backend %in% c("auto", "jgd") ) .sess_env$reconnecting <- if (is.null(settings$endpoint)) "startup" else TRUE - tryCatch( + rejected <- FALSE + attached <- tryCatch( .reconnect_with_startup(endpoint, function() { - do.call(connect, c(list(endpoint = endpoint), settings$options)) + withCallingHandlers( + do.call(connect, c(list(endpoint = endpoint), settings$options)), + sess_attach_rejected = function(e) rejected <<- TRUE + ) }), error = function(e) message("[sess] Reconnection failed: ", conditionMessage(e)), finally = { .sess_env$reconnecting <- NULL } ) - if (!is.null(.sess_env$con)) { + if (isTRUE(attached)) { settings$endpoint <- endpoint settings$startup_run <- NULL .sess_env$reconnect <- settings return(invisible(NULL)) } - # An attach write/poll failure may itself have queued a retry. Cancel it - # before scheduling our retry so there is only one pending chain. - .transport_disconnect(silent = TRUE, preserve_plots = TRUE) + if (rejected || !is.null(.sess_env$con)) { + return(invisible(NULL)) + } } next_delay <- if (is.null(settings$endpoint)) min(delay * 2, 8) else 1 .schedule_reconnect(settings, .sess_env$transport_generation, schedule, next_delay) @@ -473,7 +519,9 @@ connect <- function( .transport_disconnect <- function(silent = FALSE, reconnect = FALSE, preserve_plots = FALSE) { con <- .sess_env$con settings <- .sess_env$reconnect + .sess_env$attaching_generation <- NULL .sess_env$reconnect <- NULL + .sess_env$attach_jdv <- NULL .sess_env$con <- NULL .sess_env$transport_generation <- if (is.null(.sess_env$transport_generation)) { 1L @@ -496,6 +544,15 @@ connect <- function( invisible(NULL) } +# Startup and reconnect callers own retries until attach has committed. +.transport_lost <- function() { + .transport_disconnect( + silent = TRUE, + reconnect = is.null(.sess_env$attaching_generation), + preserve_plots = TRUE + ) +} + .transport_empty_read_is_eof <- function(con) { # A ready poll can race with a read that finds no bytes. Treat only a # connection known to have reached EOF as disconnected; processx documents @@ -504,83 +561,164 @@ connect <- function( identical(incomplete, FALSE) } +# Split complete NDJSON frames from the trailing partial frame. +.split_ipc_frames <- function(tail, chunk) { + buffer <- paste0(tail, paste0(chunk, collapse = "")) + parts <- strsplit(buffer, "\n", fixed = TRUE)[[1L]] + if (!length(parts) || endsWith(buffer, "\n")) { + return(list(lines = parts, tail = "")) + } + list(lines = parts[-length(parts)], tail = parts[[length(parts)]]) +} + +.attach_timeout <- 5 + +.ipc_json_object <- function(value) { + is.list(value) && !is.null(names(value)) +} + +.ipc_json_string <- function(value) { + is.character(value) && length(value) == 1L && !is.na(value) && nzchar(value) +} + +.valid_attach_result <- function(result) { + if (!.ipc_json_object(result) || !"jdv" %in% names(result)) { + return(FALSE) + } + jdv <- result[["jdv"]] + if (is.null(jdv)) { + return(TRUE) + } + if (!.ipc_json_object(jdv)) { + return(FALSE) + } + fields <- intersect(names(jdv), c("address", "unavailable")) + if (identical(fields, "address")) { + return(.ipc_json_string(jdv[["address"]])) + } + unavailable <- jdv[["unavailable"]] + identical(fields, "unavailable") && + .ipc_json_object(unavailable) && + identical(unavailable[["code"]], "listener_failed") && + .ipc_json_string(unavailable[["message"]]) +} + +.await_attach <- function(con, id, timeout = .attach_timeout) { + deadline <- proc.time()[["elapsed"]] + timeout + lines <- character() + tail <- "" + failed <- function(message) { + list(status = "failed", message = message) + } + closed <- function() { + failed("IPC connection closed before VS Code acknowledged the session attachment.") + } + repeat { + remaining <- deadline - proc.time()[["elapsed"]] + if (remaining <= 0) { + return(failed("Timed out waiting for VS Code to acknowledge the session attachment.")) + } + ready <- tryCatch( + processx::poll(list(con), as.integer(ceiling(remaining * 1000))), + error = function(e) "error" + ) + if (length(ready) && ready[[1L]] %in% c("closed", "error")) { + return(closed()) + } + if (!length(ready) || !identical(ready[[1L]], "ready")) { + next + } + chunk <- tryCatch(processx::conn_read_chars(con), error = function(e) NULL) + if (is.null(chunk) || (!any(nzchar(chunk)) && .transport_empty_read_is_eof(con))) { + return(closed()) + } + frames <- .split_ipc_frames(tail, chunk) + tail <- frames$tail + for (i in seq_along(frames$lines)) { + line <- frames$lines[[i]] + reply <- tryCatch(jsonlite::fromJSON(line, simplifyVector = FALSE), error = function(e) NULL) + if (!.ipc_json_object(reply) || !identical(reply[["id"]], id) || "method" %in% names(reply)) { + lines <- c(lines, line) + next + } + fields <- intersect(names(reply), c("result", "error")) + if (identical(reply[["jsonrpc"]], "2.0")) { + if (identical(fields, "result") && .valid_attach_result(reply[["result"]])) { + return(list( + status = "accepted", + jdv = reply[["result"]][["jdv"]], + lines = c(lines, frames$lines[-seq_len(i)]), + tail = tail + )) + } + error <- reply[["error"]] + if ( + identical(fields, "error") && + .ipc_json_object(error) && + is.numeric(error[["code"]]) && + length(error[["code"]]) == 1L && + is.finite(error[["code"]]) && + error[["code"]] == trunc(error[["code"]]) && + .ipc_json_string(error[["message"]]) + ) { + return(list(status = "rejected", message = error[["message"]])) + } + } + return(failed("VS Code sent an invalid session attachment acknowledgement.")) + } + } +} + #' Poll the IPC connection for incoming messages (internal) #' #' Runs as a recurring later callback; dispatches NDJSON messages from vscode. #' @keywords internal -poll_connection <- function(generation = .sess_env$transport_generation) { +poll_connection <- function(generation = .sess_env$transport_generation, pending = character()) { if ( isTRUE(.sess_env$interactive_connected) && !identical(.sess_env$interactive_pid, Sys.getpid()) ) { return() } con <- .sess_env$con - if (is.null(con) || !identical(generation, .sess_env$transport_generation)) { - return() - } - - # Non-blocking poll: 0 ms timeout - ready <- tryCatch( - processx::poll(list(con), 0L), - error = function(e) { - .transport_disconnect(silent = TRUE, reconnect = TRUE) - NULL - } - ) - - if (is.null(.sess_env$con) || !identical(generation, .sess_env$transport_generation)) { - return() - } - - # A NULL poll result is transient; keep the loop alive and reschedule below. - if (!is.null(ready) && length(ready) > 0 && identical(ready[[1]], "ready")) { - chunk <- tryCatch( - processx::conn_read_chars(con), - error = function(e) { - .transport_disconnect(silent = TRUE, reconnect = TRUE) - NULL + current <- function() { + !is.null(con) && + identical(con, .sess_env$con) && + identical(generation, .sess_env$transport_generation) + } + dispatch <- function(lines) { + for (line in lines) { + if (!current()) { + break } - ) - - if (is.null(.sess_env$con)) { - return() - } - has_data <- !is.null(chunk) && length(chunk) > 0L && any(nzchar(chunk)) - if (!has_data) { - if (.transport_empty_read_is_eof(con)) { - .transport_disconnect(silent = TRUE, reconnect = TRUE) - return() - } - } else { - .sess_env$read_buffer <- paste0(.sess_env$read_buffer, paste0(chunk, collapse = "")) - parts <- strsplit(.sess_env$read_buffer, "\n", fixed = TRUE)[[1]] - - n <- length(parts) - # Keep any trailing partial line in the buffer - if (endsWith(.sess_env$read_buffer, "\n")) { - .sess_env$read_buffer <- "" - } else { - .sess_env$read_buffer <- parts[n] - parts <- parts[-n] - } - - for (line in parts) { - line <- trimws(line) - if (!nzchar(line)) { - next - } + line <- trimws(line) + if (nzchar(line)) { tryCatch( dispatch_message(line), error = function(e) warning("[sess] Error dispatching message: ", e$message) ) } } - } else if (length(ready) > 0 && ready[[1]] %in% c("closed", "error")) { - .transport_disconnect(silent = TRUE, reconnect = TRUE) - return() } - if (!is.null(.sess_env$con) && identical(generation, .sess_env$transport_generation)) { + dispatch(pending) + if (!current()) { + return() + } + ready <- tryCatch(processx::poll(list(con), 0L), error = function(e) "error") + if (length(ready) && identical(ready[[1L]], "ready")) { + chunk <- tryCatch(processx::conn_read_chars(con), error = function(e) NULL) + if (is.null(chunk) || (!any(nzchar(chunk)) && .transport_empty_read_is_eof(con))) { + .transport_lost() + return() + } + frames <- .split_ipc_frames(.sess_env$read_buffer, chunk) + .sess_env$read_buffer <- frames$tail + dispatch(frames$lines) + } else if (length(ready) && ready[[1L]] %in% c("closed", "error")) { + .transport_lost() + return() + } + if (current()) { later::later(function() poll_connection(generation), 0.01) } } diff --git a/sess/README.md b/sess/README.md index 8990919cd..37d63d33f 100644 --- a/sess/README.md +++ b/sess/README.md @@ -212,14 +212,15 @@ This section is for developers writing or debugging a client. ### Handshake -On connecting, `sess` sends an `attach` notification: +On connecting, `sess` sends an `attach` request: ```json { "jsonrpc": "2.0", + "id": "attach_1", "method": "attach", "params": { - "protocol_version": 2, + "protocol_version": 3, "sess_version": "3.0.0", "session_id": "sess-session-...", "host": "compute42", @@ -239,14 +240,35 @@ On connecting, `sess` sends an `attach` notification: `protocol_version` versions the message contract independently of the R package version. The extension rejects unsupported versions. `session_id` identifies an R process across reconnects; PID and host are metadata, not connection identity. +The receiver acknowledges the request before publishing the connection. A native +session gets a jdv listener address for the lifetime of that connection: + +```json +{"jsonrpc":"2.0","id":"attach_1","result":{"jdv":{"address":"/tmp/vscr-jdv-abc.sock"}}} +``` + +If the listener fails to start, the session can still attach and use the sess +data viewer: + +```json +{"jsonrpc":"2.0","id":"attach_1","result":{"jdv":{"unavailable":{"code":"listener_failed","message":"Timed out starting the jdv listener."}}}} +``` + +The Interactive bridge acknowledges with `{"jdv":null}` as its result. Clients +ignore additional fields in the result and its jdv object. + +Invalid attach metadata or an unsupported protocol version produces a JSON-RPC +error with the same request ID before the receiver closes the socket. The client +waits up to five seconds for an acknowledgement before starting its runtime. + The attached socket's lifetime controls cleanup. A replacement socket with the same identity supersedes the old one; a late close cannot remove its replacement. A fork child receives its own identity. Terminal PID association is local-only. -Protocol version 2 includes the viewer-state generation contract: dynamic table +Protocol version 3 retains the viewer-state generation contract: dynamic table and list `dataview` notifications provide `state_generation`, and `dataview_dispose` requires it. Both the extension and `sess` must support version -2. The extension/webview `documentGeneration` field is internal to the client +3. The extension/webview `documentGeneration` field is internal to the client and is not part of the `sess` IPC contract. ### Notifications from R to client @@ -255,7 +277,6 @@ Sent with `notify_client()`. | Method | Params | Sent when | |---|---|---| -| `attach` | see above | Connection is established. | | `workspace_updated` | none | A top-level command completes. | | `dataview` | `title`, `source`, `type`; `view_id` and `state_generation` for tables/lists, plus `navigation` for lists; `file` for other objects | `View()` is called. | | `plot_updated` | none | The standard device records a new or changed plot. | diff --git a/sess/inst/tinytest/test-attachment-metadata.R b/sess/inst/tinytest/test-attachment-metadata.R index e72a45bf5..3c3635976 100644 --- a/sess/inst/tinytest/test-attachment-metadata.R +++ b/sess/inst/tinytest/test-attachment-metadata.R @@ -120,14 +120,28 @@ local({ env$.configure_discovery_jgd <- function(discovery, jgd_enabled) { discovery_jgd_enabled <<- c(discovery_jgd_enabled, jgd_enabled) } - invisible(env$connect( - endpoint = target_endpoint, + options <- list( + vscodeR.terminalStartup = list( + pid = Sys.getpid(), + file = paste0(discovery_path, ".startup"), + endpoint = target_endpoint, + run = function(endpoint, setup) setup() + ) + ) + previous_options <- base::options(options) + on.exit(base::options(previous_options), add = TRUE) + Sys.unsetenv("SESS_ENDPOINT") + retry <- NULL + env$.schedule_reconnect <- function(settings) { + retry <<- settings + } + expect_false(env$connect( attachment_id = "console_retry_2", auto_activate = FALSE, allow_jgd = FALSE )) - expect_equal(state$reconnect$options$attachment_id, "console_retry_2") - expect_false(state$reconnect$options$auto_activate) - expect_false(state$reconnect$options$allow_jgd) + expect_equal(retry$options$attachment_id, "console_retry_2") + expect_false(retry$options$auto_activate) + expect_false(retry$options$allow_jgd) expect_false(tail(discovery_jgd_enabled, 1L)) }) diff --git a/sess/inst/tinytest/test-connect-failure.R b/sess/inst/tinytest/test-connect-failure.R index c1f82d504..ee1ea38e4 100644 --- a/sess/inst/tinytest/test-connect-failure.R +++ b/sess/inst/tinytest/test-connect-failure.R @@ -50,11 +50,17 @@ local({ # Accept while the client is open, including on Windows named pipes. Drive # subsequent retries explicitly instead of starting background poll timers. env$poll_connection <- function(...) { + NULL + } + env$.await_attach <- function(con, id, ...) { processx::poll(list(server), 1000L) processx::conn_accept_unix_socket(server) processx::poll(list(server), 1000L) line <- processx::conn_read_chars(server) - expect_equal(jsonlite::fromJSON(trimws(line))$method, "attach") + request <- jsonlite::fromJSON(trimws(line)) + expect_identical(request$method, "attach") + expect_identical(request$id, id) + list(status = "accepted", lines = character(), tail = "") } close_peer <- function() { close(server) @@ -109,3 +115,121 @@ local({ expect_true(isTRUE(do.call(env$connect, c(list(endpoint = endpoint), opts)))) close_peer() }) + +for (reject in c(FALSE, TRUE)) { + local({ + # Managed startup retries the same endpoint after a missing acknowledgement. + # Managed startup stops automatic retries after an explicit rejection. + env <- new.env(parent = asNamespace("sess")) + for (name in c("connect", ".schedule_reconnect")) { + fun <- get(name, asNamespace("sess")) + environment(fun) <- env + assign(name, fun, env) + } + endpoint <- if (.Platform$OS.type == "windows") { + paste0("\\\\?\\pipe\\", basename(tempfile("sess-retry-"))) + } else { + tempfile(fileext = ".sock") + } + discovery <- tempfile(fileext = ".json") + writeLines( + jsonlite::toJSON(list(version = 1L, endpoint = endpoint), auto_unbox = TRUE), + discovery + ) + saved_env <- Sys.getenv(c("SESS_DISCOVERY_FILE", "SESS_ENDPOINT"), unset = NA_character_) + Sys.setenv(SESS_DISCOVERY_FILE = discovery) + Sys.unsetenv("SESS_ENDPOINT") + states <- logical() + saved_options <- options( + vscodeR.terminalStartup = list( + pid = Sys.getpid(), + file = paste0(discovery, ".startup"), + endpoint = endpoint, + run = function(endpoint, setup) { + result <- setup() + states <<- c(states, isTRUE(result)) + result + } + ) + ) + + server <- function() { + processx::conn_create_unix_socket(endpoint, encoding = "") + } + peer <- server() + close_peer <- function() { + if (!is.null(peer)) { + close(peer) + peer <<- NULL + if (.Platform$OS.type != "windows") unlink(endpoint) + } + } + on.exit({ + sess:::.transport_disconnect(silent = TRUE) + close_peer() + unlink(discovery) + options(saved_options) + for (key in names(saved_env)) { + if (is.na(saved_env[[key]])) { + Sys.unsetenv(key) + } else { + do.call(Sys.setenv, as.list(saved_env[key])) + } + } + }) + + callbacks <- list() + schedule_retry <- function(callback, delay) { + callbacks[[length(callbacks) + 1L]] <<- callback + } + env$.schedule_reconnect <- local({ + reconnect <- env$.schedule_reconnect + function( + settings, + generation = sess:::.sess_env$transport_generation, + schedule = schedule_retry, + delay = 1 + ) { + reconnect(settings, generation, schedule, delay) + } + }) + + attempts <- 0L + env$poll_connection <- function(...) { + NULL + } + env$.await_attach <- function(...) { + attempts <<- attempts + 1L + processx::poll(list(peer), 1000L) + processx::conn_accept_unix_socket(peer) + if (attempts == 1L) { + return(list(status = "failed", message = "Timed out waiting for acknowledgement.")) + } + if (reject) { + return(list(status = "rejected", message = "Bad metadata")) + } + list(status = "accepted", lines = character(), tail = "") + } + attempt <- function() { + env$connect(use_rstudioapi = FALSE, plot_backend = "standard") + } + expect_false(getOption("vscodeR.terminalStartup")$run(endpoint, attempt)) + expect_identical(states, FALSE) + expect_null(sess:::.sess_env$reconnect) + expect_length(callbacks, 1L) + close_peer() + peer <- server() + retry <- callbacks[[1L]] + callbacks <- list() + retry() + expect_identical(attempts, 2L) + expect_length(callbacks, 0L) + expect_identical(states, c(FALSE, !reject)) + if (reject) { + expect_null(sess:::.sess_env$con) + expect_null(sess:::.sess_env$reconnect) + } else { + expect_identical(sess:::.sess_env$reconnect$endpoint, endpoint) + } + }) +} diff --git a/sess/inst/tinytest/test-connection-message.R b/sess/inst/tinytest/test-connection-message.R index 31cddca6e..40ec0bdb0 100644 --- a/sess/inst/tinytest/test-connection-message.R +++ b/sess/inst/tinytest/test-connection-message.R @@ -26,13 +26,32 @@ local({ } opts <- list(use_rstudioapi = FALSE, plot_backend = "standard") + server <- NULL + # Drive the same-process peer before entering the blocking attach reader. + env$.await_attach <- function(con, id) { + processx::poll(list(server), 1000L) + processx::conn_accept_unix_socket(server) + processx::poll(list(server), 1000L) + request <- jsonlite::fromJSON(processx::conn_read_chars(server)) + expect_identical(request$method, "attach") + expect_identical(request$id, id) + ack <- list(jsonrpc = "2.0", id = request$id, result = list(jdv = NULL)) + bytes <- charToRaw(paste0(sess:::ipc_json(ack), "\n")) + while (length(bytes)) { + bytes <- processx::conn_write(server, bytes) + } + sess:::.await_attach(con, id) + } + connect_once <- function(quiet) { path <- tempfile(fileext = ".sock") - server <- processx::conn_create_unix_socket(path, encoding = "") + previous <- server + server <<- processx::conn_create_unix_socket(path, encoding = "") on.exit( { sess:::.transport_disconnect(silent = TRUE) try(close(server), silent = TRUE) + server <<- previous unlink(path) }, add = TRUE @@ -71,7 +90,6 @@ local({ jsonlite::toJSON(list(version = 1L, endpoint = replacement), auto_unbox = TRUE), discovery ) - server <- NULL on.exit( { if (!is.null(server)) { diff --git a/sess/inst/tinytest/test-ipc.R b/sess/inst/tinytest/test-ipc.R index 425d6fdd2..4fa9c9599 100644 --- a/sess/inst/tinytest/test-ipc.R +++ b/sess/inst/tinytest/test-ipc.R @@ -611,43 +611,164 @@ local({ expect_equal(res$value, 42L) }) -# A peer disappearing while a request is waiting stops the runtime, and a new -# discovery reconnect starts a fresh runtime without duplicating callbacks. -local({ - .sess_env <- sess:::.sess_env - if (!requireNamespace("processx", quietly = TRUE) || .Platform$OS.type == "windows") { - return(invisible(NULL)) - } - - listener <- function() { - path <- tempfile(fileext = ".sock") - server <- tryCatch( - processx::conn_create_unix_socket(path, encoding = ""), - error = function(e) NULL +# Run the wire peer independently of the client's synchronous attach wait. +attach_peer <- function(mode = "accept") { + path <- if (.Platform$OS.type == "windows") { + paste0("\\\\?\\pipe\\", basename(tempfile("sess-attach-"))) + } else { + tempfile(fileext = ".sock") + } + ready <- tempfile() + request <- tempfile() + serve <- function(path, ready, request, mode) { + server <- processx::conn_create_unix_socket(path, encoding = "") + on.exit(close(server)) + file.create(ready) + processx::poll(list(server), 5000L) + processx::conn_accept_unix_socket(server) + buffer <- "" + while (!grepl("\n", buffer, fixed = TRUE)) { + if (!identical(processx::poll(list(server), 5000L)[[1L]], "ready")) { + stop("Attach request did not arrive") + } + buffer <- paste0(buffer, processx::conn_read_chars(server)) + } + writeLines(sub("\n.*$", "", buffer), request) + attach <- jsonlite::fromJSON(readLines(request)) + write_frame <- function(frame) { + bytes <- charToRaw(frame) + while (length(bytes)) { + bytes <- processx::conn_write(server, bytes) + } + } + if (mode == "eof") { + return() + } + payload <- if (mode == "reject") { + list(error = list(code = -32602L, message = "Bad metadata")) + } else { + list(result = list(jdv = NULL)) + } + ack <- paste0( + jsonlite::toJSON( + c(list(jsonrpc = "2.0", id = attach$id), payload), + auto_unbox = TRUE, + null = "null" + ), + "\n" ) - if (is.null(server)) { - return(NULL) + if (mode == "split") { + first <- '{"jsonrpc":"2.0","id":11,"method":"workspace","params":{}}' + second <- '{"jsonrpc":"2.0","id":12,"method":"workspace","params":{}}' + write_frame(substr(ack, 1L, 10L)) + Sys.sleep(0.05) + write_frame(paste0(substr(ack, 11L, nchar(ack)), first, "\n", substr(second, 1L, 12L))) + Sys.sleep(0.2) + write_frame(paste0(substr(second, 13L, nchar(second)), "\n")) + } else if (mode != "silent") { + write_frame(ack) } - list(path = path, server = server) + Sys.sleep(30) } - accept_peer <- function(server) { - ready <- tryCatch(processx::poll(list(server), 1000L), error = function(e) NULL) - if (is.null(ready) || !ready[[1]] %in% c("connect", "ready")) { - return(NULL) + script <- tempfile(fileext = ".R") + writeLines( + c("serve <-", deparse(serve), "do.call(serve, as.list(commandArgs(trailingOnly = TRUE)))"), + script + ) + peer <- processx::process$new( + file.path(R.home("bin"), "Rscript"), + c("--vanilla", script, path, ready, request, mode), + stderr = "|", + cleanup_tree = TRUE + ) + deadline <- Sys.time() + 5 + while (!file.exists(ready) && peer$is_alive() && Sys.time() < deadline) { + Sys.sleep(0.01) + } + if (!file.exists(ready)) { + peer$kill() + unlink(script) + stop("Attach peer did not start: ", paste(peer$read_all_error(), collapse = "\n")) + } + list( + path = path, + request = request, + close = function() { + peer$kill() + unlink(c(script, ready, request, if (.Platform$OS.type != "windows") path)) } + ) +} + +local({ + # attach accepts a split acknowledgement and preserves following frames + peer <- attach_peer("split") + on.exit({ + sess:::.transport_disconnect(silent = TRUE) + peer$close() + }) + env <- new.env(parent = asNamespace("sess")) + for (name in c("connect", "poll_connection")) { + fun <- get(name, asNamespace("sess")) + environment(fun) <- env + assign(name, fun, env) + } + ids <- integer() + env$dispatch_message <- function(line) { + expect_true(isTRUE(sess:::.runtime_state()$active)) + ids <<- c(ids, jsonlite::fromJSON(line)$id) + } + expect_true(env$connect(peer$path, use_rstudioapi = FALSE, plot_backend = "standard")) + deadline <- Sys.time() + 2 + while (length(ids) < 2L && Sys.time() < deadline) { + later::run_now(0.1) + } + expect_identical(ids, c(11L, 12L)) +}) + +local({ + # attach closes a connection on rejection, EOF, or deadline + env <- new.env(parent = asNamespace("sess")) + for (name in c("connect", ".await_attach")) { + fun <- get(name, asNamespace("sess")) + environment(fun) <- env + assign(name, fun, env) + } + env$.attach_timeout <- 0.2 + for (mode in c("reject", "eof", "silent")) { + peer <- attach_peer(mode) tryCatch( { - processx::conn_accept_unix_socket(server) - server + output <- capture.output( + connected <- env$connect(peer$path, use_rstudioapi = FALSE, plot_backend = "standard") + ) + expected <- switch( + mode, + reject = "rejected the session attachment: Bad metadata", + eof = "closed before VS Code acknowledged", + silent = "Timed out waiting for VS Code to acknowledge" + ) + expect_true(any(grepl(expected, output, fixed = TRUE))) + expect_false(connected) + expect_null(sess:::.sess_env$con) + expect_identical(sess:::.sess_env$read_buffer, "") + expect_identical(sess:::.sess_env$pending_responses, list()) + expect_false(isTRUE(sess:::.runtime_state()$active)) }, - error = function(e) NULL + finally = peer$close() ) } +}) - first <- listener() - if (is.null(first)) { +# A peer disappearing while a request is waiting stops the runtime, and a new +# discovery reconnect starts a fresh runtime without duplicating callbacks. +local({ + .sess_env <- sess:::.sess_env + if (!requireNamespace("processx", quietly = TRUE) || .Platform$OS.type == "windows") { return(invisible(NULL)) } + + first <- attach_peer() discovery <- tempfile(fileext = ".json") old_discovery <- Sys.getenv("SESS_DISCOVERY_FILE", unset = NA_character_) Sys.setenv(SESS_DISCOVERY_FILE = discovery) @@ -679,38 +800,26 @@ local({ original_plot_hook <- getHook("plot.new") original_grid_hook <- getHook("grid.newpage") second <- NULL - first_peer <- NULL - second_peer <- NULL on.exit( { sess:::.transport_disconnect() - for (con in list( - first_peer, - second_peer, - first$server, - if (!is.null(second)) second$server else NULL - )) { - if (!is.null(con)) try(close(con), silent = TRUE) - } - unlink(c(first$path, if (!is.null(second)) second$path else character())) + first$close() + if (!is.null(second)) second$close() }, add = TRUE ) - connected <- tryCatch( - { - sess::connect(endpoint = first$path, use_rstudioapi = FALSE, plot_backend = "standard") - first_peer <- accept_peer(first$server) - !is.null(first_peer) && !is.null(.sess_env$con) - }, - error = function(e) FALSE + connected <- sess::connect( + endpoint = first$path, + use_rstudioapi = FALSE, + plot_backend = "standard" ) - expect_true(isTRUE(connected)) + expect_true(connected) if (!isTRUE(connected)) { return(invisible(NULL)) } - close(first_peer) + first$close() result <- suppressWarnings(sess::request_client("test/disconnect_wait")) expect_false(isTRUE(result)) expect_null(.sess_env$con) @@ -730,28 +839,19 @@ local({ expect_equal(length(grep("^sess.workspace$", getTaskCallbackNames())), 0L) expect_equal(length(grep("^sess.plot$", getTaskCallbackNames())), 0L) - second <- listener() - expect_false(is.null(second)) - if (is.null(second)) { - return(invisible(NULL)) - } + second <- attach_peer() publish(second$path) deadline <- Sys.time() + 5 while (is.null(.sess_env$con) && Sys.time() < deadline) { later::run_now(0.1) } expect_false(is.null(.sess_env$con)) - second_peer <- accept_peer(second$server) - expect_false(is.null(second_peer)) expect_equal(sess:::.session_id(), identity) expect_false(.sess_env$reconnect$options$use_rstudioapi) expect_equal(.sess_env$reconnect$options$plot_backend, "standard") expect_null(.sess_env$attachment_id) expect_true(.sess_env$auto_activate) - attach_ready <- tryCatch(processx::poll(list(second_peer), 1000L), error = function(e) NULL) - expect_false(is.null(attach_ready)) - attach_line <- processx::conn_read_chars(second_peer) - attach_message <- jsonlite::fromJSON(trimws(attach_line), simplifyVector = FALSE) + attach_message <- jsonlite::fromJSON(readLines(second$request), simplifyVector = FALSE) expect_equal(attach_message$method, "attach") expect_false("attachment_id" %in% names(attach_message$params)) expect_false("auto_activate" %in% names(attach_message$params)) @@ -769,42 +869,16 @@ local({ return(invisible(NULL)) } - path <- tempfile(fileext = ".sock") - server <- tryCatch( - processx::conn_create_unix_socket(path, encoding = ""), - error = function(e) NULL - ) - if (is.null(server)) { - return(invisible(NULL)) - } - peer <- NULL - on.exit( - { - sess:::.transport_disconnect() - if (!is.null(peer)) { - try(close(peer), silent = TRUE) - } - try(close(server), silent = TRUE) - unlink(path) - }, - add = TRUE - ) - - connected <- tryCatch( - { - sess::connect(endpoint = path, use_rstudioapi = FALSE, plot_backend = "standard") - ready <- processx::poll(list(server), 1000L) - if (ready[[1]] %in% c("connect", "ready")) { - processx::conn_accept_unix_socket(server) - peer <- server - } - !is.null(peer) && !is.null(.sess_env$con) - }, - error = function(e) FALSE - ) - if (!isTRUE(connected)) { - return(invisible(NULL)) - } + peer <- attach_peer() + on.exit({ + sess:::.transport_disconnect() + peer$close() + }) + expect_true(sess::connect( + endpoint = peer$path, + use_rstudioapi = FALSE, + plot_backend = "standard" + )) close(.sess_env$con) sent <- suppressWarnings(sess:::ipc_write(list(method = "test/write_failure"))) @@ -812,3 +886,20 @@ local({ expect_null(.sess_env$con) expect_false(isTRUE(sess:::.runtime_state()$active)) }) + +# A terminal profile connects before R attaches utils, so splitting a partial +# attach acknowledgement must rely on base R only. +local({ + code <- paste( + 'stopifnot(!"package:utils" %in% search());', + 'frames <- sess:::.split_ipc_frames("", c("first\\n", "sec"));', + 'stopifnot(identical(frames$lines, "first"), identical(frames$tail, "sec"));', + 'cat("split-ok")' + ) + result <- processx::run( + file.path(R.home("bin"), "Rscript"), + c("--vanilla", "--default-packages=NULL", "-e", code), + env = c("current", R_LIBS = paste(.libPaths(), collapse = .Platform$path.sep)) + ) + expect_true(grepl("split-ok", result$stdout, fixed = TRUE), info = result$stderr) +}) diff --git a/sess/inst/tinytest/test-jdv.R b/sess/inst/tinytest/test-jdv.R index 0c0845190..d93019958 100644 --- a/sess/inst/tinytest/test-jdv.R +++ b/sess/inst/tinytest/test-jdv.R @@ -12,6 +12,8 @@ local({ ns <- asNamespace("sess") runtime <- sess:::.sess_env previous_con <- runtime$con + previous_attach_jdv <- runtime$attach_jdv + session_server <- NULL previous_plot_path <- runtime$latest_plot_path previous_interactive_connected <- runtime$interactive_connected original_request_client <- ns$request_client @@ -19,12 +21,19 @@ local({ host <- NULL on.exit( { - sess:::runtime_stop() + if (is.null(session_server)) { + sess:::runtime_stop() + } else { + sess:::.transport_disconnect(silent = TRUE) + close(session_server) + if (.Platform$OS.type != "windows") unlink(endpoint) + } jdv::jdv_disconnect() unlockBinding("request_client", ns) assign("request_client", original_request_client, envir = ns) lockBinding("request_client", ns) runtime$con <- previous_con + runtime$attach_jdv <- previous_attach_jdv runtime$latest_plot_path <- previous_plot_path runtime$interactive_connected <- previous_interactive_connected if (!is.null(host)) { @@ -42,20 +51,12 @@ local({ options(sess.dataviewer = NULL) sess:::runtime_start(use_rstudioapi = FALSE, plot_backend = "standard") - # VS Code answers `jdv/address` with the address of its per-session listener. - stub_address <- function(address) { - unlockBinding("request_client", ns) - assign( - "request_client", - function(action, args = list()) { - if (is.null(address)) stop("no jdv transport") else list(address = address) - }, - envir = ns - ) - lockBinding("request_client", ns) + set_address <- function(address) { + runtime$attach_jdv <- if (!is.null(address)) list(address = address) } read_messages <- function() { - messages <- strsplit(processx::conn_read_chars(pipe[[1L]]), "\n", fixed = TRUE)[[1L]] + peer <- if (is.null(session_server)) pipe[[1L]] else session_server + messages <- strsplit(processx::conn_read_chars(peer), "\n", fixed = TRUE)[[1L]] lapply(messages[nzchar(messages)], jsonlite::fromJSON, simplifyVector = FALSE) } used_sess_viewer <- function(messages = read_messages()) { @@ -103,16 +104,16 @@ local({ # The opt-out keeps the sess data viewer. options(sess.dataviewer = "sess") - stub_address("tcp://127.0.0.1:1") + set_address("tcp://127.0.0.1:1") expect_false(sess:::.jdv_connect()) utils::View(sample) expect_true(used_sess_viewer()) options(sess.dataviewer = NULL) # Without a transport, or with an unreachable one, View() falls back and leaves jdv alone. - stub_address(NULL) + set_address(NULL) expect_false(sess:::.jdv_connect()) - stub_address("tcp://127.0.0.1:1") + set_address("tcp://127.0.0.1:1") expect_false(sess:::.jdv_connect()) expect_identical(jdv::jdv_connection()$state, "disconnected") expect_null(runtime$jdv_address) @@ -122,64 +123,13 @@ local({ # An embedded session of another jdv user is never taken over. jdv::jdv_register(sample) expect_identical(jdv::jdv_connection()$state, "embedded") - stub_address("tcp://127.0.0.1:1") + set_address("tcp://127.0.0.1:1") expect_false(sess:::.jdv_connect()) utils::View(sample) expect_true(used_sess_viewer()) expect_identical(jdv::jdv_connection()$state, "embedded") jdv::jdv_disconnect() - # A View() reached while sess answers a socket request cannot wait for the - # `jdv/address` reply, which only the next poll would read. It falls back to - # the sess viewer instead of blocking R. - unlockBinding("request_client", ns) - assign("request_client", original_request_client, envir = ns) - lockBinding("request_client", ns) - # Open `sample` through a workspace_view socket request; return what sess sent. - view_from_workspace <- function() { - workspace_name <- basename(tempfile("jdv_workspace_")) - assign(workspace_name, sample, envir = .GlobalEnv) - # connect() sets the directory that request IDs are made in. - previous_tempdir <- runtime$tempdir - runtime$tempdir <- tempdir() - on.exit( - { - setTimeLimit(elapsed = Inf) - runtime$tempdir <- previous_tempdir - rm(list = workspace_name, envir = .GlobalEnv) - }, - add = TRUE - ) - setTimeLimit(elapsed = 10, transient = TRUE) - sess:::dispatch_message(as.character(jsonlite::toJSON( - list( - jsonrpc = "2.0", - id = "workspace-view", - method = "workspace_view", - params = list(name = workspace_name) - ), - auto_unbox = TRUE - ))) - read_messages() - } - messages <- view_from_workspace() - reply <- Filter(function(message) identical(message$id, "workspace-view"), messages) - expect_identical(length(reply), 1L) - expect_true(isTRUE(reply[[1L]]$result)) - # The time limit only keeps a regression from blocking the tests; its error - # would also end in the fallback, so the request itself must not be sent. - expect_false(any(vapply( - messages, - function(message) identical(message$method, "jdv/address"), - logical(1L) - ))) - expect_true(any(vapply( - messages, - function(message) identical(message$method, "dataview"), - logical(1L) - ))) - expect_identical(jdv::jdv_connection()$state, "disconnected") - # A minimal viewer host: it records every line that jdv sends. received <- tempfile(fileext = ".jsonl") port <- NULL @@ -214,7 +164,35 @@ local({ exit_file("no free TCP port for the viewer host") } address <- sprintf("tcp://127.0.0.1:%d", port) - stub_address(address) + endpoint <- if (.Platform$OS.type == "windows") { + paste0("\\\\?\\pipe\\", basename(tempfile("sess-attach-"))) + } else { + tempfile(fileext = ".sock") + } + session_server <- processx::conn_create_unix_socket(endpoint, encoding = "") + env <- new.env(parent = ns) + env$connect <- sess::connect + environment(env$connect) <- env + send <- function(message) { + bytes <- charToRaw(paste0(sess:::ipc_json(message), "\n")) + while (length(bytes)) { + bytes <- processx::conn_write(session_server, bytes) + } + } + env$.await_attach <- function(con, id) { + processx::poll(list(session_server), 1000L) + processx::conn_accept_unix_socket(session_server) + processx::poll(list(session_server), 1000L) + request <- read_messages()[[1L]] + expect_identical(request$id, id) + expect_identical(request$method, "attach") + send(list(jsonrpc = "2.0", id = id, result = list(jdv = list(address = address)))) + sess:::.await_attach(con, id) + } + # Leave the pre-attach pipe under the fixture's ownership. + runtime$con <- NULL + expect_true(env$connect(endpoint, use_rstudioapi = FALSE, plot_backend = "standard")) + expect_identical(runtime$attach_jdv$address, address) host_messages <- function(n, timeout = 10) { deadline <- Sys.time() + timeout repeat { @@ -248,9 +226,52 @@ local({ expect_null(runtime$jdv_address) }) + request_view <- function(method, params) { + id <- "view-request" + send(list(jsonrpc = "2.0", id = id, method = method, params = params)) + deadline <- Sys.time() + 5 + repeat { + later::run_now(0.05) + messages <- read_messages() + expect_false(any(vapply( + messages, + function(message) identical(message$method, "jdv/address"), + logical(1L) + ))) + reply <- Filter(function(message) identical(message$id, id), messages) + if (length(reply) || Sys.time() >= deadline) { + break + } + } + expect_identical(length(reply), 1L) + expect_true(isTRUE(reply[[1L]]$result)) + expect_false(used_sess_viewer(messages)) + } + # The first workspace view uses the address from attach. + workspace_name <- basename(tempfile("jdv_workspace_")) + assign(workspace_name, sample, envir = .GlobalEnv) + on.exit(rm(list = workspace_name, envir = .GlobalEnv), add = TRUE) + expect_identical(jdv::jdv_connection()$state, "disconnected") + request_view("workspace_view", list(name = workspace_name)) + host_messages(2L) + expect_identical(opens()[[1L]]$params$title, workspace_name) + + # Navigating a legacy list to its table uses the same attach address. + options(sess.dataviewer = "sess") + legacy_list <- list(df = sample) + utils::View(legacy_list) + options(sess.dataviewer = NULL) + legacy_view <- Filter(function(message) identical(message$method, "dataview"), read_messages()) + request_view( + "listview_navigate", + list(view_id = legacy_view[[1L]]$params$view_id, path = list(1L)) + ) + host_messages(3L) + expect_identical(opens()[[2L]]$params$kind, "grid") + utils::View(sample) expect_false(used_sess_viewer()) - messages <- host_messages(2L) + messages <- host_messages(4L) expect_identical(messages[[1L]]$method, "hello") expect_identical(messages[[1L]]$params$producer$name, "jdv") expect_identical(runtime$jdv_address, address) @@ -291,7 +312,7 @@ local({ lockBinding("notify_client", ns) # Data frames are paged and titled by their expression. - open <- opens()[[1L]]$params + open <- opens()[[3L]]$params expect_identical(open$kind, "grid") expect_identical(open$access, "random") expect_identical(open$encoding, "jdv-json") @@ -301,16 +322,16 @@ local({ # The same title replaces the view and increments its generation. utils::View(sample) - host_messages(3L) - reopened <- opens()[[2L]]$params + host_messages(5L) + reopened <- opens()[[4L]]$params expect_identical(reopened$view, open$view) expect_identical(reopened$generation, 2L) # Lists open as trees on the same connection. nested <- list(a = 1:3, df = sample) utils::View(nested) - host_messages(4L) - tree <- opens()[[3L]]$params + host_messages(6L) + tree <- opens()[[5L]]$params expect_identical(tree$kind, "tree") expect_identical(tree$title, "nested") expect_false(used_sess_viewer()) @@ -318,8 +339,8 @@ local({ # Arrow data is a forward-only stream on the same connection. if (requireNamespace("nanoarrow", quietly = TRUE)) { utils::View(nanoarrow::as_nanoarrow_array_stream(sample), "stream") - host_messages(5L) - stream <- opens()[[4L]]$params + host_messages(7L) + stream <- opens()[[6L]]$params expect_identical(stream$access, "sequential") expect_identical(stream$title, "stream") stream_notifications <- read_messages() @@ -414,6 +435,16 @@ local({ # Explicit View() in Interactive opens the regular jdv panel before trying # the inline rich-output path used by ordinary cell results. + unlockBinding("request_client", ns) + assign( + "request_client", + function(action, args = list()) { + expect_identical(action, "jdv/address") + list(address = address) + }, + envir = ns + ) + lockBinding("request_client", ns) runtime$interactive_connected <- TRUE utils::View(sample, "interactive explicit") runtime$interactive_connected <- FALSE @@ -423,19 +454,10 @@ local({ "interactive explicit" ) - # While sess answers a socket request, a session that only this client - # controls keeps its connection. An Interactive session falls back to the sess - # viewer instead: another client may have taken control, and the reply that - # names its viewer host could not be read. + # An Interactive session answering a request cannot ask for its controller's address. unlockBinding("request_client", ns) assign("request_client", original_request_client, envir = ns) lockBinding("request_client", ns) - read_messages() - opened_before <- length(opens()) - lines_before <- length(host_messages(0L)) - expect_false(used_sess_viewer(view_from_workspace())) - host_messages(lines_before + 1L) - expect_identical(length(opens()), opened_before + 1L) local({ # Interactive notifications do not use this pipe, so the decision is checked. on.exit({ @@ -447,10 +469,13 @@ local({ expect_false(sess:::.jdv_connect()) }) expect_identical(jdv::jdv_connection()$address, address) - stub_address(address) - - # Releasing the runtime closes the connection that sess opened. - sess:::.jdv_release() + configured <- runtime$attach_jdv + runtime$attach_jdv <- list(unavailable = list(code = "listener_failed", message = "No listener")) + expect_false(sess:::.jdv_connect()) + runtime$attach_jdv <- configured + # Disconnecting clears the attach address and releases the owned jdv connection. + sess:::.transport_disconnect(silent = TRUE) + expect_null(runtime$attach_jdv) expect_identical(jdv::jdv_connection()$state, "disconnected") expect_null(runtime$jdv_address) }) diff --git a/sess/inst/tinytest/test-native-plot.R b/sess/inst/tinytest/test-native-plot.R index 53c9498b2..b61384cfa 100644 --- a/sess/inst/tinytest/test-native-plot.R +++ b/sess/inst/tinytest/test-native-plot.R @@ -158,10 +158,16 @@ local({ env$connect <- sess::connect environment(env$connect) <- env env$poll_connection <- function(...) { + NULL + } + env$.await_attach <- function(con, id, ...) { processx::poll(list(server), 1000L) processx::conn_accept_unix_socket(server) processx::poll(list(server), 1000L) - expect_equal(jsonlite::fromJSON(processx::conn_read_chars(server))$method, "attach") + request <- jsonlite::fromJSON(processx::conn_read_chars(server)) + expect_identical(request$method, "attach") + expect_identical(request$id, id) + list(status = "accepted", lines = character(), tail = "") } env$connect(endpoint = endpoint, use_rstudioapi = FALSE, plot_backend = "native") expect_true(isTRUE(sess:::.runtime_state()$active)) diff --git a/sess/inst/tinytest/test-reconnect.R b/sess/inst/tinytest/test-reconnect.R index 8c7327874..a1118c7af 100644 --- a/sess/inst/tinytest/test-reconnect.R +++ b/sess/inst/tinytest/test-reconnect.R @@ -283,10 +283,10 @@ local({ registration$pid <- Sys.getpid() registration$endpoint <- socket options(vscodeR.terminalStartup = registration) - env$.transport_disconnect <- sess:::.transport_disconnect - environment(env$.transport_disconnect) <- env - env$notify_client <- function(...) { - env$.transport_disconnect(silent = TRUE, reconnect = TRUE) + env$ipc_write <- function(data, disconnect_on_error = TRUE) { + expect_identical(data$method, "attach") + expect_false(disconnect_on_error) + FALSE } server <- processx::conn_create_unix_socket(socket, encoding = "") on.exit(try(close(server), silent = TRUE), add = TRUE) diff --git a/sess/inst/tinytest/test-session-contract.R b/sess/inst/tinytest/test-session-contract.R index 116994f7f..c102e8d74 100644 --- a/sess/inst/tinytest/test-session-contract.R +++ b/sess/inst/tinytest/test-session-contract.R @@ -16,7 +16,7 @@ local({ first <- sess:::.session_attach_metadata() second <- sess:::.session_attach_metadata() - expect_equal(first$protocol_version, 2L) + expect_equal(first$protocol_version, 3L) expect_true(is.character(first$session_id) && nzchar(first$session_id)) expect_equal(first$session_id, second$session_id) expect_false(identical(first$session_id, as.character(first$pid))) diff --git a/src/interactive/backends/sessBridge.ts b/src/interactive/backends/sessBridge.ts index 8f8d02184..e4eee5510 100644 --- a/src/interactive/backends/sessBridge.ts +++ b/src/interactive/backends/sessBridge.ts @@ -1,3 +1,9 @@ +import { + SESS_PROTOCOL_VERSION, + acknowledgeSessAttach, + isSessRequestId, + rejectSessAttach, +} from '../../sessProtocol'; import * as net from 'net'; import { randomUUID } from 'crypto'; import { localEndpoint, listenLocal } from '../transport'; @@ -80,31 +86,67 @@ export class SessBridge { }); } private connectSess(socket: net.Socket): void { - let attached = false; + let sessionId: string | undefined; this.parse(socket, (message) => { if (message.method === 'attach') { - const params = object(message.params); + if (!socket.writable) { + return; + } + const id = message.id; + const reject = (reason: string) => + socket.end(rejectSessAttach(id, reason), () => socket.destroy()); + if (message.jsonrpc !== '2.0' || !isSessRequestId(id)) { + reject('Expected a JSON-RPC 2.0 attach request with an id.'); + return; + } if ( - params.protocol_version !== 2 || - params.interactive_token !== this.token || - (this.sess && this.sess !== socket) + !message.params || + typeof message.params !== 'object' || + Array.isArray(message.params) ) { + reject('Expected an attach metadata object.'); + return; + } + const params = object(message.params); + if (params.protocol_version !== SESS_PROTOCOL_VERSION) { + reject(`Unsupported sess protocol version; expected ${SESS_PROTOCOL_VERSION}.`); + return; + } + if (params.interactive_token !== this.token) { + reject('Invalid Interactive session token.'); + return; + } + const requestedSession = + typeof params.session_id === 'string' ? params.session_id.trim() : ''; + if (!requestedSession) { + reject('Missing or invalid session_id.'); + return; + } + if (sessionId && sessionId !== requestedSession) { + reject('This connection is already attached to another session.'); + return; + } + if (this.sess && this.sess !== socket) { socket.destroy(); return; } + socket.write(acknowledgeSessAttach(id)); + if (sessionId) { + return; + } this.sess = socket; - attached = true; + sessionId = requestedSession; this.emit({ type: 'metadata', metadata: { rPid: Number(params.pid), rVersion: String(params.version), - runtimeSessionId: String(params.session_id), + runtimeSessionId: sessionId, }, }); return; } - if (!attached || this.sess !== socket) { + if (!sessionId || this.sess !== socket || !socket.writable) { return; } if (typeof message.id === 'number' && !message.method) { diff --git a/src/jdvTransport.ts b/src/jdvTransport.ts index bd8a34296..0a5a26b00 100644 --- a/src/jdvTransport.ts +++ b/src/jdvTransport.ts @@ -492,10 +492,18 @@ export class JdvHost { resolve(); }); }); - if (process.platform !== 'win32') { - fs.chmodSync(socketPath, 0o600); + try { + if (process.platform !== 'win32') { + fs.chmodSync(socketPath, 0o600); + } + return new JdvHost(server, address, socketPath, events); + } catch (error) { + server.close(); + if (process.platform !== 'win32') { + fs.rmSync(socketPath, { force: true }); + } + throw error; } - return new JdvHost(server, address, socketPath, events); } get connection(): JdvPeer | undefined { diff --git a/src/sessProtocol.ts b/src/sessProtocol.ts new file mode 100644 index 000000000..43362572c --- /dev/null +++ b/src/sessProtocol.ts @@ -0,0 +1,24 @@ +export const SESS_PROTOCOL_VERSION = 3; + +export function isSessRequestId(id: unknown): id is string | number { + return typeof id === 'string' || (typeof id === 'number' && Number.isFinite(id)); +} + +export type SessAttachJdv = + | { address: string } + | { unavailable: { code: 'listener_failed'; message: string } } + | null; + +export function acknowledgeSessAttach(id: string | number, jdv: SessAttachJdv = null): string { + return JSON.stringify({ jsonrpc: '2.0', id, result: { jdv } }) + '\n'; +} + +export function rejectSessAttach(id: unknown, message: string): string { + return ( + JSON.stringify({ + jsonrpc: '2.0', + id: isSessRequestId(id) ? id : null, + error: { code: -32602, message }, + }) + '\n' + ); +} diff --git a/src/session.ts b/src/session.ts index fe8e1e18d..cef17e760 100644 --- a/src/session.ts +++ b/src/session.ts @@ -1,5 +1,12 @@ 'use strict'; +import { + SESS_PROTOCOL_VERSION, + type SessAttachJdv, + acknowledgeSessAttach, + isSessRequestId, + rejectSessAttach, +} from './sessProtocol'; import * as fs from 'node:fs'; import * as fsp from 'node:fs/promises'; import { pathExists, readJson } from './fileSystem'; @@ -179,8 +186,6 @@ let info: SessionInfo; export let globalPipePath: string | undefined; export let workspaceFile: string; -const SESS_PROTOCOL_VERSION = 2; - const sessions = new Map(); const sessionConnectionEmitter = new vscode.EventEmitter(); export const onDidChangeSessionConnection = sessionConnectionEmitter.event; @@ -227,6 +232,9 @@ function enqueueSessionConnectionChanges(changes: readonly RSessionConnectionCha function invalidateSessionConnection(target: Session): RSessionConnectionChange | undefined { const reference = createSessionReference(target); + if (target.connectionId) { + disposeJdvHost(nativeJdvHostKey(target.connectionId)); + } target.connectionId = undefined; target.attachmentId = undefined; return reference ? Object.freeze({ kind: 'disconnected', session: reference }) : undefined; @@ -247,12 +255,41 @@ export function getSessionReference(sessionId: string): RSessionReference | unde } const sessionProcessMonitor = new SessionProcessMonitor(isLocalHost); -// Only the newest handshake for a stable ID may commit after terminal discovery. +// Only the newest handshake for a stable session ID can publish. interface PendingSessionAttachment { readonly socket: IpcSocket; readonly controller: AbortController; + releaseHost?: () => void; + // A published connection whose terminal lookup must continue until this + // attempt replaces it. + supersedes?: PendingSessionAttachment; + // Set once the terminal lookup has finished. + settled?: boolean; } +const nativeJdvAttachments = new WeakMap(); const pendingSessionAttachments = new Map(); +function nativeJdvHostKey(connectionId: string): string { + return `native:${connectionId}`; +} + +function cancelSessionAttachment(pending: PendingSessionAttachment): void { + pending.releaseHost?.(); + pending.releaseHost = undefined; + pending.controller.abort(); +} + +// Cancel an attempt that never committed. The published connection it would +// have replaced becomes the pending attachment for its session again. +function withdrawSessionAttachment(sessionId: string, pending: PendingSessionAttachment): void { + pendingSessionAttachments.delete(sessionId); + cancelSessionAttachment(pending); + const published = pending.supersedes; + pending.supersedes = undefined; + if (published && !published.settled && !published.controller.signal.aborted) { + pendingSessionAttachments.set(sessionId, published); + } +} + const terminalRegistry = new TerminalSessionRegistry( (target) => sessions.get(target.sessionId) === target && isConnectedSession(target), (terminal) => !terminal.exitStatus && window.terminals.includes(terminal), @@ -1481,7 +1518,6 @@ function startGlobalSessionServer(generation: number): Promise { const rpc = new NativeRpcConnection(socket); nativeRpcConnections.set(socket, rpc); - let attachment: Promise | undefined; const handleLine = (buf: Buffer) => { let lineEnd = buf.length; @@ -1496,23 +1532,11 @@ function startGlobalSessionServer(generation: number): Promise { void (async () => { try { const message = JSON.parse(line) as Record; - if ( - message.method === 'attach' && - (message.id === undefined || message.id === null) - ) { - attachment = handleNotification(message, socket); - await attachment; + if (message.method === 'attach') { + await handleAttach(message, socket); return; } - // R announces retained devices immediately after attach. - // An accepted attach binds the socket before its terminal - // lookup, so those notifications do not wait for it. Once - // the socket is bound, RPC responses must remain independent - // of any UI work still completing in the attach handler. - if (!socket._sessionId && attachment) { - await attachment; - } - if (message.method !== 'attach' && !isCurrentSocket(socket)) { + if (!isCurrentSocket(socket)) { return; } if (message.id !== undefined && !message.method) { @@ -1546,8 +1570,7 @@ function startGlobalSessionServer(generation: number): Promise { activeConnections.delete(socket); for (const [id, pending] of pendingSessionAttachments) { if (pending.socket === socket) { - pendingSessionAttachments.delete(id); - pending.controller.abort(); + withdrawSessionAttachment(id, pending); } } if (pipeClient === socket) { @@ -2138,7 +2161,7 @@ export async function shutdownSessionWatcher(): Promise { for (const [sessionId, pending] of pendingSessionAttachments) { if (pending.socket._server === serverAtShutdown) { pendingSessionAttachments.delete(sessionId); - pending.controller.abort(); + cancelSessionAttachment(pending); } } // Queue removal of the fixed manual-attach path before a redeployed lifecycle @@ -2198,7 +2221,7 @@ export async function shutdownSessionWatcher(): Promise { for (const [sessionId, pending] of pendingSessionAttachments) { if (pending.socket === socket) { pendingSessionAttachments.delete(sessionId); - pending.controller.abort(); + cancelSessionAttachment(pending); } } } @@ -3986,277 +4009,349 @@ function sendToSocket(socket: IpcSocket, data: Record): void { } } -async function handleNotification(message: Record, socket: IpcSocket) { - if (typeof message.method !== 'string') { - return; - } - const method = message.method; - const params = (message.params as Record) || {}; +const NATIVE_JDV_LISTENER_TIMEOUT = 3000; - switch (method) { - case 'attach': { - if (!isLiveSessionSocket(socket)) { - socket.destroy(); - return; - } - const protocolVersion = params.protocol_version; - const sessionId = typeof params.session_id === 'string' ? params.session_id.trim() : ''; - const host = typeof params.host === 'string' ? params.host : ''; - const attachmentId = - params.attachment_id === undefined || params.attachment_id === null - ? undefined - : params.attachment_id; - const autoActivateValue = params.auto_activate; - if ( - attachmentId !== undefined && - (typeof attachmentId !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(attachmentId)) - ) { - void window.showErrorMessage( - 'Cannot attach R session: invalid attachment_id metadata; expected 1–128 ASCII letters, digits, underscores, or hyphens.', - ); - socket.destroy(); - return; - } - if (autoActivateValue !== undefined && typeof autoActivateValue !== 'boolean') { - void window.showErrorMessage( - 'Cannot attach R session: invalid auto_activate metadata; expected a boolean.', - ); - socket.destroy(); - return; - } - if (autoActivateValue === false && attachmentId === undefined) { - void window.showErrorMessage( - 'Cannot attach R session: auto_activate=false requires a valid attachment_id. Update the external console and try again.', - ); - socket.destroy(); - return; - } - const autoActivate = autoActivateValue !== false; - if (protocolVersion !== SESS_PROTOCOL_VERSION) { - const found = - protocolVersion === undefined ? 'missing' : JSON.stringify(protocolVersion); - void window.showErrorMessage( - `Cannot attach R session: unsupported sess protocol version ${found}; this extension requires protocol version ${SESS_PROTOCOL_VERSION}.`, - ); - socket.destroy(); - return; - } - if (!sessionId) { - void window.showErrorMessage( - 'Cannot attach R session: the sess attach handshake has no session_id. Update the sess package and try again.', - ); - socket.destroy(); - return; - } - if ( - typeof params.tempdir !== 'string' || - !params.tempdir || - typeof params.wd !== 'string' || - !params.wd - ) { - void window.showErrorMessage( - 'Cannot attach R session: the sess attach handshake has missing or invalid session paths. Update the sess package and try again.', - ); - socket.destroy(); - return; - } +async function prepareNativeJdv( + sessionId: string, + hostKey: string, + pending: PendingSessionAttachment, +): Promise { + let timer: NodeJS.Timeout | undefined; + try { + const address = await withRpcCancellation( + () => + Promise.race([ + getJdvAddress(sessionId, hostKey), + new Promise((_resolve, reject) => { + timer = setTimeout( + () => reject(new Error('Timed out starting the jdv listener.')), + NATIVE_JDV_LISTENER_TIMEOUT, + ); + }), + ]), + pending.controller.signal, + ); + return { address }; + } catch (error) { + pending.releaseHost?.(); + pending.releaseHost = undefined; + return { + unavailable: { + code: 'listener_failed', + message: error instanceof Error && error.message ? error.message : String(error), + }, + }; + } finally { + clearTimeout(timer); + } +} - const boundSessionId = socket._sessionId; - if (boundSessionId) { - if (boundSessionId !== sessionId) { - void window.showErrorMessage( - `Cannot attach R session ${sessionId}: this IPC connection is already bound to session ${boundSessionId}. Reconnect using a new IPC connection.`, - ); - socket.destroy(); - } - // An attach notification is only accepted once per socket. Treat a - // repeated handshake for the same session as an idempotent no-op. - return; - } +async function handleAttach(message: Record, socket: IpcSocket) { + if (!isLiveSessionSocket(socket)) { + socket.destroy(); + return; + } + const reject = (reason: string) => { + socket.end(rejectSessAttach(message.id, reason), () => socket.destroy()); + void window.showErrorMessage(reason); + }; + const id = message.id; + if (message.jsonrpc !== '2.0' || !isSessRequestId(id)) { + reject('Cannot attach R session: expected a JSON-RPC 2.0 request with an id.'); + return; + } + if (!message.params || typeof message.params !== 'object' || Array.isArray(message.params)) { + reject('Cannot attach R session: expected an attach metadata object.'); + return; + } + const params = message.params as Record; + const protocolVersion = params.protocol_version; + const sessionId = typeof params.session_id === 'string' ? params.session_id.trim() : ''; + const host = typeof params.host === 'string' ? params.host : ''; + const attachmentId = + params.attachment_id === undefined || params.attachment_id === null + ? undefined + : params.attachment_id; + const autoActivateValue = params.auto_activate; + if ( + attachmentId !== undefined && + (typeof attachmentId !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(attachmentId)) + ) { + reject( + 'Cannot attach R session: invalid attachment_id metadata; expected 1–128 ASCII letters, digits, underscores, or hyphens.', + ); + return; + } + if (autoActivateValue !== undefined && typeof autoActivateValue !== 'boolean') { + reject('Cannot attach R session: invalid auto_activate metadata; expected a boolean.'); + return; + } + if (autoActivateValue === false && attachmentId === undefined) { + reject( + 'Cannot attach R session: auto_activate=false requires a valid attachment_id. Update the external console and try again.', + ); + return; + } + const autoActivate = autoActivateValue !== false; + if (protocolVersion !== SESS_PROTOCOL_VERSION) { + const found = protocolVersion === undefined ? 'missing' : JSON.stringify(protocolVersion); + reject( + `Cannot attach R session: unsupported sess protocol version ${found}; this extension requires protocol version ${SESS_PROTOCOL_VERSION}.`, + ); + return; + } + if (!sessionId) { + reject( + 'Cannot attach R session: the sess attach handshake has no session_id. Update the sess package and try again.', + ); + return; + } + if ( + typeof params.tempdir !== 'string' || + !params.tempdir || + typeof params.wd !== 'string' || + !params.wd + ) { + reject( + 'Cannot attach R session: the sess attach handshake has missing or invalid session paths. Update the sess package and try again.', + ); + return; + } - const rPid = - typeof params.pid === 'string' || typeof params.pid === 'number' - ? String(params.pid) - : ''; - pendingSessionAttachments.get(sessionId)?.controller.abort(); - const pendingAttachment: PendingSessionAttachment = { - socket, - controller: new AbortController(), - }; - pendingSessionAttachments.set(sessionId, pendingAttachment); - const selectionRevision = sessionSelectionRevision; - const selectedTerminal = window.activeTerminal; - - // Register the connection before any await. Finding its terminal can - // take seconds (a process-table query on Windows), and the session - // must be usable while that runs; the terminal is associated after. - const previous = sessions.get(sessionId); - // A reconnect from the same local R process keeps its native terminal, - // so selecting that terminal still selects the session meanwhile. - const inherited = - previous && - rPid && - previous.pid === rPid && - isLocalHost(host) && - previous.host === (host || 'unknown') - ? terminalRegistry.forSession(previous) - : undefined; - const inheritedTerminalPid = previous?.socket._terminalPid; - if (previous) { - terminalRegistry.releaseSession(previous); - } - const session = new Session( - sessionId, - host || 'unknown', - typeof params.sess_version === 'string' ? params.sess_version : 'unknown', - socket._pipePath ?? globalPipePath ?? '', - socket, + const boundSessionId = socket._sessionId; + if (boundSessionId) { + if (boundSessionId !== sessionId) { + reject( + `Cannot attach R session ${sessionId}: this IPC connection is already bound to session ${boundSessionId}. Reconnect using a new IPC connection.`, ); - session.connectionId = crypto.randomBytes(16).toString('hex'); - session.attachmentId = attachmentId; - session.rVer = String(params.version); - session.pid = rPid; - session.info = (params.info as SessionInfo | undefined) ?? { - version: session.rVer, - command: '', - start_time: '', - }; - session.sessionDir = params.tempdir; - session.workingDir = params.wd; - let lookupDone!: () => void; - socket._terminalLookup = new Promise((resolve) => { - lookupDone = resolve; - }); - socket._sessionId = sessionId; - sessions.set(sessionId, session); - const changes: RSessionConnectionChange[] = []; - const disconnected = previous ? invalidateSessionConnection(previous) : undefined; - if (disconnected) { - changes.push(disconnected); - } - if (previous && previous.socket !== socket) { - previous.socket.destroy(); - } - // Only an attach that would look up its terminal inherits it, and - // only while the terminal is still eligible: one that gained a - // terminal integration since must go through that integration. - // The lookup below confirms or releases this provisional binding. - const provisional = - autoActivate && - inherited?.kind === 'native' && - isNativeTerminalEligible(inherited.terminal) && - terminalRegistry.attachNative(inherited.terminal, session) - ? terminalRegistry.forSession(session) - : undefined; - if (provisional && inheritedTerminalPid) { - socket._terminalPid = inheritedTerminalPid; - } - // Replacing the selected connection keeps the user's logical choice. - const replacesSelection = previous !== undefined && activeSession === previous; - let activation: Promise = replacesSelection - ? activateSession(session) - : Promise.resolve(); - // The lookup below can take seconds; observe a rejection now and - // still surface it when the activation is awaited. - activation.catch(() => undefined); - const isCurrentAttachment = () => - sessions.get(sessionId) === session && - session.socket === socket && - socket._sessionId === sessionId && - isLiveSessionSocket(socket) && - !pendingAttachment.controller.signal.aborted; - // Start the lookup before notifying listeners, so its ownership snapshot - // detects a terminal a listener binds explicitly. - let lookupFailed = false; - const discovery = - autoActivate && rPid && isLocalHost(host) - ? findLocalTerminal(rPid, pendingAttachment.controller.signal).catch( - (error: unknown) => { - lookupFailed = true; - console.error( - `[startSessionWatcher] terminal lookup for session ${sessionId} failed`, - error, - ); - return undefined; - }, - ) - : Promise.resolve(undefined); - const connected = createSessionReference(session); - if (connected) { - changes.push(Object.freeze({ kind: 'connected', session: connected })); - } - enqueueSessionConnectionChanges(changes); - purgeAddinPickerItems(); + } else { + socket.write(acknowledgeSessAttach(id, nativeJdvAttachments.get(socket))); + } + return; + } - let candidate: NativeTerminalCandidate | undefined; - try { - candidate = await discovery; - } finally { - if (pendingSessionAttachments.get(sessionId) === pendingAttachment) { - pendingSessionAttachments.delete(sessionId); - } - } - if (!isCurrentAttachment()) { - lookupDone(); - await activation; - return; - } - const native = candidate?.isCurrent() ? candidate : undefined; - if (native && terminalRegistry.attachNative(native.terminal, session)) { - socket._terminalPid = Number(native.pid); - } else if ( - provisional && - (!lookupFailed || !isNativeTerminalEligible(provisional.terminal)) && - terminalRegistry.forSession(session) === provisional - ) { - // The lookup ruled out the inherited terminal, for example - // because a connected R process is between it and this one, or - // the terminal gained an integration while the lookup failed. - // A binding made during the lookup is kept. - terminalRegistry.releaseSession(session); - socket._terminalPid = undefined; - } - const terminalPid = - terminalRegistry.forSession(session)?.kind === 'native' - ? socket._terminalPid - : undefined; - - const canUseLegacyUiEffects = - autoActivate && - selectionRevision === sessionSelectionRevision && - selectedTerminal === window.activeTerminal; - if (!replacesSelection && autoActivate) { - activation = activateAttachedSession( - session, - previous, - selectionRevision, - selectedTerminal, - ); - } - // Capture after the synchronous activation decision, so a later - // user or listener selection cancels stale effects. - const committedSelectionRevision = sessionSelectionRevision; + const rPid = + typeof params.pid === 'string' || typeof params.pid === 'number' ? String(params.pid) : ''; + if ([...pendingSessionAttachments.values()].some((pending) => pending.socket === socket)) { + return; + } + const superseded = pendingSessionAttachments.get(sessionId); + let supersedes: PendingSessionAttachment | undefined; + if (superseded?.socket._sessionId) { + // The published connection stays live until this attempt commits. + supersedes = superseded; + } else if (superseded) { + supersedes = superseded.supersedes; + cancelSessionAttachment(superseded); + superseded.socket.destroy(); + } + const connectionId = crypto.randomBytes(16).toString('hex'); + const hostKey = nativeJdvHostKey(connectionId); + const pendingAttachment: PendingSessionAttachment = { + socket, + controller: new AbortController(), + releaseHost: () => disposeJdvHost(hostKey), + supersedes, + }; + pendingSessionAttachments.set(sessionId, pendingAttachment); + const selectionRevision = sessionSelectionRevision; + const selectedTerminal = window.activeTerminal; - console.info( - `[startSessionWatcher] attach session ${sessionId} (${host || 'unknown'}:${rPid || 'unknown'}), terminal PID: ${terminalPid ?? 'unassociated'}`, - ); - lookupDone(); - await activation; - const mayApplyUiEffects = () => - activeSession === session || - (canUseLegacyUiEffects && sessionSelectionRevision === committedSelectionRevision); - if (!isLiveSessionSocket(socket) || !isCurrentSocket(socket) || !mayApplyUiEffects()) { - return; - } - if (typeof params.plot_url === 'string' && params.plot_url) { - await globalPlotManager?.showHttpgdPlot(params.plot_url, session); - } - if (isLiveSessionSocket(socket) && isCurrentSocket(socket) && mayApplyUiEffects()) { - scheduleWorkspaceRefresh(0); - } - break; + const jdv = await prepareNativeJdv(sessionId, hostKey, pendingAttachment); + if ( + pendingSessionAttachments.get(sessionId) !== pendingAttachment || + !isLiveSessionSocket(socket) || + pendingAttachment.controller.signal.aborted + ) { + if (pendingSessionAttachments.get(sessionId) === pendingAttachment) { + withdrawSessionAttachment(sessionId, pendingAttachment); + } else { + cancelSessionAttachment(pendingAttachment); } + socket.destroy(); + return; + } + + const previous = sessions.get(sessionId); + // A reconnect from the same local R process keeps its native terminal, + // so selecting that terminal still selects the session meanwhile. + const inherited = + previous && + rPid && + previous.pid === rPid && + isLocalHost(host) && + previous.host === (host || 'unknown') + ? terminalRegistry.forSession(previous) + : undefined; + const inheritedTerminalPid = previous?.socket._terminalPid; + if (previous) { + terminalRegistry.releaseSession(previous); + } + const session = new Session( + sessionId, + host || 'unknown', + typeof params.sess_version === 'string' ? params.sess_version : 'unknown', + socket._pipePath ?? globalPipePath ?? '', + socket, + ); + session.connectionId = connectionId; + session.attachmentId = attachmentId; + session.rVer = String(params.version); + session.pid = rPid; + session.info = (params.info as SessionInfo | undefined) ?? { + version: session.rVer, + command: '', + start_time: '', + }; + session.sessionDir = params.tempdir; + session.workingDir = params.wd; + let lookupDone!: () => void; + socket._terminalLookup = new Promise((resolve) => { + lookupDone = resolve; + }); + socket.write(acknowledgeSessAttach(id, jdv)); + nativeJdvAttachments.set(socket, jdv); + pendingAttachment.releaseHost = undefined; + if (pendingAttachment.supersedes) { + cancelSessionAttachment(pendingAttachment.supersedes); + pendingAttachment.supersedes = undefined; + } + socket._sessionId = sessionId; + sessions.set(sessionId, session); + const changes: RSessionConnectionChange[] = []; + const disconnected = previous ? invalidateSessionConnection(previous) : undefined; + if (disconnected) { + changes.push(disconnected); + } + if (previous && previous.socket !== socket) { + previous.socket.destroy(); + } + // Only an attach that would look up its terminal inherits it, and + // only while the terminal is still eligible: one that gained a + // terminal integration since must go through that integration. + // The lookup below confirms or releases this provisional binding. + const provisional = + autoActivate && + inherited?.kind === 'native' && + isNativeTerminalEligible(inherited.terminal) && + terminalRegistry.attachNative(inherited.terminal, session) + ? terminalRegistry.forSession(session) + : undefined; + if (provisional && inheritedTerminalPid) { + socket._terminalPid = inheritedTerminalPid; + } + // Replacing the selected connection keeps the user's logical choice. + const replacesSelection = previous !== undefined && activeSession === previous; + let activation: Promise = replacesSelection + ? activateSession(session) + : Promise.resolve(); + // The lookup below can take seconds; observe a rejection now and + // still surface it when the activation is awaited. + activation.catch(() => undefined); + const isCurrentAttachment = () => + sessions.get(sessionId) === session && + session.socket === socket && + socket._sessionId === sessionId && + isLiveSessionSocket(socket) && + !pendingAttachment.controller.signal.aborted; + // Start the lookup before notifying listeners, so its ownership snapshot + // detects a terminal a listener binds explicitly. + let lookupFailed = false; + const discovery = + autoActivate && rPid && isLocalHost(host) + ? findLocalTerminal(rPid, pendingAttachment.controller.signal).catch( + (error: unknown) => { + lookupFailed = true; + console.error( + `[startSessionWatcher] terminal lookup for session ${sessionId} failed`, + error, + ); + return undefined; + }, + ) + : Promise.resolve(undefined); + const connected = createSessionReference(session); + if (connected) { + changes.push(Object.freeze({ kind: 'connected', session: connected })); + } + enqueueSessionConnectionChanges(changes); + purgeAddinPickerItems(); + + let candidate: NativeTerminalCandidate | undefined; + try { + candidate = await discovery; + } finally { + pendingAttachment.settled = true; + if (pendingSessionAttachments.get(sessionId) === pendingAttachment) { + pendingSessionAttachments.delete(sessionId); + } + } + if (!isCurrentAttachment()) { + lookupDone(); + await activation; + return; + } + const native = candidate?.isCurrent() ? candidate : undefined; + if (native && terminalRegistry.attachNative(native.terminal, session)) { + socket._terminalPid = Number(native.pid); + } else if ( + provisional && + (!lookupFailed || !isNativeTerminalEligible(provisional.terminal)) && + terminalRegistry.forSession(session) === provisional + ) { + // The lookup ruled out the inherited terminal, for example + // because a connected R process is between it and this one, or + // the terminal gained an integration while the lookup failed. + // A binding made during the lookup is kept. + terminalRegistry.releaseSession(session); + socket._terminalPid = undefined; + } + const terminalPid = + terminalRegistry.forSession(session)?.kind === 'native' ? socket._terminalPid : undefined; + + const canUseLegacyUiEffects = + autoActivate && + selectionRevision === sessionSelectionRevision && + selectedTerminal === window.activeTerminal; + if (!replacesSelection && autoActivate) { + activation = activateAttachedSession( + session, + previous, + selectionRevision, + selectedTerminal, + ); + } + // Capture after the synchronous activation decision, so a later + // user or listener selection cancels stale effects. + const committedSelectionRevision = sessionSelectionRevision; + console.info( + `[startSessionWatcher] attach session ${sessionId} (${host || 'unknown'}:${rPid || 'unknown'}), terminal PID: ${terminalPid ?? 'unassociated'}`, + ); + lookupDone(); + await activation; + const mayApplyUiEffects = () => + activeSession === session || + (canUseLegacyUiEffects && sessionSelectionRevision === committedSelectionRevision); + if (!isLiveSessionSocket(socket) || !isCurrentSocket(socket) || !mayApplyUiEffects()) { + return; + } + if (typeof params.plot_url === 'string' && params.plot_url) { + await globalPlotManager?.showHttpgdPlot(params.plot_url, session); + } + if (isLiveSessionSocket(socket) && isCurrentSocket(socket) && mayApplyUiEffects()) { + scheduleWorkspaceRefresh(0); + } +} + +async function handleNotification(message: Record, socket: IpcSocket) { + if (typeof message.method !== 'string') { + return; + } + const method = message.method; + const params = (message.params as Record) || {}; + + switch (method) { case 'workspace_updated': { const target = socket._sessionId && sessions.get(socket._sessionId); if (target && target.socket === socket) { @@ -4434,15 +4529,6 @@ async function handleRequest(message: Record, socket?: IpcSocke try { switch (method) { - case 'jdv/address': { - // The per-session jdv transport; sess connects jdv to it when View() is used. - const owner = sessions.get(socket?._sessionId ?? ''); - if (!owner) { - throw new Error('The jdv transport requires an attached session'); - } - result = { address: await getJdvAddress(owner.sessionId) }; - break; - } case 'rstudioapi/active_editor_context': result = rstudioapi.activeEditorContext(); break; @@ -4547,7 +4633,6 @@ export async function cleanupSession(sessionId: string, closingSocket?: IpcSocke } workspaceRefreshes.get(session)?.dispose(); sessions.delete(sessionId); - disposeJdvHost(sessionId); terminalRegistry.releaseSession(session); const disconnected = invalidateSessionConnection(session); if (pipeClient === session.socket) { diff --git a/src/test/common/sessAttachFixture.ts b/src/test/common/sessAttachFixture.ts new file mode 100644 index 000000000..9757a16a9 --- /dev/null +++ b/src/test/common/sessAttachFixture.ts @@ -0,0 +1,18 @@ +import * as assert from 'assert'; +import type { Socket } from 'net'; +import { SESS_PROTOCOL_VERSION, acknowledgeSessAttach, isSessRequestId } from '../../sessProtocol'; + +export function acknowledgeFixtureAttach( + socket: Socket, + message: { method?: unknown; id?: unknown; params?: unknown }, +): void { + if (message.method !== 'attach') { + return; + } + assert.strictEqual( + (message.params as { protocol_version?: unknown }).protocol_version, + SESS_PROTOCOL_VERSION, + ); + assert.ok(isSessRequestId(message.id)); + socket.write(acknowledgeSessAttach(message.id)); +} diff --git a/src/test/common/sessionConnections.ts b/src/test/common/sessionConnections.ts index 4f6f0a18c..5e0e8a265 100644 --- a/src/test/common/sessionConnections.ts +++ b/src/test/common/sessionConnections.ts @@ -2,6 +2,7 @@ import * as assert from 'assert'; import * as net from 'net'; import * as os from 'os'; import * as session from '../../session'; +import { SESS_PROTOCOL_VERSION, type SessAttachJdv } from '../../sessProtocol'; export function deferred() { let resolve!: (value: T) => void; @@ -29,6 +30,84 @@ export interface SessionAttachMetadata { plotUrl?: string; } +export function sessAttachRequest(params: Record): string { + return ( + JSON.stringify({ + jsonrpc: '2.0', + id: 'attach-test', + method: 'attach', + params: { protocol_version: SESS_PROTOCOL_VERSION, ...params }, + }) + '\n' + ); +} + +function observeAttachReply( + socket: net.Socket, + id: string, + onMessage?: (message: Record) => void, +): Promise> { + const reply = new Promise>((resolve, reject) => { + let buffer = ''; + const cleanup = () => { + socket.off('data', onData); + socket.off('close', onClose); + }; + const onClose = () => { + cleanup(); + reject(new Error('Socket closed before acknowledging attach')); + }; + const onData = (data: Buffer) => { + buffer += data.toString(); + const lines = buffer.split('\n'); + buffer = lines.pop() ?? ''; + for (const line of lines) { + if (!line) { + continue; + } + const message = JSON.parse(line) as Record; + onMessage?.(message); + if (message.id === id && !message.method) { + if (!onMessage) { + cleanup(); + } + resolve(message); + if (!onMessage) { + return; + } + } + } + }; + socket.on('data', onData); + socket.once('close', onClose); + }); + void reply.catch(() => undefined); + return reply; +} + +function attachJdv(reply: Record | undefined): NonNullable { + assert.strictEqual(reply?.jsonrpc, '2.0'); + const result = reply?.result as { jdv?: SessAttachJdv } | undefined; + assert.ok(result?.jdv, 'The native attach response should describe the jdv listener'); + return result.jdv; +} + +export async function attachSessionSocket( + socket: net.Socket, + params: Record, + expectedError?: RegExp, +): Promise { + const reply = observeAttachReply(socket, 'attach-test'); + socket.write(sessAttachRequest(params)); + const message = await reply; + if (expectedError) { + const error = message.error as { code: number; message: string }; + assert.strictEqual(error.code, -32602); + assert.match(error.message, expectedError); + } else { + assert.ok('address' in attachJdv(message)); + } +} + /** Real IPC handshakes shared by terminal routing and startup regressions. */ export class SessionConnections { private readonly clients: net.Socket[] = []; @@ -36,6 +115,10 @@ export class SessionConnections { private readonly ids = new Set(); private readonly clientsById = new Map(); private readonly messagesById = new Map(); + private readonly attachReplies = new Map< + session.Session['socket'], + Promise> + >(); private requestSequence = 0; async attach( @@ -45,7 +128,7 @@ export class SessionConnections { metadata?: SessionAttachMetadata, ): Promise { const socket = await this.startAttach(id, pid, host, metadata); - await waitForValue(() => (socket._sessionId === id ? socket : undefined)); + assert.ok('address' in (await this.waitForAttach(socket))); // Also wait for terminal association and the activation decision. await socket._terminalLookup; assert.strictEqual(socket.destroyed, false); @@ -58,6 +141,7 @@ export class SessionConnections { pid: number, host = os.hostname(), metadata?: SessionAttachMetadata, + onMessage?: (message: Record) => void, ): Promise { const endpoint = await session.getGlobalPipePath(); const previous = new Set(session.activeConnections); @@ -72,32 +156,32 @@ export class SessionConnections { ); this.sockets.push(socket); this.ids.add(id); - const payload = `${JSON.stringify({ - jsonrpc: '2.0', - method: 'attach', - params: { - protocol_version: 2, - session_id: id, - host, - pid, - version: '4.4.0', - tempdir: '/tmp', - wd: '/tmp', - ...(metadata?.attachmentId !== undefined - ? { attachment_id: metadata.attachmentId } - : {}), - ...(metadata?.autoActivate !== undefined - ? { auto_activate: metadata.autoActivate } - : {}), - ...(metadata?.plotUrl !== undefined ? { plot_url: metadata.plotUrl } : {}), - }, - })}\n`; + const payload = sessAttachRequest({ + session_id: id, + host, + pid, + version: '4.4.0', + tempdir: '/tmp', + wd: '/tmp', + ...(metadata?.attachmentId !== undefined + ? { attachment_id: metadata.attachmentId } + : {}), + ...(metadata?.autoActivate !== undefined + ? { auto_activate: metadata.autoActivate } + : {}), + ...(metadata?.plotUrl !== undefined ? { plot_url: metadata.plotUrl } : {}), + }); + this.attachReplies.set(socket, observeAttachReply(client, 'attach-test', onMessage)); this.clientsById.set(id, client); this.messagesById.set(id, payload); client.write(payload); return socket; } + async waitForAttach(socket: session.Session['socket']): Promise> { + return attachJdv(await this.attachReplies.get(socket)); + } + repeatAttach(id: string): void { const client = this.clientsById.get(id); const payload = this.messagesById.get(id); diff --git a/src/test/node/interactiveLibraries.test.ts b/src/test/node/interactiveLibraries.test.ts index 3326ad53b..5d72bfc6d 100644 --- a/src/test/node/interactiveLibraries.test.ts +++ b/src/test/node/interactiveLibraries.test.ts @@ -1,3 +1,4 @@ +import { acknowledgeFixtureAttach } from '../common/sessAttachFixture'; import * as assert from 'assert'; import * as fs from 'fs'; import * as os from 'os'; @@ -70,8 +71,15 @@ suite('Interactive library isolation', function () { let received = ''; const server = net.createServer((socket) => { sockets.add(socket); + let buffer = ''; socket.on('data', (data) => { received += data.toString(); + buffer += data.toString(); + const lines = buffer.split('\n'); + buffer = lines.pop() ?? ''; + for (const line of lines) { + acknowledgeFixtureAttach(socket, JSON.parse(line) as Record); + } }); socket.on('close', () => sockets.delete(socket)); }); diff --git a/src/test/node/jdvTransport.test.ts b/src/test/node/jdvTransport.test.ts index 0a772a45d..0baf8b372 100644 --- a/src/test/node/jdvTransport.test.ts +++ b/src/test/node/jdvTransport.test.ts @@ -1,7 +1,9 @@ import * as assert from 'node:assert/strict'; import { EventEmitter } from 'node:events'; -import { Socket } from 'node:net'; -import { JdvPeer } from '../../jdvTransport'; +import { Server, Socket } from 'node:net'; +import fs = require('node:fs'); +import * as sinon from 'sinon'; +import { JdvHost, JdvPeer } from '../../jdvTransport'; import { JsonObject } from '../../jdvAdapter'; class FakeSocket extends EventEmitter { @@ -153,3 +155,33 @@ suite('jdv transport framing', () => { } }); }); + +suite('jdv listener setup', () => { + test('closes the listener and removes its socket when setting permissions fails', async function () { + if (process.platform === 'win32') { + this.skip(); + } + const sandbox = sinon.createSandbox(); + try { + const chmod = sandbox + .stub(fs, 'chmodSync') + .throws(new Error('permission setup failed')); + const close = sandbox.spy(Server.prototype, 'close'); + const ignore = () => undefined; + await assert.rejects( + JdvHost.create({ + viewOpen: ignore, + viewClosed: ignore, + viewUpdateFailed: ignore, + viewTracking: ignore, + disconnected: ignore, + }), + /permission setup failed/, + ); + sinon.assert.calledOnce(close); + assert.equal(fs.existsSync(chmod.firstCall.args[0]), false); + } finally { + sandbox.restore(); + } + }); +}); diff --git a/src/test/node/plotReconnect.test.ts b/src/test/node/plotReconnect.test.ts index c302553d4..b7d163753 100644 --- a/src/test/node/plotReconnect.test.ts +++ b/src/test/node/plotReconnect.test.ts @@ -1,3 +1,4 @@ +import { acknowledgeFixtureAttach } from '../common/sessAttachFixture'; import * as assert from 'node:assert/strict'; import * as fs from 'node:fs/promises'; import * as os from 'node:os'; @@ -110,11 +111,11 @@ suite('Live R plot reconnect', function () { buffer += data.toString(); let index: number; while ((index = buffer.indexOf('\n')) >= 0) { - notifications.push( - JSON.parse( - buffer.slice(0, index), - ) as (typeof notifications)[number], - ); + const message = JSON.parse( + buffer.slice(0, index), + ) as (typeof notifications)[number]; + acknowledgeFixtureAttach(socket, message); + notifications.push(message); buffer = buffer.slice(index + 1); } }); diff --git a/src/test/plot/sessionConnectionLifecycle.test.ts b/src/test/plot/sessionConnectionLifecycle.test.ts index 61bc3f4a8..aa7086f5e 100644 --- a/src/test/plot/sessionConnectionLifecycle.test.ts +++ b/src/test/plot/sessionConnectionLifecycle.test.ts @@ -12,6 +12,7 @@ import { pathExists } from '../../fileSystem'; import { SessConsentService } from '../../sessConsent'; import { mockExtensionContext } from '../common/mockvscode'; import { deferred, SessionConnections, waitForValue } from '../common/sessionConnections'; +import { JdvHost } from '../../jdvTransport'; import { StandardPlotViewer } from '../../plotViewer/standardViewer'; async function waitForFileRemoval(filePath: string): Promise { @@ -257,6 +258,7 @@ suite('Session Connection Lifecycle API', () => { }); test('foreground external attach selects itself and selected logical replacement follows reconnect', async () => { + const dispose = sandbox.spy(JdvHost.prototype, 'dispose'); const first = await connections.attach('external-foreground', 55005, 'external-host', { attachmentId: 'foreground-1', autoActivate: true, @@ -265,6 +267,8 @@ suite('Session Connection Lifecycle API', () => { session.getSessionReference('external-foreground'), ); assert.strictEqual(session.activeSession?.socket, first); + const firstJdv = await connections.waitForAttach(first); + assert.ok('address' in firstJdv); const replacement = await connections.attach( 'external-foreground', @@ -281,6 +285,186 @@ suite('Session Connection Lifecycle API', () => { }); assert.strictEqual(session.activeSession?.socket, replacement); assert.notStrictEqual(newReference.connectionId, oldReference.connectionId); + const replacementJdv = await connections.waitForAttach(replacement); + assert.ok('address' in replacementJdv); + assert.notStrictEqual(firstJdv.address, replacementJdv.address); + await waitForValue(() => + dispose + .getCalls() + .some(({ thisValue }) => (thisValue as JdvHost).address === firstJdv.address) + ? true + : undefined, + ); + }); + + test('writes the attach acknowledgement before publishing the session', async () => { + const id = 'attach-ack-order'; + const processId = deferred(); + const discovering = deferred(); + terminals.value([ + { + get processId() { + discovering.resolve(); + return processId.promise; + }, + }, + ]); + const frames: Record[] = []; + let reply: Promise | undefined; + const subscription = session.onDidChangeSessionConnection((change) => { + if (change.kind === 'connected' && change.session.sessionId === id) { + reply = session.sessionRequest({ method: 'plot_latest' }, id); + void reply.catch(() => undefined); + } + }); + try { + const socket = await connections.startAttach( + id, + 55159, + os.hostname(), + undefined, + (message) => frames.push(message), + ); + await discovering.promise; + const jdv = await connections.waitForAttach(socket); + assert.ok('address' in jdv); + const request = await waitForValue(() => + frames.find((frame) => frame.method === 'plot_latest'), + ); + assert.deepStrictEqual(frames[0], { + jsonrpc: '2.0', + id: 'attach-test', + result: { jdv }, + }); + socket.emit( + 'data', + Buffer.from(JSON.stringify({ id: request.id, result: 'plot' }) + '\n'), + ); + assert.strictEqual(await reply, 'plot'); + } finally { + processId.resolve(55159); + subscription.dispose(); + } + }); + + test('a superseded attach cannot publish or close the replacement listener', async () => { + const id = 'superseded-listener'; + const gate = deferred(); + const started = deferred(); + const create = JdvHost.create.bind(JdvHost); + const dispose = sandbox.spy(JdvHost.prototype, 'dispose'); + const listener = sandbox.stub(JdvHost, 'create').callThrough(); + let lateHost: JdvHost | undefined; + listener.onFirstCall().callsFake(async (events) => { + started.resolve(); + await gate.promise; + lateHost = await create(events); + return lateHost; + }); + const changes: RSessionConnectionChange[] = []; + const subscription = session.onDidChangeSessionConnection((change) => changes.push(change)); + try { + const old = await connections.startAttach(id, 55158, 'external-host'); + await started.promise; + assert.strictEqual(session.getSessionReference(id), undefined); + const replacement = await connections.attach(id, 55159, 'external-host'); + const current = session.getSessionReference(id); + assert.ok(current); + const replacementHost = await (listener.secondCall.returnValue as Promise); + assert.deepStrictEqual(await connections.waitForAttach(replacement), { + address: replacementHost.address, + }); + await assert.rejects(connections.waitForAttach(old), /closed before acknowledging/); + gate.resolve(); + await waitForValue(() => (lateHost && dispose.calledOn(lateHost) ? true : undefined)); + assert.strictEqual(dispose.calledOn(replacementHost), false); + assert.deepStrictEqual(session.getSessionReference(id), current); + assert.deepStrictEqual( + changes.map((change) => change.kind), + ['connected'], + ); + replacement.destroy(); + await waitForValue(() => (dispose.calledOn(replacementHost) ? true : undefined)); + } finally { + gate.resolve(); + subscription.dispose(); + } + }); + + test('an abandoned replacement does not cancel the live terminal lookup', async () => { + const id = 'abandoned-replacement'; + const processId = deferred(); + const discovering = deferred(); + const terminal = { + get processId() { + discovering.resolve(); + return processId.promise; + }, + sendText: sandbox.stub(), + show: sandbox.stub(), + } as unknown as vscode.Terminal; + terminals.value([terminal]); + activeTerminal.value(terminal); + const gate = deferred(); + const started = deferred(); + const create = JdvHost.create.bind(JdvHost); + const listener = sandbox.stub(JdvHost, 'create').callThrough(); + listener.onSecondCall().callsFake(async (events) => { + started.resolve(); + await gate.promise; + return create(events); + }); + try { + const live = await connections.startAttach(id, 55164, os.hostname()); + assert.ok('address' in (await connections.waitForAttach(live))); + await discovering.promise; + const contender = await connections.startAttach(id, 55164, os.hostname()); + await started.promise; + contender.destroy(); + await waitForValue(() => + !session.activeConnections.has(contender) ? true : undefined, + ); + processId.resolve(55164); + await live._terminalLookup; + assert.strictEqual(live._terminalPid, 55164); + await waitForValue(() => (session.activeSession?.socket === live ? true : undefined)); + } finally { + gate.resolve(); + } + }); + + test('a listener deadline still acknowledges the session', async () => { + const id = 'listener-deadline'; + const gate = deferred(); + const create = JdvHost.create.bind(JdvHost); + const dispose = sandbox.spy(JdvHost.prototype, 'dispose'); + const listener = sandbox.stub(JdvHost, 'create').callsFake(async (events) => { + await gate.promise; + return create(events); + }); + try { + const socket = await connections.startAttach(id, 55157, 'external-host'); + assert.deepStrictEqual(await connections.waitForAttach(socket), { + unavailable: { + code: 'listener_failed', + message: 'Timed out starting the jdv listener.', + }, + }); + assert.ok(session.getSessionReference(id)); + const write = sandbox.spy(socket, 'write'); + const reply = session.sessionRequest({ method: 'plot_latest' }, id); + const request = JSON.parse(String(write.lastCall.args[0])) as { id: number }; + socket.emit( + 'data', + Buffer.from(JSON.stringify({ id: request.id, result: 'plot' }) + '\n'), + ); + assert.strictEqual(await reply, 'plot'); + gate.resolve(); + const host = await (listener.firstCall.returnValue as Promise); + await waitForValue(() => (dispose.calledOn(host) ? true : undefined)); + } finally { + gate.resolve(); + } }); test('plot notifications arriving during native terminal discovery are shown for the connected session', async () => { @@ -1062,13 +1246,16 @@ suite('Session Connection Lifecycle API', () => { test('shutdown revokes live references and emits disconnect before awaiting teardown', async () => { const events: RSessionConnectionChange[] = []; const subscription = session.onDidChangeSessionConnection((event) => events.push(event)); + const dispose = sandbox.spy(JdvHost.prototype, 'dispose'); let shutdown: Promise | undefined; try { - await connections.attach('external-shutdown', 55007, 'external-host', { + const socket = await connections.attach('external-shutdown', 55007, 'external-host', { attachmentId: 'shutdown', autoActivate: false, }); assert.ok(session.getSessionReference('external-shutdown')); + const jdv = await connections.waitForAttach(socket); + assert.ok('address' in jdv); shutdown = session.shutdownSessionWatcher(); assert.strictEqual(session.getSessionReference('external-shutdown'), undefined); assert.deepStrictEqual( @@ -1076,6 +1263,13 @@ suite('Session Connection Lifecycle API', () => { ['connected', 'disconnected'], ); assert.strictEqual(events[1].session.attachmentId, 'shutdown'); + await waitForValue(() => + dispose + .getCalls() + .some(({ thisValue }) => (thisValue as JdvHost).address === jdv.address) + ? true + : undefined, + ); } finally { await shutdown; subscription.dispose(); diff --git a/src/test/suite/dataViewerSessions.test.ts b/src/test/suite/dataViewerSessions.test.ts index 107410f7f..ef63f1547 100644 --- a/src/test/suite/dataViewerSessions.test.ts +++ b/src/test/suite/dataViewerSessions.test.ts @@ -1,3 +1,4 @@ +import { attachSessionSocket } from '../common/sessionConnections'; import * as assert from 'assert'; import fs from 'fs/promises'; import * as net from 'net'; @@ -172,6 +173,9 @@ suite('Viewer session ownership', () => { while ((newline = buffer.indexOf('\n')) >= 0) { const request = JSON.parse(buffer.slice(0, newline)) as Request; buffer = buffer.slice(newline + 1); + if (!request.method) { + continue; + } client.requests.push(request); let result: unknown = true; switch (request.method) { @@ -205,8 +209,7 @@ suite('Viewer session ownership', () => { socket.once('connect', resolve); socket.once('error', reject); }); - notify(client, 'attach', { - protocol_version: 2, + await attachSessionSocket(socket, { session_id: id, host, pid, diff --git a/src/test/suite/htmlWidgetBrowser.test.ts b/src/test/suite/htmlWidgetBrowser.test.ts index de6e24ca0..16600dbc7 100644 --- a/src/test/suite/htmlWidgetBrowser.test.ts +++ b/src/test/suite/htmlWidgetBrowser.test.ts @@ -1,3 +1,4 @@ +import { attachSessionSocket } from '../common/sessionConnections'; import * as assert from 'assert'; import { createHash } from 'crypto'; import * as fs from 'fs'; @@ -1321,7 +1322,7 @@ suite('HTML widget browser rendering', () => { method?: string; }; buffer = buffer.slice(newline + 1); - if (request.id === undefined) { + if (request.id === undefined || !request.method) { continue; } if (request.method === 'workspace') { @@ -1346,7 +1347,7 @@ suite('HTML widget browser rendering', () => { const notify = (method: string, params: Record) => { socket.write(JSON.stringify({ jsonrpc: '2.0', method, params }) + '\n'); }; - notify('attach', { + await attachSessionSocket(socket, { protocol_version: connection.protocolVersion, session_id: id, host: 'native-toolbar-test-host', diff --git a/src/test/suite/session.test.ts b/src/test/suite/session.test.ts index 245dcc209..fa0698ad6 100644 --- a/src/test/suite/session.test.ts +++ b/src/test/suite/session.test.ts @@ -1,3 +1,4 @@ +import { attachSessionSocket } from '../common/sessionConnections'; import { TOOL_MINIMUM_VERSIONS } from '../../toolVersions'; import * as vscode from 'vscode'; import * as sinon from 'sinon'; @@ -377,7 +378,7 @@ suite('Session Communication', () => { const connection = await api.getConnectionInfo(); assert.ok(connection); - assert.strictEqual(connection.protocolVersion, 2); + assert.strictEqual(connection.protocolVersion, 3); assert.strictEqual(connection.endpoint, session.globalPipePath); assert.strictEqual(connection.plotBackend, 'standard'); assert.ok( @@ -434,22 +435,15 @@ suite('Session Communication', () => { ); assert.ok(server); attached.push({ id, client, server }); - client.write( - `${JSON.stringify({ - jsonrpc: '2.0', - method: 'attach', - params: { - protocol_version: 2, - session_id: id, - host: 'test-remote-host', - version: '4.4.0', - pid: id, - tempdir: '/tmp', - wd: '/tmp', - info: { version: 'R version 4.4.0', command: 'R', start_time: '' }, - }, - })}\n`, - ); + await attachSessionSocket(client, { + session_id: id, + host: 'test-remote-host', + version: '4.4.0', + pid: id, + tempdir: '/tmp', + wd: '/tmp', + info: { version: 'R version 4.4.0', command: 'R', start_time: '' }, + }); await waitFor(() => session.activeSession?.sessionId === id); }; @@ -1455,21 +1449,14 @@ suite('Session Communication', () => { assert.ok(socket); sockets.push(socket); const id = `reconnected-${terminalPid}`; - client.write( - `${JSON.stringify({ - jsonrpc: '2.0', - method: 'attach', - params: { - protocol_version: 2, - session_id: id, - host: os.hostname(), - pid: terminalPid, - version: '4.4.0', - tempdir: '/tmp', - wd: '/tmp', - }, - })}\n`, - ); + await attachSessionSocket(client, { + session_id: id, + host: os.hostname(), + pid: terminalPid, + version: '4.4.0', + tempdir: '/tmp', + wd: '/tmp', + }); await waitFor(() => socket._sessionId === id); await socket._terminalLookup; if (terminalPid === 46241 && order[0] === 46240) { @@ -1532,22 +1519,15 @@ suite('Session Communication', () => { client.once('connect', resolve); client.once('error', reject); }); - client.write( - `${JSON.stringify({ - jsonrpc: '2.0', - method: 'attach', - params: { - protocol_version: 2, - session_id: 'manual-recovery-first', - host: os.hostname(), - pid: 45240, - version: '4.5.0', - tempdir: os.tmpdir(), - wd: os.tmpdir(), - info: { version: 'R 4.5.0', command: 'R', start_time: '' }, - }, - })}\n`, - ); + await attachSessionSocket(client, { + session_id: 'manual-recovery-first', + host: os.hostname(), + pid: 45240, + version: '4.5.0', + tempdir: os.tmpdir(), + wd: os.tmpdir(), + info: { version: 'R 4.5.0', command: 'R', start_time: '' }, + }); await waitFor(() => session.activeSession?.sessionId === 'manual-recovery-first'); await session.activateRSession(); sinon.assert.calledOnce(second.sendText); @@ -1735,23 +1715,16 @@ suite('Session Communication', () => { socket.once('connect', resolve); socket.once('error', reject); }); - socket.write( - `${JSON.stringify({ - jsonrpc: '2.0', - method: 'attach', - params: { - protocol_version: 2, - session_id: 'stable-session-id', - host: 'remote-compute-node', - sess_version: '3.0.0', - pid, - version: 'R 4.4.0', - info: { version: '4.4.0', command: 'R', start_time: 'now' }, - tempdir: '/tmp/session', - wd: '/workspace', - }, - })}\n`, - ); + await attachSessionSocket(socket, { + session_id: 'stable-session-id', + host: 'remote-compute-node', + sess_version: '3.0.0', + pid, + version: 'R 4.4.0', + info: { version: '4.4.0', command: 'R', start_time: 'now' }, + tempdir: '/tmp/session', + wd: '/workspace', + }); }; try { @@ -1808,23 +1781,16 @@ suite('Session Communication', () => { otherSession.once('connect', resolve); otherSession.once('error', reject); }); - otherSession.write( - `${JSON.stringify({ - jsonrpc: '2.0', - method: 'attach', - params: { - protocol_version: 2, - session_id: 'other-session-id', - host: 'other-compute-node', - sess_version: '3.0.0', - pid: 9876, - version: 'R 4.4.0', - info: { version: '4.4.0', command: 'R', start_time: 'now' }, - tempdir: '/tmp/other-session', - wd: '/workspace', - }, - })}\n`, - ); + await attachSessionSocket(otherSession, { + session_id: 'other-session-id', + host: 'other-compute-node', + sess_version: '3.0.0', + pid: 9876, + version: 'R 4.4.0', + info: { version: '4.4.0', command: 'R', start_time: 'now' }, + tempdir: '/tmp/other-session', + wd: '/workspace', + }); await waitFor(() => session.activeSession?.sessionId === 'other-session-id'); assert.strictEqual( session.activeSession?.pid, @@ -1853,23 +1819,17 @@ suite('Session Communication', () => { const showError = sandbox.stub(vscode.window, 'showErrorMessage'); const endpoint = await session.getGlobalPipePath(); const client = net.createConnection(endpoint); - const sendAttach = (sessionId: string) => - client.write( - `${JSON.stringify({ - jsonrpc: '2.0', - method: 'attach', - params: { - protocol_version: 2, - session_id: sessionId, - host: 'remote-compute-node', - sess_version: '3.0.0', - pid: 1234, - version: 'R 4.4.0', - info: { version: '4.4.0', command: 'R', start_time: 'now' }, - tempdir: '/tmp/session', - wd: '/workspace', - }, - })}\n`, + const sendAttach = (sessionId: string, expectedError?: RegExp) => + attachSessionSocket( + client, + { + session_id: sessionId, + host: 'remote-compute-node', + pid: 1234, + tempdir: '/tmp/session', + wd: '/tmp/workspace', + }, + expectedError, ); try { @@ -1877,7 +1837,7 @@ suite('Session Communication', () => { client.once('connect', resolve); client.once('error', reject); }); - sendAttach('session-a'); + await sendAttach('session-a'); await waitFor(() => session.activeSession?.sessionId === 'session-a'); const attachedSession = session.activeSession; if (!attachedSession) { @@ -1885,7 +1845,7 @@ suite('Session Communication', () => { } const boundSocket = attachedSession.socket; - sendAttach('session-b'); + await sendAttach('session-b', /already bound to session session-a/); await waitFor(() => showError.called); assert.match(String(showError.firstCall.args[0]), /already bound to session session-a/); await waitFor(() => !session.activeSession); @@ -1905,17 +1865,15 @@ suite('Session Communication', () => { client.once('connect', resolve); client.once('error', reject); }); - client.write( - `${JSON.stringify({ - jsonrpc: '2.0', - method: 'attach', - params: { protocol_version: 1, session_id: 'legacy-session' }, - })}\n`, + await attachSessionSocket( + client, + { protocol_version: 1, session_id: 'legacy-session' }, + /unsupported sess protocol version 1/, ); await waitFor(() => showError.called); assert.match( String(showError.firstCall.args[0]), - /unsupported sess protocol version 1; this extension requires protocol version 2/, + /unsupported sess protocol version 1; this extension requires protocol version 3/, ); assert.notStrictEqual(session.activeSession?.sessionId, 'legacy-session'); } finally { @@ -1932,17 +1890,14 @@ suite('Session Communication', () => { client.once('connect', resolve); client.once('error', reject); }); - client.write( - `${JSON.stringify({ - jsonrpc: '2.0', - method: 'attach', - params: { - protocol_version: 2, - session_id: 'malformed-session', - tempdir: { path: os.tmpdir() }, - wd: os.tmpdir(), - }, - })}\n`, + await attachSessionSocket( + client, + { + session_id: 'malformed-session', + tempdir: { path: os.tmpdir() }, + wd: os.tmpdir(), + }, + /missing or invalid session paths/, ); await waitFor(() => showError.called); assert.match(String(showError.firstCall.args[0]), /missing or invalid session paths/);