diff --git a/R/api.R b/R/api.R index b325595..1ac3ca0 100644 --- a/R/api.R +++ b/R/api.R @@ -42,7 +42,7 @@ target_post_dataset <- function(req, res) { if (length(missing_cols) > 0) { res$status <- 400L msg <- paste("Missing required columns:", - paste(missing_cols, collapse = ", ")) + paste(missing_cols, collapse = ", ")) return(bad_request_response(msg)) } @@ -101,11 +101,11 @@ target_get_trace <- function(name, filters <- strsplit(filter, "+", fixed = TRUE)[[1]] logger::log_info(paste("Filtering by variables:", paste(filters, collapse = ", "))) - for (f in filters) { - dat <- apply_filter(f, dat, cols) - } + for (f in filters) { + dat <- apply_filter(f, dat, cols) + } } - dat <- dat[dat["biomarker"] == biomarker, ] + dat <- dat[dat["biomarker"] == biomarker,] if (length(disaggregate) > 0) { logger::log_info(paste("Disaggregating by variables:", disaggregate)) groups <- split(dat, eval(parse(text = paste("~", disaggregate)))) @@ -173,7 +173,7 @@ apply_filter <- function(filter, dat, cols) { "not found in data"), code = "BAD_REQUEST", status_code = 400L) } - dat[dat[filter_var] == filter_level, ] + dat[dat[filter_var] == filter_level,] } bad_request_response <- function(msg) { @@ -191,5 +191,10 @@ get_or_create_session_id <- function(req) { } generate_session_id <- function() { - rawToChar(as.raw(sample(c(65:90, 97:122), 10, replace = TRUE))) + tolower(rawToChar(sample(c(as.raw(sample(c(65:90, 97:122), + 5, + replace = TRUE)), + as.raw(sample(48:57, + 5, + replace = TRUE)))))) } diff --git a/R/router.R b/R/router.R index e76e495..60fb632 100644 --- a/R/router.R +++ b/R/router.R @@ -1,4 +1,5 @@ -build_routes <- function(cookie_key = plumber::random_cookie_key()) { +build_routes <- function(cookie_key = plumber::random_cookie_key(), + cache = cachem::cache_mem(max_age = 60)) { if (!dir.exists("uploads")) { dir.create("uploads") } @@ -11,12 +12,17 @@ build_routes <- function(cookie_key = plumber::random_cookie_key()) { res$setHeader("Access-Control-Allow-Origin", req$HTTP_ORIGIN) res$setHeader("Access-Control-Allow-Credentials", "true") } + + id <- as.character(req$session$id) + cache$set(id, TRUE) + prune_inactive_sessions(cache) value }) pr$registerHooks(plumber::session_cookie(cookie_key, name = "serovizr", - path = "/")) + path = "/", + expiration = 60)) pr$handle(get_root()) pr$handle(get_version()) @@ -68,3 +74,13 @@ get_trace <- function() { filter = "string"), returning = porcelain::porcelain_returning_json("DataSeries")) } + +prune_inactive_sessions <- function(cache) { + active_sessions <- cache$keys() + subdirectories <- list.files("uploads") + old_sessions <- setdiff(subdirectories, active_sessions) + if (length(old_sessions) > 0) { + logger::log_info("Cleaning up expired sessions") + lapply(old_sessions, function(x) fs::dir_delete(file.path("uploads", x))) + } +}