/
applications.R
326 lines (289 loc) · 10.1 KB
/
applications.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
#' List Deployed Applications
#'
#' List all applications currently deployed for a given account.
#' @inheritParams deployApp
#' @return
#' Returns a data frame with the following columns:
#' \tabular{ll}{
#' `id` \tab Application unique id \cr
#' `name` \tab Name of application \cr
#' `title` \tab Application title \cr
#' `url` \tab URL where application can be accessed \cr
#'
#' `status` \tab Current status of application. Valid values are `pending`,
#' `deploying`, `running`, `terminating`, and `terminated` \cr
#' `size` \tab Instance size (small, medium, large, etc.) (on
#' ShinyApps.io) \cr
#' `instances` \tab Number of instances (on ShinyApps.io) \cr
#' `config_url` \tab URL where application can be configured \cr
#' }
#' @note To register an account you call the [setAccountInfo()] function.
#' @examples
#' \dontrun{
#'
#' # list all applications for the default account
#' applications()
#'
#' # list all applications for a specific account
#' applications("myaccount")
#'
#' # view the list of applications in the data viewer
#' View(applications())
#' }
#' @seealso [deployApp()], [terminateApp()]
#' @family Deployment functions
#' @export
applications <- function(account = NULL, server = NULL) {
# resolve account and create connect client
accountDetails <- accountInfo(account, server)
serverDetails <- serverInfo(accountDetails$server)
client <- clientForAccount(accountDetails)
isConnect <- isConnectServer(accountDetails$server)
# retrieve applications
apps <- client$listApplications(accountDetails$accountId)
# extract the subset of fields we're interested in
keep <- if (isConnect) {
c(
"id",
"name",
"title",
"url",
"build_status",
"created_time",
"last_deployed_time",
"guid"
)
} else {
c(
"id",
"name",
"url",
"status",
"created_time",
"updated_time",
"deployment"
)
}
res <- lapply(apps, `[`, keep)
res <- if (isConnect) {
lapply(res, function(x) {
# set size and instance to NA since Connect doesn't return this info
x$size <- NA
x$instances <- NA
x$title <- x$title %||% NA_character_
x
})
} else {
lapply(res, function(x) {
# promote the size and instance data to first-level fields
x$size <- x$deployment$properties$application.instances.template
if (is.null(x$size))
x$size <- NA
x$instances <- x$deployment$properties$application.instances.count
if (is.null(x$instances))
x$instances <- NA
x$deployment <- NULL
x$guid <- NA
x$title <- NA_character_
x
})
}
# The config URL may be provided by the server at some point, but for now
# infer it from the account type
res <- lapply(res, function(row) {
if (isConnect) {
prefix <- sub("/__api__", "", serverDetails$url)
row$config_url <- paste(prefix, "connect/#/apps", row$id, sep = "/")
} else {
row$config_url <- paste("https://www.shinyapps.io/admin/#/application", row$id, sep = "/")
}
row
})
# convert to data frame
res <- lapply(res, as.data.frame, stringsAsFactors = FALSE)
res <- do.call("rbind", res)
# Ensure the Connect and ShinyApps.io data frames have same column names
idx <- match("last_deployed_time", names(res))
if (!is.na(idx)) names(res)[idx] <- "updated_time"
idx <- match("build_status", names(res))
if (!is.na(idx)) names(res)[idx] <- "status"
return(res)
}
# Use the API to filter applications by name and error when it does not exist.
getAppByName <- function(client, accountInfo, name, error_call = caller_env()) {
# NOTE: returns a list with 0 or 1 elements
app <- client$listApplications(accountInfo$accountId, filters = list(name = name))
if (length(app)) {
return(app[[1]])
}
cli::cli_abort(
c(
"No application found",
i = "Specify the application directory, name, and/or associated account."
),
call = error_call,
class = "rsconnect_app_not_found"
)
}
# Use the API to list all applications then filter the results client-side.
resolveApplication <- function(accountDetails, appName) {
client <- clientForAccount(accountDetails)
apps <- client$listApplications(accountDetails$accountId)
for (app in apps) {
if (identical(app$name, appName))
return(app)
}
stopWithApplicationNotFound(appName)
}
getApplication <- function(account, server, appId) {
accountDetails <- accountInfo(account, server)
client <- clientForAccount(accountDetails)
withCallingHandlers(
client$getApplication(appId, "unknown"),
rsconnect_http_404 = function(err) {
cli::cli_abort("Can't find app with id {.str {appId}}", parent = err)
}
)
}
stopWithApplicationNotFound <- function(appName) {
stop(paste("No application named '", appName, "' is currently deployed.",
sep = ""), call. = FALSE)
}
applicationTask <- function(taskDef, appName, accountDetails, quiet) {
# resolve target account and application
application <- resolveApplication(accountDetails, appName)
# get status function and display initial status
displayStatus <- displayStatus(quiet)
displayStatus(paste(taskDef$beginStatus, "...\n", sep = ""))
# perform the action
client <- clientForAccount(accountDetails)
task <- taskDef$action(client, application)
client$waitForTask(task$task_id, quiet)
displayStatus(paste(taskDef$endStatus, "\n", sep = ""))
invisible(NULL)
}
# streams application logs from ShinyApps
streamApplicationLogs <- function(authInfo, applicationId, entries, skip) {
# build the URL
url <- paste0(serverInfo("shinyapps.io")$url, "/applications/", applicationId,
"/logs?", "count=", entries, "&tail=1")
parsed <- parseHttpUrl(url)
# create the curl handle and perform the minimum necessary to create an
# authenticated request. we ignore the rsconnect.http option here because only
# curl supports the kind of streaming connection that we need.
handle <- createCurlHandle("GET")
curl::handle_setheaders(handle,
.list = signatureHeaders(authInfo, "GET", parsed$path, NULL)
)
# begin the stream
curl::curl_fetch_stream(url = url,
fun = function(data) {
if (skip > 0)
skip <<- skip - 1
else
cat(rawToChar(data))
}, handle = handle)
}
#' Show Application Logs
#'
#' Show the logs for a deployed ShinyApps application.
#'
#' @param appPath The path to the directory or file that was deployed.
#' @param appFile The path to the R source file that contains the application
#' (for single file applications).
#' @param appName The name of the application to show logs for. May be omitted
#' if only one application deployment was made from `appPath`.
#' @param account The account under which the application was deployed. May be
#' omitted if only one account is registered on the system.
#' @param server Server name. Required only if you use the same account name on
#' multiple servers.
#' @param entries The number of log entries to show. Defaults to 50 entries.
#' @param streaming Whether to stream the logs. If `TRUE`, then the
#' function does not return; instead, log entries are written to the console
#' as they are made, until R is interrupted. Defaults to `FALSE`.
#'
#' @note This function only uses the \code{libcurl} transport, and works only for
#' ShinyApps servers.
#'
#' @export
showLogs <- function(appPath = getwd(), appFile = NULL, appName = NULL,
account = NULL, server = NULL, entries = 50, streaming = FALSE) {
# determine the log target and target account info
deployment <- findDeployment(
appPath = appPath,
appName = appName,
server = server,
account = account
)
accountDetails <- accountInfo(deployment$account, deployment$server)
client <- clientForAccount(accountDetails)
application <- getAppByName(client, accountDetails, deployment$name)
if (streaming) {
# streaming; poll for the entries directly
skip <- 0
repeat {
tryCatch({
streamApplicationLogs(accountDetails, application$id, entries, skip)
# after the first fetch, we've seen all recent entries, so show
# only new entries. unfortunately /logs/ doesn't support getting 0
# entries, so get one and don't log it.
entries <- 1
skip <- 1
},
error = function(e) {
# if the server times out, ignore the error; otherwise, let it
# bubble through
if (!identical(e$message,
"transfer closed with outstanding read data remaining")) {
stop(e)
}
})
}
} else {
# if not streaming, poll for the entries directly
logs <- client$getLogs(application$id, entries)
cat(logs)
}
}
#' Update deployment records
#'
#' Update the deployment records for applications published to Posit Connect.
#' This updates application title and URL, and deletes records for deployments
#' where the application has been deleted on the server.
#'
#' @param appPath The path to the directory or file that was deployed.
#' @export
syncAppMetadata <- function(appPath = ".") {
check_directory(appPath)
deploys <- deployments(appPath)
for (i in seq_len(nrow(deploys))) {
curDeploy <- deploys[i, ]
# don't sync if published to RPubs
if (isRPubs(curDeploy$server)) {
next
}
account <- accountInfo(curDeploy$account, curDeploy$server)
client <- clientForAccount(account)
application <- tryCatch(
client$getApplication(curDeploy$appId),
rsconnect_http_404 = function(c) {
# if the app has been deleted, delete the deployment record
file.remove(curDeploy$deploymentFile)
cli::cli_inform("Deleting deployment record for deleted app {curDeploy$appId}.")
NULL
}
)
if (is.null(application)) {
next
}
# update the record and save out a new config file
path <- curDeploy$deploymentFile
curDeploy$deploymentFile <- NULL # added on read
# remove old fields
curDeploy$when <- NULL
curDeploy$lastSyncTime <- NULL
curDeploy$title <- application$title
curDeploy$url <- application$url
writeDeploymentRecord(curDeploy, path)
}
}