Detect if R code is running from RStudio Connect

400 views Asked by At

I have some content (written in the R language) deployed to an RStudio Connect instance.

I would like to be able to do something like:

if (isTRUE(is_connect)) {
  print("Running on Connect")
} else {
  print("Not running on Connect")
}

That is, I'd like to have my code detect whether it is running from RStudio Connect or not, and behave differently depending on its environment.

How can I detect, using R code, whether it is running on RStudio Connect?

2

There are 2 answers

1
r2evans On BEST ANSWER

An alternative that I've been using is the R_CONFIG_ACTIVE envvar. From https://docs.rstudio.com/connect/admin/process-management/#using-the-config-package,

By default, R processes launched by RStudio Connect set R_CONFIG_ACTIVE to rsconnect.

This this, one might use

if (Sys.getenv("R_CONFIG_ACTIVE") == "rsconnect") {
  print("Running on Connect")
} else {
  print("Not running on Connect")
}

It's safe to not use isTRUE here, since Sys.getenv will always return a string of length 1; if it is unset, it returns "" (still length 1, just empty). (It's okay to use isTRUE if you still prefer.)

If you are curious what else is set within the RSC environment, see my other answer for a quick app that displays env-vars (among others).

1
jwalton On

Since v1.8.8 (April 2021) RStudio Connect has defined the CONNECT_SERVER environment variable to all content runtimes (source).

You could use the existence of this environment variable to detect if you're running on Connect or not:

is_connect = function() {
  Sys.getenv("CONNECT_SERVER") != ""
}

You could then use this in your code as:

if (isTRUE(is_connect())) {
  print("Running on Connect")
} else {
  print("Not running on Connect")
}

Of course this solution isn't completely fool-proof: there's nothing to stop me from defining a CONNECT_SERVER environment variable on my local machine, but so long as you don't do this you'll be fine...