Repository navigation
Expand file tree
/
Copy pathpackage-cache.R
More file actions
585 lines (547 loc) · 16 KB
/
Copy pathpackage-cache.R
File metadata and controls
585 lines (547 loc) · 16 KB
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
#' A simple package cache
#'
#' This is an R6 class that implements a concurrency safe package cache.
#'
#' By default these fields are included for every package:
#' * `fullpath` Full package path.
#' * `path` Package path, within the repository.
#' * `package` Package name.
#' * `url` URL it was downloaded from.
#' * `etag` ETag for the last download, from the given URL.
#' * `sha256` SHA256 hash of the file.
#'
#' Additional fields can be added as needed.
#'
#' For a simple API to a session-wide instance of this class, see
#' [pkg_cache_summary()] and the other functions listed there.
#'
#' @section Usage:
#' ```
#' pc <- package_cache$new(path = NULL)
#'
#' pc$list()
#' pc$find(..., .list = NULL)
#' pc$copy_to(..., .list = NULL)
#' pc$add(file, path, sha256 = shasum256(file), ..., .list = NULL)
#' pc$add_url(url, path, ..., .list = NULL, on_progress = NULL,
#' http_headers = NULL)
#' pc$async_add_url(url, path, ..., .list = NULL, on_progress = NULL,
#' http_headers = NULL)
#' pc$copy_or_add(target, urls, path, sha256 = NULL, ..., .list = NULL,
#' on_progress = NULL, http_headers = NULL)
#' pc$async_copy_or_add(target, urls, path, ..., sha256 = NULL, ...,
#' .list = NULL, on_progress = NULL, http_headers = NULL)
#' pc$update_or_add(target, urls, path, ..., .list = NULL,
#' on_progress = NULL, http_headers = NULL)
#' pc$async_update_or_add(target, urls, path, ..., .list = NULL,
#' on_progress = NULL, http_headers = NULL)
#' pc$delete(..., .list = NULL)
#' ```
#'
#' @section Arguments:
#' * `path`: For `package_cache$new()` the location of the cache. For other
#' functions the location of the file inside the cache.
#' * `...`: Extra attributes to search for. They have to be named.
#' * `.list`: Extra attributes to search for, they have to in a named list.
#' * `file`: Path to the file to add.
#' * `url`: URL attribute. This is used to update the file, if requested.
#' * `sha256`: SHA256 hash of the file.
#' * `on_progress`: Callback to create progress bar. Passed to internal
#' function `http_get()`.
#' * `target`: Path to copy the (first) to hit to.
#' * `urls`: Character vector or URLs to try to download the file from.
#' * `http_headers`: HTTP headers to add to all HTTP queries.
#'
#' @section Details:
#'
#' `package_cache$new()` attaches to the cache at `path`. (By default
#' a platform dependent user level cache directory.) If the cache does
#' not exists, it creates it.
#'
#' `pc$list()` lists all files in the cache, returns a data frame with all the
#' default columns, and potentially extra columns as well.
#'
#' `pc$find()` list all files that match the specified criteria (`fullpath`,
#' `path`, `package`, etc.). Custom columns can be searched for as well.
#'
#' `pc$copy_to()` will copy the first matching file from the cache to
#' `target`. It returns the data frame of _all_ matching records, invisibly.
#' If no file matches, it returns an empty (zero-row) data frame.
#'
#' `pc$add()` adds a file to the cache.
#'
#' `pc$add_url()` downloads a file and adds it to the cache.
#'
#' `pc$async_add_url()` is the same, but it is asynchronous.
#'
#' `pc$copy_or_add()` works like `pc$copy_to()`, but if the file is not in
#' the cache, it tries to download it from one of the specified URLs first.
#'
#' `pc$async_copy_or_add()` is the same, but asynchronous.
#'
#' `pc$update_or_add()` is like `pc$copy_to_add()`, but if the file is in
#' the cache it tries to update it from the urls, using the stored ETag to
#' avoid unnecessary downloads.
#'
#' `pc$async_update_or_add()` is the same, but it is asynchronous.
#'
#' `pc$delete()` deletes the file(s) from the cache.
#'
#' @importFrom R6 R6Class
#'
#' @export
#' @examples
#'
#' ## Although package_cache usually stores packages, it may store
#' ## arbitrary files, that can be search by metadata
#' pc <- package_cache$new(path = tempfile())
#' pc$list()
#'
#' cat("foo\n", file = f1 <- tempfile())
#' cat("bar\n", file = f2 <- tempfile())
#' pc$add(f1, "/f1")
#' pc$add(f2, "/f2")
#' pc$list()
#' pc$find(path = "/f1")
#' pc$copy_to(target = f3 <- tempfile(), path = "/f1")
#' readLines(f3)
package_cache <- R6Class(
"package_cache",
public = list(
initialize = function(path = NULL) {
path <- path %||% get_user_cache_dir()$pkg
assert_that(is_path(path))
private$path <- path
create_empty_db_file_if_needed(path)
invisible(self)
},
list = function() {
l <- private$lock(exclusive = FALSE)
on.exit(filelock::unlock(l), add = TRUE)
dbfile <- get_db_file(private$path)
read_db_rds(dbfile)
},
find = function(..., .list = NULL) {
self$copy_to(NULL, ..., .list = .list)
},
copy_to = function(target, ..., .list = NULL) {
l <- private$lock(exclusive = FALSE)
on.exit(filelock::unlock(l), add = TRUE)
res <- private$find_locked(..., .list = .list)
if (!is.null(target) && nrow(res) >= 1) {
mkdirp(dirname(target))
file.copy(res$fullpath[1], target, overwrite = TRUE)
}
res
},
add = function(
file,
path,
sha256 = shasum256(file),
...,
.list = NULL,
.headers = NULL
) {
assert_that(is_existing_file(file))
l <- private$lock(exclusive = TRUE)
on.exit(filelock::unlock(l), add = TRUE)
dbfile <- get_db_file(private$path)
db <- read_db_rds(dbfile)
extra <- c(list(...), .list)
# updates for unexpected PPM binaries and sources
# need to update 'path', 'platform', 'sha256'
if (is.list(.headers)) {
.headers <- .headers[[1]]
}
.headers <- tolower(.headers)
if ("x-repository-type: rspm" %in% .headers) {
fields <- update_fields_for_ppm_download(path, extra, .headers)
path <- fields$path
extra <- fields$extra
}
idx <- find_in_data_frame(
db,
path = path,
sha256 = sha256,
.list = extra
)
target <- file.path(private$path, path)
mkdirp(dirname(target))
file.copy(file, target, overwrite = TRUE)
db <- append_to_data_frame(
db,
fullpath = target,
path = path,
sha256 = null2na(sha256),
.list = extra
)
save_rds(db, dbfile)
db[nrow(db), ]
},
## Just download a file from an url and add it
## Returns a deferred value
async_add_url = function(
url,
path,
...,
.list = NULL,
on_progress = NULL,
http_headers = NULL
) {
self
private
url
path
list(...)
.list
on_progress
http_headers
target <- tempfile()
download_file(
url,
target,
on_progress = on_progress,
headers = http_headers
)$then(function(res) {
headers <- curl::parse_headers(res$response$headers, multiple = TRUE)
self$add(
target,
path,
url = url,
etag = res$etag,
...,
sha256 = shasum256(target),
.list = .list,
.headers = headers
)
})$finally(function(x) unlink(target, recursive = TRUE))
},
add_url = function(
url,
path,
...,
.list = NULL,
on_progress = NULL,
http_headers = NULL
) {
synchronise(self$async_add_url(
url,
path,
...,
.list = .list,
on_progress = on_progress,
http_headers = http_headers
))
},
## If the file is not in the cache, then download it and add it.
async_copy_or_add = function(
target,
urls,
path,
sha256 = NULL,
...,
.list = NULL,
on_progress = NULL,
http_headers = NULL
) {
self
private
target
urls
path
sha256
list(...)
.list
on_progress
http_headers
etag <- tempfile()
async_constant()$then(
function() self$copy_to(target, url = urls[1], ..., .list = .list)
)$then(function(res) {
if (!nrow(res)) {
download_one_of(
urls,
target,
on_progress = on_progress,
headers = http_headers
)$then(function(d) {
headers <- curl::parse_headers(d$response$headers, multiple = TRUE)
sha256 <- shasum256(target)
self$add(
target,
path,
url = d$url,
etag = d$etag,
sha256 = null2na(sha256),
...,
.list = .list,
.headers = headers
)
})$then(function(x) add_attr(x, "action", "Got"))
} else {
add_attr(res, "action", "Had")
}
})$finally(function(x) unlink(etag, recursive = TRUE))
},
copy_or_add = function(
target,
urls,
path,
sha256 = NULL,
...,
.list = NULL,
on_progress = NULL,
http_headers = NULL
) {
synchronise(self$async_copy_or_add(
target,
urls,
path,
sha256,
...,
.list = .list,
on_progress = on_progress,
http_headers = http_headers
))
},
## Like copy_to_add, but we always try to update the file, from
## the URL, and if the update was successful, we update the file
## in the cache as well
async_update_or_add = function(
target,
urls,
path,
sha256 = NULL,
...,
.list = NULL,
on_progress = NULL,
http_headers = NULL
) {
self
private
target
urls
path
sha256
list(...)
.list
on_progress
http_headers
async_constant()$then(
function() {
self$copy_to(target, url = urls[1], path = path, ..., .list = .list)
}
)$then(function(res) {
if (!nrow(res)) {
## Not in the cache, download and add it
download_one_of(
urls,
target,
on_progress = on_progress,
headers = http_headers
)$then(function(d) {
headers <- curl::parse_headers(d$response$headers, multiple = TRUE)
sha256 <- shasum256(target)
self$add(
target,
path,
url = d$url,
etag = d$etag,
sha256 = null2na(sha256),
...,
.list = .list,
.headers = headers
)
})$then(function(x) add_attr(x, "action", "Got"))
} else {
## In the cache, check if it is current
cat(res$etag, file = etag <- tempfile())
download_one_of(
urls,
target,
etag_file = etag,
on_progress = on_progress,
headers = http_headers
)$then(function(d) {
if (d$response$status_code != 304) {
## No current, update it
headers <- curl::parse_headers(
d$response$headers,
multiple = TRUE
)
sha256 <- shasum256(target)
x <- self$add(
target,
path,
url = d$url,
etag = d$etag,
sha256 = null2na(sha256),
...,
.list = .list,
.headers = headers
)
add_attr(x, "action", "Got")
} else {
## Current, nothing to do
add_attr(res, "action", "Current")
}
})$finally(function(x) unlink(etag, recursive = TRUE))
}
})
},
update_or_add = function(
target,
urls,
path,
...,
.list = NULL,
on_progress = NULL,
http_headers = NULL
) {
synchronise(self$async_update_or_add(
target,
urls,
path,
...,
.list = .list,
on_progress = on_progress,
http_headers = http_headers
))
},
delete = function(..., .list = NULL) {
l <- private$lock(exclusive = TRUE)
on.exit(filelock::unlock(l), add = TRUE)
dbfile <- get_db_file(private$path)
pkgs <- c(list(...), .list)
if (length(pkgs) == 0) {
files <- list.files(private$path, recursive = TRUE, full.names = TRUE)
files <- setdiff(files, get_lock_file(private$path))
unlink(files, recursive = TRUE, force = TRUE)
unlink(dbfile, force = TRUE)
} else {
db <- read_db_rds(dbfile)
idx <- find_in_data_frame(db, .list = pkgs)
if (length(idx) != 0) {
unlink(file.path(private$path, db$path[idx]))
save_rds(db[-idx, ], dbfile)
}
}
invisible()
}
),
## ----------------------------------------------------------------------
private = list(
path = NULL,
lock = function(exclusive = TRUE, ...) {
lockfile <- get_lock_file(private$path)
filelock::lock(lockfile, exclusive = exclusive, ...)
},
find_locked = function(..., .list = NULL) {
dbfile <- get_db_file(private$path)
db <- read_db_rds(dbfile)
idx <- find_in_data_frame(db, ..., .list = .list)
db[idx, ]
}
)
)
## ------------------------------------------------------------------------
## Internal functions
get_db_file <- function(path) {
file.path(path, ".db.rds")
}
get_lock_file <- function(path) {
file.path(path, ".db.lock")
}
read_db_rds <- function(dbfile) {
tryCatch(
suppressWarnings(readRDS(dbfile)),
error = function(err) {
cond <- new_error(
"Failed to read the package cache database from ",
encodeString(dbfile, quote = "`"),
". The cache file is possibly corrupt, call ",
"`pkgcache::pkg_cache_delete_files()` or `pak::cache_clean()` ",
"to reset the cache, and then try again."
)
cond$dbfile <- dbfile
class(cond) <- c("pkgcache_corrupt_db_error", class(cond))
throw(cond, parent = err)
}
)
}
create_empty_db_file_if_needed <- function(path) {
mkdirp(path)
dbfile <- get_db_file(path)
if (file.exists(dbfile)) {
return()
}
lockfile <- get_lock_file(path)
df <- make_empty_db_data_frame()
l <- filelock::lock(lockfile)
on.exit(filelock::unlock(l))
save_rds(df, dbfile)
}
make_empty_db_data_frame <- function() {
data.frame(
stringsAsFactors = FALSE,
fullpath = character(),
path = character(),
package = character(),
url = character(),
etag = character(),
sha256 = character()
)
}
update_fields_for_ppm_download <- function(path, extra, headers) {
res <- list(path = path, extra = extra)
pkg_type <- grep("^x-package-type:", headers, value = TRUE)[1]
if (is.na(pkg_type)) {
return(res)
}
pkg_type <- sub("^x-package-type: ?", "", pkg_type)
if (pkg_type == "binary") {
# Got a binary package, check what kind
bin_tag <- grep("x-package-binary-tag:", headers, value = TRUE)[1]
if (is.na(bin_tag)) {
return(res)
}
bin_tag <- sub("x-package-binary-tag: ?", "", bin_tag)
synchronise(async_get_ppm_status())
rver <- strsplit(bin_tag, "-")[[1]][[1]]
binurl <- strsplit(bin_tag, "-")[[1]][[2]]
if (!binurl %in% pkgenv$ppm_distros$binary_url) {
return(res)
}
# fix platform if neeeded
if (!is.null(extra$platform) && extra$platform == "source") {
wdist <- match(binurl, pkgenv$ppm_distros$binary_url)
distro <- pkgenv$ppm_distros$distribution[wdist]
release <- pkgenv$ppm_distros$release[wdist]
res$extra$platform <- linux_platform_with_suffix(
paste0(distro, "-", release)
)
}
# fix path if needed
if (dirname(path) == "src/contrib") {
res$path <- paste0(
"src/contrib/",
res$extra$platform %||% current_r_platform(),
"/",
rver,
"/",
basename(path)
)
}
} else {
# Got a source package
# Fix platform if needed
if (!is.null(extra$platform) && extra$platform != "source") {
res$extra$platform <- "source"
}
# Fix path if needed
if (dirname(path) != "src/contrib") {
res$path <- paste0("src/contrib/", basename(path))
}
}
res
}