Uncompressing input file errs on every second upload

I'm trying to handle large compressed file inputs. The uploaded file is uncompressed and stored in a temporary directory before being postprocessed internally to get usable data for future analyses. I need to clear the input files everytime the user upload data so that only the new data are processed.

For some reason I'm getting the following error on every second upload (first upload works, second fails, third works, etc.):

tar.exe: Error opening archive: Failed to open 'C:\Users\L1156319\AppData\Local\Temp\RtmpGCglVL/6ab060975b2065643d1f20a4/0.tar'
Avis dans utils::untar(file$datapath, exdir = private$.dir) :
  ‘tar.exe -xf "C:\Users\L1156319\AppData\Local\Temp\RtmpGCglVL/6ab060975b2065643d1f20a4/0.tar" -C "C:/Users/L1156319/AppData/Local/Temp/RtmpGCglVL"’ returned error code 1

I'd very much appreciate any help because I don't understand what's happening. The file is there but can't be open on every 2 upload. The problem is related to unlink(recursive = TRUE). I do need to remove files recursively though.

Here's a minimal reproducible example:

DataHandler <- R6::R6Class(
  classname = "DataHandler",
  private = list(
    .dir = NULL,
    .file = NULL,
    .files = character()
  ),
  public = list(
    read = function(file) {
      if (length(private$.files) != 0L) {
        self$clear()
      }
      private$.dir <- tempdir()
      private$.file <- file
      # print(file$datapath)
      utils::untar(file$datapath, exdir = private$.dir)
      private$.files <- fs::dir_ls(private$.dir, regexp = "\\.gz$")
    },
    clear = function() {
      private$.file <- NULL
      private$.files <- character()
      unlink(private$.dir, recursive = TRUE)
    }
  )
)


ui <- fluidPage(
  fileInput(
    "file",
    label = "Load data",
    buttonLabel = "Browse",
    placeholder = "No file selected",
    accept = ".tar"
  )
)

server <- function(input, output, session) {
  r6 <- DataHandler$new()
  observeEvent(input$file, {
    r6$read(input$file)
  })
}

shinyApp(ui, server)

I couldn't reproduce your problem because my tempdir() isn't empty, but I'm fairly what you're experiencing is because unlink(private$.dir, recursive = TRUE) is deleting the file you uploaded before it is processed, because that is stored in tempdir() as well. You only have one tempdir() per session, unlike tempfile()which can create an infinite number of temporary paths.

Doing something like this should fix it:

private$.dir  <- tempfile()
dir.create(private$.dir, recursive = TRUE)