1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: Apache-2.0
5 getAPIDocument <- function(){
6 url <- "https://jutro.arvadosapi.com/discovery/v1/apis/arvados/v1/rest"
7 serverResponse <- httr::RETRY("GET", url = url)
9 httr::content(serverResponse, as = "parsed", type = "application/json")
13 generateAPI <- function()
15 #TODO: Consider passing discovery document URL as parameter.
16 #TODO: Consider passing location where to create new files.
17 discoveryDocument <- getAPIDocument()
19 methodResources <- discoveryDocument$resources
21 # Don't emit deprecated APIs
22 methodResources <- methodResources[!(names(methodResources) %in% c("jobs", "job_tasks", "pipeline_templates", "pipeline_instances",
23 "keep_disks", "nodes", "humans", "traits", "specimens"))]
24 resourceNames <- names(methodResources)
26 methodDoc <- genMethodsDoc(methodResources, resourceNames)
27 classDoc <- genAPIClassDoc(methodResources, resourceNames)
28 arvadosAPIHeader <- genAPIClassHeader()
29 arvadosProjectMethods <- genProjectMethods()
30 arvadosClassMethods <- genClassContent(methodResources, resourceNames)
31 arvadosAPIFooter <- genAPIClassFooter()
33 arvadosClass <- c(methodDoc,
36 arvadosProjectMethods,
40 fileConn <- file("./R/Arvados.R", "w")
42 "# Copyright (C) The Arvados Authors. All rights reserved.",
44 "# SPDX-License-Identifier: Apache-2.0", ""), fileConn)
45 writeLines(unlist(arvadosClass), fileConn)
50 genAPIClassHeader <- function()
52 c("Arvados <- R6::R6Class(",
58 "\t\tinitialize = function(authToken = NULL, hostName = NULL, numRetries = 0)",
60 "\t\t\tif(!is.null(hostName))",
61 "\t\t\t\tSys.setenv(ARVADOS_API_HOST = hostName)",
63 "\t\t\tif(!is.null(authToken))",
64 "\t\t\t\tSys.setenv(ARVADOS_API_TOKEN = authToken)",
66 "\t\t\thostName <- Sys.getenv(\"ARVADOS_API_HOST\")",
67 "\t\t\ttoken <- Sys.getenv(\"ARVADOS_API_TOKEN\")",
69 "\t\t\tif(hostName == \"\" | token == \"\")",
70 "\t\t\t\tstop(paste(\"Please provide host name and authentification token\",",
71 "\t\t\t\t\t\t \"or set ARVADOS_API_HOST and ARVADOS_API_TOKEN\",",
72 "\t\t\t\t\t\t \"environment variables.\"))",
74 "\t\t\tprivate$token <- token",
75 "\t\t\tprivate$host <- paste0(\"https://\", hostName, \"/arvados/v1/\")",
76 "\t\t\tprivate$numRetries <- numRetries",
77 "\t\t\tprivate$REST <- RESTService$new(token, hostName,",
78 "\t\t\t HttpRequest$new(), HttpParser$new(),",
84 genProjectMethods <- function()
86 c("\t\tprojects.get = function(uuid)",
88 "\t\t\tself$groups.get(uuid)",
91 "\t\tprojects.create = function(group, ensure_unique_name = \"false\")",
93 "\t\t\tgroup <- c(\"group_class\" = \"project\", group)",
94 "\t\t\tself$groups.create(group, ensure_unique_name)",
97 "\t\tprojects.update = function(group, uuid)",
99 "\t\t\tgroup <- c(\"group_class\" = \"project\", group)",
100 "\t\t\tself$groups.update(group, uuid)",
103 "\t\tprojects.list = function(filters = NULL, where = NULL,",
104 "\t\t\torder = NULL, select = NULL, distinct = NULL,",
105 "\t\t\tlimit = \"100\", offset = \"0\", count = \"exact\",",
106 "\t\t\tinclude_trash = NULL)",
108 "\t\t\tfilters[[length(filters) + 1]] <- list(\"group_class\", \"=\", \"project\")",
109 "\t\t\tself$groups.list(filters, where, order, select, distinct,",
110 "\t\t\t limit, offset, count, include_trash)",
113 "\t\tprojects.delete = function(uuid)",
115 "\t\t\tself$groups.delete(uuid)",
120 genClassContent <- function(methodResources, resourceNames)
122 arvadosMethods <- Map(function(resource, resourceName)
124 methodNames <- names(resource$methods)
126 functions <- Map(function(methodMetaData, methodName)
128 #NOTE: Index, show and destroy are aliases for the preferred names
129 # "list", "get" and "delete". Until they are removed from discovery
130 # document we will filter them here.
131 if(methodName %in% c("index", "show", "destroy"))
134 methodName <- paste0(resourceName, ".", methodName)
135 createMethod(methodName, methodMetaData)
137 }, resource$methods, methodNames)
139 unlist(unname(functions))
141 }, methodResources, resourceNames)
146 genAPIClassFooter <- function()
148 c("\t\tgetHostName = function() private$host,",
149 "\t\tgetToken = function() private$token,",
150 "\t\tsetRESTService = function(newREST) private$REST <- newREST,",
151 "\t\tgetRESTService = function() private$REST",
159 "\t\tnumRetries = NULL",
162 "\tcloneable = FALSE",
166 createMethod <- function(name, methodMetaData)
168 args <- getMethodArguments(methodMetaData)
169 signature <- getMethodSignature(name, args)
170 body <- getMethodBody(methodMetaData)
178 getMethodArguments <- function(methodMetaData)
180 request <- methodMetaData$request
183 if(!is.null(request))
185 resourceName <- tolower(request$properties[[1]][[1]])
188 requestArgs <- resourceName
190 requestArgs <- paste(resourceName, "=", "NULL")
193 argNames <- names(methodMetaData$parameters)
195 args <- sapply(argNames, function(argName)
197 arg <- methodMetaData$parameters[[argName]]
201 if(!is.null(arg$default))
202 return(paste0(argName, " = ", "\"", arg$default, "\""))
204 return(paste(argName, "=", "NULL"))
213 getMethodSignature <- function(methodName, args)
215 collapsedArgs <- paste0(args, collapse = ", ")
216 lineLengthLimit <- 40
218 if(nchar(collapsedArgs) > lineLengthLimit)
220 return(paste0("\t\t",
221 formatArgs(paste(methodName, "= function("),
222 "\t", args, ")", lineLengthLimit)))
226 return(paste0("\t\t", methodName, " = function(", collapsedArgs, ")"))
230 getMethodBody <- function(methodMetaData)
232 url <- getRequestURL(methodMetaData)
233 headers <- getRequestHeaders()
234 requestQueryList <- getRequestQueryList(methodMetaData)
235 requestBody <- getRequestBody(methodMetaData)
236 request <- getRequest(methodMetaData)
237 response <- getResponse(methodMetaData)
238 errorCheck <- getErrorCheckingCode()
239 returnStatement <- getReturnObject()
243 requestQueryList, "",
245 request, response, "",
249 paste0("\t\t\t", body)
252 getRequestURL <- function(methodMetaData)
254 endPoint <- methodMetaData$path
255 endPoint <- stringr::str_replace_all(endPoint, "\\{", "${")
256 url <- c(paste0("endPoint <- stringr::str_interp(\"", endPoint, "\")"),
257 paste0("url <- paste0(private$host, endPoint)"))
261 getRequestHeaders <- function()
263 c("headers <- list(Authorization = paste(\"Bearer\", private$token), ",
264 " \"Content-Type\" = \"application/json\")")
267 getRequestQueryList <- function(methodMetaData)
269 queryArgs <- names(Filter(function(arg) arg$location == "query",
270 methodMetaData$parameters))
272 if(length(queryArgs) == 0)
273 return("queryArgs <- NULL")
275 queryArgs <- sapply(queryArgs, function(arg) paste0(arg, " = ", arg))
276 collapsedArgs <- paste0(queryArgs, collapse = ", ")
278 lineLengthLimit <- 40
280 if(nchar(collapsedArgs) > lineLengthLimit)
281 return(formatArgs("queryArgs <- list(", "\t\t\t\t ", queryArgs, ")",
284 return(paste0("queryArgs <- list(", collapsedArgs, ")"))
287 getRequestBody <- function(methodMetaData)
289 request <- methodMetaData$request
291 if(is.null(request) || !request$required)
292 return("body <- NULL")
294 resourceName <- tolower(request$properties[[1]][[1]])
296 requestParameterName <- names(request$properties)[1]
298 c(paste0("if(length(", resourceName, ") > 0)"),
299 paste0("\tbody <- jsonlite::toJSON(list(", resourceName, " = ", resourceName, "), "),
300 "\t auto_unbox = TRUE)",
305 getRequest <- function(methodMetaData)
307 method <- methodMetaData$httpMethod
308 c(paste0("response <- private$REST$http$exec(\"", method, "\", url, headers, body,"),
309 " queryArgs, private$numRetries)")
312 getResponse <- function(methodMetaData)
314 "resource <- private$REST$httpParser$parseJSONResponse(response)"
317 getErrorCheckingCode <- function()
319 c("if(!is.null(resource$errors))",
320 "\tstop(resource$errors)")
323 getReturnObject <- function()
328 #NOTE: Arvados class documentation:
330 genMethodsDoc <- function(methodResources, resourceNames)
332 methodsDoc <- unlist(unname(Map(function(resource, resourceName)
334 methodNames <- names(resource$methods)
336 methodDoc <- Map(function(methodMetaData, methodName)
338 #NOTE: Index, show and destroy are aliases for the preferred names
339 # "list", "get" and "delete". Until they are removed from discovery
340 # document we will filter them here.
341 if(methodName %in% c("index", "show", "destroy"))
344 methodName <- paste0(resourceName, ".", methodName)
345 getMethodDoc(methodName, methodMetaData)
347 }, resource$methods, methodNames)
349 unlist(unname(methodDoc))
351 }, methodResources, resourceNames)))
353 projectDoc <- genProjectMethodsDoc()
355 c(methodsDoc, projectDoc)
358 genAPIClassDoc <- function(methodResources, resourceNames)
362 "#' Arvados class gives users ability to access Arvados REST API.",
364 "#' @section Usage:",
365 "#' \\preformatted{arv = Arvados$new(authToken = NULL, hostName = NULL, numRetries = 0)}",
367 "#' @section Arguments:",
369 "#' \t\\item{authToken}{Authentification token. If not specified ARVADOS_API_TOKEN environment variable will be used.}",
370 "#' \t\\item{hostName}{Host name. If not specified ARVADOS_API_HOST environment variable will be used.}",
371 "#' \t\\item{numRetries}{Number which specifies how many times to retry failed service requests.}",
374 "#' @section Methods:",
376 getAPIClassMethodList(methodResources, resourceNames),
382 "#' arv <- Arvados$new(\"your Arvados token\", \"example.arvadosapi.com\")",
384 "#' collection <- arv$collections.get(\"uuid\")",
386 "#' collectionList <- arv$collections.list(list(list(\"name\", \"like\", \"Test%\")))",
387 "#' collectionList <- listAll(arv$collections.list, list(list(\"name\", \"like\", \"Test%\")))",
389 "#' deletedCollection <- arv$collections.delete(\"uuid\")",
391 "#' updatedCollection <- arv$collections.update(list(name = \"New name\", description = \"New description\"),",
394 "#' createdCollection <- arv$collections.create(list(name = \"Example\",",
395 "#' description = \"This is a test collection\"))",
402 getAPIClassMethodList <- function(methodResources, resourceNames)
404 methodList <- unlist(unname(Map(function(resource, resourceName)
406 methodNames <- names(resource$methods)
409 methodNames[!(methodNames %in% c("index", "show", "destroy"))])
411 }, methodResources, resourceNames)))
413 hardcodedMethods <- c("projects.create", "projects.get",
414 "projects.list", "projects.update", "projects.delete")
415 paste0("#' \t\\item{}{\\code{\\link{", sort(c(methodList, hardcodedMethods)), "}}}")
418 getMethodDoc <- function(methodName, methodMetaData)
420 name <- paste("#' @name", methodName)
421 usage <- getMethodUsage(methodName, methodMetaData)
422 description <- paste("#'", methodName, "is a method defined in Arvados class.")
423 params <- getMethodDescription(methodMetaData)
424 returnValue <- paste("#' @return", methodMetaData$response[["$ref"]], "object.")
426 c(paste("#'", methodName),
438 getMethodUsage <- function(methodName, methodMetaData)
440 lineLengthLimit <- 40
441 args <- getMethodArguments(methodMetaData)
442 c(formatArgs(paste0("#' @usage arv$", methodName,
443 "("), "#' \t", args, ")", lineLengthLimit))
446 getMethodDescription <- function(methodMetaData)
448 request <- methodMetaData$request
451 if(!is.null(request))
453 requestDoc <- unname(unlist(sapply(request$properties, function(prop)
455 className <- sapply(prop, function(ref) ref)
456 objectName <- paste0(tolower(substr(className, 1, 1)),
457 substr(className, 2, nchar(className)))
458 paste("#' @param", objectName, className, "object.")
462 argNames <- names(methodMetaData$parameters)
464 argsDoc <- unname(unlist(sapply(argNames, function(argName)
466 arg <- methodMetaData$parameters[[argName]]
467 argDescription <- arg$description
468 paste("#' @param", argName, argDescription)
471 c(requestDoc, argsDoc)
474 genProjectMethodsDoc <- function()
476 #TODO: Manually update this documentation to reflect changes in discovery document.
479 "#' projects.get is equivalent to groups.get method.",
481 "#' @usage arv$projects.get(uuid)",
482 "#' @param uuid The UUID of the Group in question.",
483 "#' @return Group object.",
484 "#' @name projects.get",
489 "#' projects.create wrapps groups.create method by setting group_class attribute to \"project\".",
491 "#' @usage arv$projects.create(group, ensure_unique_name = \"false\")",
492 "#' @param group Group object.",
493 "#' @param ensure_unique_name Adjust name to ensure uniqueness instead of returning an error on (owner_uuid, name) collision.",
494 "#' @return Group object.",
495 "#' @name projects.create",
500 "#' projects.update wrapps groups.update method by setting group_class attribute to \"project\".",
502 "#' @usage arv$projects.update(group, uuid)",
503 "#' @param group Group object.",
504 "#' @param uuid The UUID of the Group in question.",
505 "#' @return Group object.",
506 "#' @name projects.update",
511 "#' projects.delete is equivalent to groups.delete method.",
513 "#' @usage arv$project.delete(uuid)",
514 "#' @param uuid The UUID of the Group in question.",
515 "#' @return Group object.",
516 "#' @name projects.delete",
521 "#' projects.list wrapps groups.list method by setting group_class attribute to \"project\".",
523 "#' @usage arv$projects.list(filters = NULL,",
524 "#' where = NULL, order = NULL, distinct = NULL,",
525 "#' limit = \"100\", offset = \"0\", count = \"exact\",",
526 "#' include_trash = NULL, uuid = NULL, recursive = NULL)",
527 "#' @param filters ",
530 "#' @param distinct ",
534 "#' @param include_trash Include items whose is_trashed attribute is true.",
536 "#' @param recursive Include contents from child groups recursively.",
537 "#' @return Group object.",
538 "#' @name projects.list",
543 #NOTE: Utility functions:
545 # This function is used to split very long lines of code into smaller chunks.
546 # This is usually the case when we pass a lot of named argumets to a function.
547 formatArgs <- function(prependAtStart, prependToEachSplit,
548 args, appendAtEnd, lineLength)
552 args[1:(length(args) - 1)] <- paste0(args[1:(length(args) - 1)], ",")
555 args[1] <- paste0(prependAtStart, args[1])
556 args[length(args)] <- paste0(args[length(args)], appendAtEnd)
558 argsLength <- length(args)
562 while(index <= argsLength)
567 while(nchar(line) < lineLength && index <= argsLength)
569 line <- paste(line, args[index])
573 argLines <- c(argLines, line)
576 argLines <- unlist(argLines)
577 argLinesLen <- length(argLines)
580 argLines[2:argLinesLen] <- paste0(prependToEachSplit, argLines[2:argLinesLen])