Debian Codegraph @

R/job.R

raw
1
2 job <- function(callback, data = list()) {
3
4 # unquote things in the callback
5 body(callback) <- renv_expr_impl(body(callback), envir = parent.frame())
6
7 # set up job directory
8 jobdir <- tempfile("renv-job-")
9 ensure_directory(jobdir)
10
11 # set up paths
12 paths <- list(
13 options = file.path(jobdir, "options.rds"),
14 workspace = file.path(jobdir, "workspace.Rdata"),
15 script = file.path(jobdir, "script.R"),
16 result = file.path(jobdir, "result.rds")
17 )
18
19 # save options
20 names <- list("download.file.method", "download.file.extra", "pkgType", "repos")
21 saveRDS(do.call(options, names), file = paths$options)
22
23 # save callback and data
24 save(callback, data, file = paths$workspace)
25
26 # find path where renv is installed
27 library <- if (devmode() || testing()) {
28 dirname(renv_package_find("renv"))
29 } else {
30 dirname(renv_namespace_path("renv"))
31 }
32
33 # create a script that will load this data and run it
34 code <- expr({
35
36 # load renv, and make internal functions visible
37 renv <- loadNamespace("renv", lib.loc = !!library)
38 renv$summon()
39
40 # invoke the provided callback
41 result <- catch({
42 options(readRDS(!!paths$options))
43 base::load(!!paths$workspace)
44 do.call(callback, data)
45 })
46
47 # write result to file
48 saveRDS(result, file = !!paths$result)
49
50 })
51
52 # write code to script
53 writeLines(deparse(code), con = paths$script)
54
55 # run that code
56 renv_scope_envvars(RENV_WATCHDOG_ENABLED = FALSE)
57 args <- c("--vanilla", "-s", "-f", renv_shell_path(paths$script))
58 status <- r(args)
59 if (status != 0L)
60 stopf("error executing job [error code %i]", status)
61
62 # collect the result
63 result <- readRDS(paths$result)
64 if (inherits(result, "error"))
65 stop(result)
66
67 result
68
69 }