diff --git a/CLAUDE.md b/CLAUDE.md index 12dad73..e1b0ad2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -7,9 +7,12 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co `climateData` is an R package that wraps access to [ClimateNA](https://climatena.ca/) outputs for North America. The package itself does not bundle raster data; instead, `inst/extdata/` contains a SQLite lookup database and a GeoPackage of tile polygons, and raw raster archives are pulled on -demand from Google Drive. The `data-raw/` scripts (run by the maintainer on a Windows box with the -ClimateNA executable) regenerate those archives and the SQLite index; they are excluded from the -built package via `.Rbuildignore` and should not be treated as user-facing code. +demand over HTTPS from a public bucket on Arbutus (S3-compatible object storage). The +`data-raw/pipeline/` targets pipeline (run by the maintainer on Linux compute nodes, ClimateNA in +Docker) regenerates those archives and the SQLite index, and builds a new release's DEM tiles +(`R/pipelineDem.R`, `data-raw/pipeline/R/dem.R`; the tile polygons in `tiles.gpkg` never change). +`data-raw/` is excluded from the built package via `.Rbuildignore` and should not be treated as +user-facing code. ## Common commands @@ -34,9 +37,9 @@ testthat::test_file("tests/testthat/test-prepClimateLayers.R") devtools::load_all() ``` -Most tests `skip_on_ci()` and `skip_on_cran()` because they require interactive `googledrive` -auth and multi-GB downloads from Google Drive. Expect the CI test run to be effectively empty; -real validation requires running `devtools::test()` locally with credentials in `.secrets/`. +Most tests `skip_on_ci()` and `skip_on_cran()` because they need multi-GB downloads from the +bucket. Expect the CI test run to be effectively empty; real validation requires running +`devtools::test()` locally. `makeClimateDEM` tests are Windows-only (ClimateNA rejects DEMs written on non-Windows platforms due to line-ending differences — see `rewrite_asc()`). @@ -55,8 +58,9 @@ climate variables, it: (seasonal), two trailing digits → M (monthly), otherwise Y (yearly). 2. Consolidates M/S/Y requests into the combined `MSY` archive when all three are needed for the same type (avoids downloading three overlapping zips). -3. Calls `getClimateURLs()` → `getClimateTiles()` to pull archives from Google Drive via - `reproducible::preProcess()`. URLs are looked up in the bundled SQLite +3. Calls `getClimateURLs()` → `getClimateTiles()` to download archives from the bucket with + httr2 (`.fetchArchive()` in `R/download.R`), each checked against its MD5 in the index's + `archives` table. URLs (`release.base_url` + `key`) are looked up in the bundled SQLite (`ClimateNA_tiles_sqlite()`); the schema differs per `type` and is defined in `ClimateNA_sql()`. 4. Calls `buildClimateMosaics()` / `buildClimateMosaicsNormals()` to build GDAL VRTs per tile and warp them to per-year/period GeoTIFFs — this is the CPU-heavy step and runs in parallel (see @@ -89,26 +93,31 @@ serialization cheap. `stopForInvalidBackend()` centralizes the error path. ### SQLite schema -The index at `inst/extdata/ClimateNA_tiles.sqlite` holds four main tables — -`historical`, `historical_normals`, `future`, `future_normals`. `gid` is the Google Drive -file ID; archives are grouped by decade, so many rows share a `gid`. `sqlite_connect_db()` +The index at `inst/extdata/ClimateNA_tiles.sqlite` holds four tile tables, +`tiles_historical`, `tiles_historical_normals`, `tiles_future`, `tiles_future_normals`: one row +per tile, subset and year or period, referring to its zip in the `archives` table by id +(`archive`). Archives are grouped by decade, so many rows share one. A view named for each type +(`historical`, ...) joins them back into the columns readers use (`zipfile`, `archived`, `key`, +`uploaded`); `ClimateNA_sql()` reads the view, and writers append to `tiles_`. `key` is the +archive's object key in the bucket (its URL is `release.base_url` + `/` + `key`). Storing the +paths once per archive, not once per row, keeps the index at 20 MB, from 52 MB. +`sqlite_connect_db()` sets a 60s busy timeout before anything else; lookups (`readonly = TRUE`) open the file read-only, and writing connections switch a file to WAL only when they create it. The shipped index is left in rollback-journal mode (`build_index()` in `data-raw/pipeline/R/index.R`), so read-only lookups work from a library folder the user cannot write to. -Optional `checksums_` tables are created by `checksums_sql()` when a maintainer runs the -`data-raw/` checksum loops; they may or may not be present in a given copy of the bundled -database. Don't assume they exist when querying. +Indexes from before climateData 2.3.0 may hold `checksums_` tables, written by the +Windows-era build scripts (removed in 2.3.0); the pipeline's index has none. Don't assume they +exist when querying. -**The declared schemas in `ClimateNA_sql()` / `checksums_sql()` are not authoritative for -what's actually stored.** `dbCreateTable()` emits e.g. `year CHARACTER` / `created DATETIME`, -but the `data-raw/` scripts populate rows via `dplyr::rows_append(copy = TRUE, in_place = TRUE)` -which can map R column types to its own SQLite types (e.g. R `integer` → `INTEGER`, R `POSIXct` -→ `TIMESTAMP`, R `character` → `TEXT`) — so the PRAGMA-reported column types in the shipped -file can diverge from the R schema strings. When changing a schema, inspect the bundled file -with `PRAGMA table_info()` before writing migration code; it may already be in the -target state. +**The declared schemas in `ClimateNA_sql()` are not authoritative for older indexes.** The pipeline creates each tile table with `ClimateNA_sql()` (`dbCreateTable()` +emits e.g. `year CHARACTER` / `created DATETIME`) and fills it with `DBI::dbAppendTable()`, so +its declared types are the templates'. Indexes from before 2.3.0 were filled with +`dplyr::rows_append(copy = TRUE, in_place = TRUE)`, which maps R column types to its own SQLite +types (e.g. R `integer` → `INTEGER`, R `POSIXct` → `TIMESTAMP`). When changing a schema, inspect +the bundled file with `PRAGMA table_info()` before writing migration code; it may already be +in the target state. ### Allowed variables @@ -119,10 +128,10 @@ discovery. `available()` exposes the allowed years, periods, GCMs, and SSPs. ## Dependencies worth knowing -- `reproducible` (≥ 2.0.8) — `preProcess()`, `prepInputs()`, `postProcessTo()`, `Cache()`. - Many of the long-running behaviors (downloads, reprojection, masking) are delegated here. +- `reproducible` (≥ 2.0.8) — `postProcessTo()`, `Cache()`, `checkPath()`. Reprojection, + masking and caching are delegated here; the archive downloads are not. - `SpaDES.tools` comes from the `development` branch (see `Remotes:` in DESCRIPTION); the r-universe build picks this up automatically, but plain `install.packages()` will not. -- `googledrive` and `httr2` are Imports because `getClimateTiles()` and `makeClimateDEM()` need - them to download, and reproducible has both only in Suggests. httr2 is never called directly; - `R/imports.R` imports `httr2::request` so that R CMD check accepts it in Imports. +- `httr2` downloads the archives and `makeClimateDEM()`'s GTOPO30 DEM + (`climateData/dem/gtopo30Canada.zip` in the bucket) through `.downloadArchive()`. Nothing in + the package uses Google Drive. diff --git a/DESCRIPTION b/DESCRIPTION index b5a11a7..3011d33 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -26,9 +26,8 @@ Imports: fs, future.apply, glue, - googledrive, hms, - httr2, + httr2 (>= 1.0.4), methods, parallel, parallelly, @@ -53,7 +52,8 @@ Suggests: sys, targets, testthat (>= 3.0.0), - withr + withr, + yaml VignetteBuilder: knitr, rmarkdown diff --git a/NAMESPACE b/NAMESPACE index 649106a..12e8be3 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,6 +1,5 @@ # Generated by roxygen2: do not edit by hand -export(ClimateNA_path) export(ClimateNA_sql) export(ClimateNA_tiles_gpkg) export(ClimateNA_tiles_sqlite) @@ -12,7 +11,6 @@ export(calcCumMDC) export(calcMDC) export(calcStackLayersType) export(checkCalcStackLayers) -export(checksums_sql) export(climateDataRelease) export(climateLayers) export(climateStacksByPeriod) @@ -58,7 +56,6 @@ importFrom(dplyr, ) importFrom(fs,dir_ls) importFrom(future.apply,future_lapply) -importFrom(httr2,request) importFrom(parallel, parLapply, stopCluster @@ -69,9 +66,7 @@ importFrom(reproducible, .robustDigest, Cache, checkPath, - postProcessTo, - preProcess, - prepInputs + postProcessTo ) importFrom(sf, gdal_utils, @@ -103,6 +98,5 @@ importFrom(terra, importFrom(tools,file_path_sans_ext) importFrom(utils, getFromNamespace, - packageVersion, write.table ) diff --git a/NEWS.md b/NEWS.md index 4ed045c..a7cac39 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,28 @@ # climateData (development version) +- The climate archives now download over HTTPS from a public bucket on Arbutus, the Digital + Research Alliance of Canada's object storage. No Google account or `googledrive::drive_auth()` + is needed, so downloads no longer fail on Google logins or service accounts (#13). Each + download is checked against the MD5 in the tile index, and downloaded once more if it doesn't + match. A partial download left by an interrupted session is removed by a later one (after a + day). climateData 2.2.3 and earlier download from Google Drive, which will stop serving the + archives. +- `makeClimateDEM()` downloads its GTOPO30 elevation data from the same bucket, checked against + its MD5. climateData no longer depends on googledrive. +- `getClimateURLs()` returns, for each tile, a data frame of archive URLs and MD5s instead of + Google Drive IDs. +- The tile index stores each archive's object key and path once, in its `archives` table, rather + than in every row: it is 20 MB instead of 52 MB. `historical`, `future` and the normals tables + are now views with the same columns, read as before through `ClimateNA_sql()`. +- The tile index names each archive by its object key in the bucket (`key`, replacing `gid`); the + bucket's URL is in the `release` table (`base_url`) and each archive's MD5 in `archives`. +- `rewrite_asc()` writes Windows (CRLF) line endings on every platform. On Linux and macOS it + wrote LF, which ClimateNA rejects. +- `ClimateNA_path()` and `checksums_sql()` are removed: only the old Windows build scripts used + them. Those scripts (`data-raw/01` to `06`) are replaced by the data pipeline + (`data-raw/pipeline/`), which now also builds a new release's DEM tiles and reports settings + that differ from `available()`. + - Land cells where ClimateNA writes no values now hold ClimateNA's own values for the nearest land cell it covers within 50 km, computed at the empty cell's elevation (in the 3 arcmin release, a median of 3.5 km away; 90% within 10 km). ClimateNA's future data miss some coastal cells (e.g. diff --git a/R/ClimateNA_createTiles.R b/R/ClimateNA_createTiles.R index c5039a0..95f12f1 100644 --- a/R/ClimateNA_createTiles.R +++ b/R/ClimateNA_createTiles.R @@ -18,7 +18,10 @@ ClimateNA_tiles_gpkg <- function() { system.file("extdata/tiles.gpkg", package = "climateData") } -#' Rewrite a `.asc` raster file to use Windows (CR) line-endings +#' Rewrite a `.asc` raster file to use Windows (CRLF) line-endings +#' +#' ClimateNA reads DEM files only with Windows line endings. The file is rewritten with CRLF line +#' endings on every platform. #' #' @param f character. path to a `.asc` raster file #' @@ -26,7 +29,14 @@ ClimateNA_tiles_gpkg <- function() { #' @importFrom utils write.table rewrite_asc <- function(f) { readLines(f, warn = FALSE) |> - utils::write.table(f, row.names = FALSE, col.names = FALSE, quote = FALSE, append = FALSE) + utils::write.table( + f, + row.names = FALSE, + col.names = FALSE, + quote = FALSE, + append = FALSE, + eol = "\r\n" + ) return(invisible(NULL)) } @@ -40,41 +50,6 @@ tileID <- function(file) { basename(file) |> sub("^can_dem_", "", x = _) |> sub("[.]asc$", "", x = _) |> as.integer() } -#' Construct target output paths for ClimateNA data -#' -#' @param dataPath character. path to ClimateNA data directory. -#' -#' @template ClimateNA_tile -#' -#' @template ClimateNA_type -#' -#' @template ClimateNA_msy -#' -#' @template ClimateNA_gcmssp -#' -#' @return character string representing the path to the target output directory -#' -#' @export -ClimateNA_path <- function(dataPath, tile = NULL, type = NULL, msy = NULL, gcm = NULL, ssp = NULL) { - stopifnot(type %in% .allowedClimateTypes) - - MSY <- switch(msy, MSY = "all", M = "monthly", S = "seasonal", Y = "yearly") - switch( - type, - historical = file.path(dataPath, "historical", MSY, tile), - historical_normals = file.path(dataPath, "historical", "normals", MSY, tile), - future = file.path(dataPath, "future", paste0(gcm, "_ssp", ssp), MSY, tile), - future_normals = file.path(dataPath, "future", paste0(gcm, "_ssp", ssp), "normals", MSY, tile) - ) |> - normalizePath(mustWork = FALSE) |> - (function(x) { - if (!dir.exists(x)) { - dir.create(x, recursive = TRUE) - } - x - })() -} - #' SQLite `file:` URI that opens `dbfile` immutably #' #' POSIX paths give `file:///home/...`; Windows paths give `file:///C:/...` (backslashes become `/`, the @@ -128,7 +103,7 @@ sqlite_connect_db <- function(dbfile, readonly = FALSE) { DBI::dbExecute(db, "PRAGMA synchronous = normal") if (isTRUE(newDb)) { ## WAL allows concurrent writers while building. Switch back to `journal_mode = DELETE` before the - ## file is shipped in inst/extdata (see data-raw/06-archive_fingerprints.R): a WAL file creates + ## file is shipped in inst/extdata (the pipeline's build_index() does): a WAL file creates ## `-wal`/`-shm` files beside it even when only read. DBI::dbExecute(db, "PRAGMA journal_mode = WAL") } @@ -137,7 +112,13 @@ sqlite_connect_db <- function(dbfile, readonly = FALSE) { return(db) } -#' Connect to ClimateNA tile and checksums database +#' Connect to a table of the ClimateNA tile index +#' +#' A type's rows are in the table `tiles_`, each referring to its archive (the `archives` +#' table) by id. The view named for the type gives each row with its archive's `zipfile`, +#' `archived`, `key` and `uploaded` (the archive's `verified`), and is what `df` reads. With +#' `readonly = FALSE`, the tables and the view are created when missing; rows are written to +#' `tiles_`. #' #' @template ClimateNA_dbfile #' @@ -148,7 +129,7 @@ sqlite_connect_db <- function(dbfile, readonly = FALSE) { #' #' @return named list containing: #' - `db`, the database connection; -#' - `df`, a lazy `tbl_dbi` object (see `dbplyr`). +#' - `df`, a lazy `tbl_dbi` object of the type's view (see `dbplyr`). #' #' @export #' @importFrom DBI dbCreateTable dbExecute dbExistsTable @@ -165,130 +146,16 @@ ClimateNA_sql <- function(dbfile, type, readonly = FALSE) { returned <- FALSE on.exit(if (!returned) DBI::dbDisconnect(db), add = TRUE) - df_template <- switch( - type, - historical_normals = c( - id = "INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE", - msy = "CHARACTER", ## one of: 'M', 'S', 'Y', 'MSY' - period = "CHARACTER", ## climate period - tileid = "INTEGER", ## tile ID - created = "DATETIME", ## timestamp of when tile set was created using ClimateNA - zipfile = "CHARACTER", ## relative file path - archived = "DATETIME", ## timestamp of when tile set archive was created (zipped) - gid = "CHARACTER", ## google drive file id; archives built by decade, so there will be dupe gids - uploaded = "DATETIME", ## timestamp of when archive uploaded to google drive - climatena_version = "CHARACTER" ## ClimateNA version that produced this year/period - ), - future_normals = c( - id = "INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE", - gcm = "CHARACTER", ## climate scenario GCM - ssp = "CHARACTER", ## climate scenario SSP - msy = "CHARACTER", ## one of: 'M', 'S', 'Y', 'MSY' - period = "CHARACTER", ## climate period - tileid = "INTEGER", ## tile ID - created = "DATETIME", ## timestamp of when tile set was created using ClimateNA - zipfile = "CHARACTER", ## relative file path - archived = "DATETIME", ## timestamp of when tile set archive was created (zipped) - gid = "CHARACTER", ## google drive file id; archives built by decade, so there will be dupe gids - uploaded = "DATETIME", ## timestamp of when archive uploaded to google drive - climatena_version = "CHARACTER" ## ClimateNA version that produced this year/period - ), - historical = c( - id = "INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE", - msy = "CHARACTER", ## one of: 'M', 'S', 'Y', 'MSY' - year = "INTEGER", ## climate year - tileid = "INTEGER", ## tile ID - created = "DATETIME", ## timestamp of when tile set was created using ClimateNA - zipfile = "CHARACTER", ## relative file path - archived = "DATETIME", ## timestamp of when tile set archive was created (zipped) - gid = "CHARACTER", ## google drive file id; archives built by decade, so there will be dupe gids - uploaded = "DATETIME", ## timestamp of when archive uploaded to google drive - climatena_version = "CHARACTER" ## ClimateNA version that produced this year/period - ), - future = c( - id = "INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE", - gcm = "CHARACTER", ## climate scenario GCM - ssp = "CHARACTER", ## climate scenario SSP - msy = "CHARACTER", ## one of: 'M', 'S', 'Y', 'MSY' - year = "INTEGER", ## climate year - tileid = "INTEGER", ## tile ID - created = "DATETIME", ## timestamp of when tile set was created using ClimateNA - zipfile = "CHARACTER", ## relative file path - archived = "DATETIME", ## timestamp of when tile set archive was created (zipped) - gid = "CHARACTER", ## google drive file id; archives built by decade, so there will be dupe gids - uploaded = "DATETIME", ## timestamp of when archive uploaded to google drive - climatena_version = "CHARACTER" ## ClimateNA version that produced this year/period - ) - ) - - tbl <- type - - if (!isTRUE(readonly) && !DBI::dbExistsTable(db, tbl)) { - DBI::dbCreateTable(db, tbl, df_template) + if (!isTRUE(readonly)) { + .tilesCreate(db, type) } - df <- dplyr::tbl(db, tbl) + df <- dplyr::tbl(db, type) returned <- TRUE return(list(db = db, df = df)) } -#' @export -#' @rdname ClimateNA_sql -checksums_sql <- function(dbfile, type) { - db <- sqlite_connect_db(dbfile) - - df_template <- switch( - type, - historical_normals = c( - id = "INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE", - msy = "CHARACTER", ## one of: 'M', 'S', 'Y', 'MSY' - period = "CHARACTER", ## climate period - tileid = "INTEGER", ## tile ID - filename = "CHARACTER", ## file name - filehash = "CHARACTER" ## file hash (checksum) - ), - future_normals = c( - id = "INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE", - gcm = "CHARACTER", ## climate scenario GCM - ssp = "CHARACTER", ## climate scenario SSP - msy = "CHARACTER", ## one of: 'M', 'S', 'Y', 'MSY' - period = "CHARACTER", ## climate period - tileid = "INTEGER", ## tile ID - filename = "CHARACTER", ## file name - filehash = "CHARACTER" ## file hash (checksum) - ), - historical = c( - id = "INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE", - msy = "CHARACTER", ## one of: 'M', 'S', 'Y', 'MSY' - year = "INTEGER", ## climate year - tileid = "INTEGER", ## tile ID - filename = "CHARACTER", ## file name - filehash = "CHARACTER" ## file hash (checksum) - ), - future = c( - id = "INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE", - gcm = "CHARACTER", ## climate scenario GCM - ssp = "CHARACTER", ## climate scenario SSP - msy = "CHARACTER", ## one of: 'M', 'S', 'Y', 'MSY' - year = "INTEGER", ## climate year - tileid = "INTEGER", ## tile ID - filename = "CHARACTER", ## file name - filehash = "CHARACTER" ## file hash (checksum) - ) - ) - - tbl <- paste0("checksums_", type) - - if (!DBI::dbExistsTable(db, tbl)) { - DBI::dbCreateTable(db, tbl, df_template) - } - - df <- dplyr::tbl(db, tbl) - - return(list(db = db, df = df)) -} - ## The data release behind an index: one row, written by the pipeline (data-raw/pipeline/) and ## read by climateDataRelease(). Written with explicit SQL types. .releaseCreate <- function(db) { @@ -298,6 +165,7 @@ checksums_sql <- function(dbfile, type) { release_id TEXT NOT NULL, -- e.g. cna-v7.70-3arcmin climatena_version TEXT NOT NULL, -- ClimateNA release that produced the data dem_resolution TEXT NOT NULL, -- e.g. 3arcmin, 1arcmin + base_url TEXT NOT NULL, -- the bucket's URL; an archive's URL is base_url/key created REAL NOT NULL -- epoch seconds )" ) @@ -305,14 +173,18 @@ checksums_sql <- function(dbfile, type) { } .releaseWrite <- function(db, df) { + cols <- c("release_id", "climatena_version", "dem_resolution", "base_url", "created") DBI::dbExecute(db, "DELETE FROM release") DBI::dbExecute( db, - "INSERT INTO release (release_id, climatena_version, dem_resolution, created) VALUES (?, ?, ?, ?)", - params = unname(as.list(df[ - 1, - c("release_id", "climatena_version", "dem_resolution", "created") - ])) + paste0( + "INSERT INTO release (", + paste(cols, collapse = ", "), + ") VALUES (", + paste(rep("?", length(cols)), collapse = ", "), + ")" + ), + params = unname(as.list(df[1, cols])) ) invisible(db) } @@ -375,33 +247,98 @@ checksums_sql <- function(dbfile, type) { invisible(db) } -## One fingerprint per published zip (see data-raw/06-archive_fingerprints.R). +## One fingerprint per published zip, written by the pipeline (build_index() in +## data-raw/pipeline/R/index.R); the tile tables refer to it by id. ## Written with explicit SQL types: dplyr::rows_*() would remap them. -.archivesColumns <- c("gid", "type", "zipfile", "md5", "n_files", "size", "verified") +.archivesColumns <- c("key", "type", "zipfile", "md5", "n_files", "size", "archived", "verified") .archivesCreate <- function(db) { DBI::dbExecute( db, "CREATE TABLE IF NOT EXISTS archives ( - gid TEXT PRIMARY KEY, -- Google Drive file ID - type TEXT NOT NULL, -- historical | historical_normals | future - zipfile TEXT NOT NULL, -- path relative to the ClimateNA data root - md5 TEXT NOT NULL, -- Drive md5Checksum of the published file - n_files INTEGER NOT NULL, -- members in the zip (directory entries excluded) - size REAL NOT NULL, -- bytes - verified REAL -- epoch seconds when it last passed the check; NULL if never + id INTEGER PRIMARY KEY, -- what the tile tables' archive column refers to + key TEXT UNIQUE, -- object key (see release.base_url); NULL in a dry run + type TEXT NOT NULL, -- historical | historical_normals | future | future_normals + zipfile TEXT NOT NULL, -- path below the release, e.g. historical/MSY/39_MSY_2020.zip + md5 TEXT NOT NULL, -- MD5 of the zip (the object's ETag) + n_files INTEGER NOT NULL, -- members in the zip (directory entries excluded) + size REAL NOT NULL, -- bytes + archived REAL, -- when the zip was cut (its modification time, epoch s) + verified REAL -- upload time (epoch s), MD5 and size checked; NULL: dry run )" ) invisible(db) } +## Insert `df`'s rows, or update the row with the same key in place (keeping its id, which the +## tile tables refer to). `archived` and `verified` may be left out (NULL). .archivesUpsert <- function(db, df) { + for (k in c("archived", "verified")) { + if (!k %in% names(df)) { + df[[k]] <- rep(NA_real_, nrow(df)) + } + } + update <- setdiff(.archivesColumns, "key") sql <- paste0( - "INSERT OR REPLACE INTO archives (", + "INSERT INTO archives (", paste(.archivesColumns, collapse = ", "), ") VALUES (", paste(rep("?", length(.archivesColumns)), collapse = ", "), - ")" + ") ON CONFLICT (key) DO UPDATE SET ", + paste0(update, " = excluded.", update, collapse = ", ") ) DBI::dbExecute(db, sql, params = unname(as.list(df[.archivesColumns]))) |> as.integer() } + +## A tile table's columns (tiles_): one row per tile, subset (msy) and year or period, which +## refers to its archive (archives.id); archives are per decade, so many rows share one. +.tilesColumns <- function(type) { + c( + id = "INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE", + if (startsWith(type, "future")) c(gcm = "CHARACTER", ssp = "CHARACTER"), ## the scenario + msy = "CHARACTER", ## one of: 'M', 'S', 'Y', 'MSY' + if (endsWith(type, "_normals")) c(period = "CHARACTER") else c(year = "INTEGER"), + tileid = "INTEGER", ## tile ID + created = "DATETIME", ## when ClimateNA produced this year or period + climatena_version = "CHARACTER", ## the ClimateNA version that produced it + archive = "INTEGER" ## archives.id + ) +} + +## Create the tile table tiles_, the archives table, and the readers' view named for the type: +## each row with its archive's path (zipfile), time (archived), object key (key; see +## release.base_url) and upload time (uploaded, the archive's verified), the columns the tile +## tables held themselves before the index was normalized (in climateData 2.3.0, a third the size). +.tilesCreate <- function(db, type) { + if (!isTRUE(type %in% .allowedClimateTypes)) { + stop("type must be one of ", paste(.allowedClimateTypes, collapse = ", "), call. = FALSE) + } + .archivesCreate(db) + tiles <- paste0("tiles_", type) + cols <- .tilesColumns(type) + if (!DBI::dbExistsTable(db, tiles)) { + DBI::dbCreateTable(db, tiles, cols) + } + own <- setdiff(names(cols), c("created", "climatena_version", "archive")) + select <- c( + paste0("t.", c(own, "created")), + "a.zipfile", + "a.archived", + "a.key", + "a.verified AS uploaded", + "t.climatena_version" + ) + DBI::dbExecute( + db, + paste0( + "CREATE VIEW IF NOT EXISTS ", + type, + " AS SELECT ", + paste(select, collapse = ", "), + " FROM ", + tiles, + " t LEFT JOIN archives a ON a.id = t.archive" + ) + ) + invisible(db) +} diff --git a/R/ClimateNA_useTiles.R b/R/ClimateNA_useTiles.R index ec3bb3f..0cb7d1b 100644 --- a/R/ClimateNA_useTiles.R +++ b/R/ClimateNA_useTiles.R @@ -1,5 +1,5 @@ utils::globalVariables(c( - "gid", "period", "tileid", "year" + "key", "period", "tileid", "year" )) #' Identify ClimateNA tiles overlapping a study area @@ -117,7 +117,8 @@ getNormalsPeriods <- function(type = NULL, tile = NULL, msy = "Y", gcm = NULL, s #' @template ClimateNA_msy #' @template ClimateNA_gcmssp #' -#' @return list of Google Drive ids, with names corresponding the tile ids. +#' @return list of data frames, one per tile (named by tile id), with one row per archive: +#' `url`, the archive's public URL, and `md5`, its MD5 checksum as recorded in the tile index. #' #' @export #' @importFrom data.table .SD as.data.table @@ -138,20 +139,54 @@ getClimateURLs <- function( ssp = ssp ) |> as.data.table() - subsetdt <- climate_dt[, .SD, .SDcols = c("tileid", "gid")] |> unique() + ## a row whose archive is missing from the archives table (a broken index) has no key + lost <- climate_dt[is.na(key)] + if (nrow(lost) > 0) { + when <- if ("year" %in% names(lost)) lost$year else lost$period + stop( + "The tile index ", + ClimateNA_tiles_sqlite(), + " has no archives row for ", + paste(unique(paste("tile", lost$tileid, when, lost$msy)), collapse = ", "), + call. = FALSE + ) + } + subsetdt <- climate_dt[, .SD, .SDcols = c("tileid", "key")] |> unique() + baseUrl <- .indexBaseUrl() + md5 <- .archiveMd5(unique(subsetdt$key)) url <- lapply(unique(subsetdt$tileid), function(t) { - subsetdt[tileid == t, gid] + k <- subsetdt[tileid == t, key] + data.frame(url = paste0(baseUrl, "/", k), md5 = unname(md5[k])) }) names(url) <- unique(subsetdt$tileid) return(url) } +## The MD5 the tile index records for each archive key, named by key. Stops naming any key that the +## index's archives table lacks (a broken index), rather than return NA. +.archiveMd5 <- function(keys, dbfile = ClimateNA_tiles_sqlite()) { + db <- sqlite_connect_db(dbfile, readonly = TRUE) + on.exit(DBI::dbDisconnect(db), add = TRUE) + a <- DBI::dbGetQuery(db, "SELECT key, md5 FROM archives WHERE key = ?", params = list(keys)) + md5 <- stats::setNames(a$md5, a$key)[keys] + if (anyNA(md5)) { + stop( + paste(keys[is.na(md5)], collapse = ", "), + ": not in the archives table of the tile index ", + dbfile, + call. = FALSE + ) + } + md5 +} + #' Download and extract multiple archives per tile (by decade) #' #' @template ClimateNA_tile #' -#' @param climateURLs list of lists of tile URLs, with outer list names corresponding to tile ids. +#' @param climateURLs list of data frames of tile archives (`url` and `md5`, as returned by +#' [getClimateURLs()]), named by tile id. #' #' @param climatePath character string specifying the directory path to put climate data. #' @@ -160,13 +195,12 @@ getClimateURLs <- function( #' e.g., `c("historical_CMD_sm", "future_CMD_sp")`. #' If `NULL`, the default, then all files will be extracted. #' -#' @return (invisibly) a list of length `tileIDs` containing the result of `preProcess()` calls +#' @return (invisibly) a list with one element per tile, of no use: `getClimateTiles()` is called +#' for its side effect, the tile's archives downloaded to and extracted in +#' `/`. #' #' @export -#' @importFrom reproducible preProcess -#' @importFrom utils packageVersion getClimateTiles <- function(tile, climateURLs, climatePath, needVars = NULL) { - # needVars <- get("needVars", whereInStack("needVars")) if (is.null(needVars)) { needVars <- "" } @@ -174,90 +208,33 @@ getClimateTiles <- function(tile, climateURLs, climatePath, needVars = NULL) { climateVars <- unique(gsub("_normal", "", climateVars)) #normals are in their own archive climateVarsGrep <- paste(climateVars, collapse = "|") - owd <- getwd() - on.exit(setwd(owd)) - lapply(tile, climateURL = climateURLs, function(climateTile, climateURL) { + lapply(tile, function(climateTile) { workingPath <- file.path(climatePath, climateTile) reproducible::checkPath(workingPath, create = TRUE) - ow <- setwd(workingPath) - on.exit(setwd(ow)) ## TODO: the zip files are being put inside the tile directory, but should be one level up climateTileChar <- paste0("tile_", climateTile) - preHashes <- Map(url = climateURL[[as.character(climateTile)]], function(url) { - # preProcess(url = googledriveIDtoHumanURL(url)) - getRemoteMetadata(url = googledriveIDtoHumanURL(url), isGDurl = TRUE)[c( - "remoteHash", - "targetFile" - )] - }) - preProcessOut <- Map( - url = climateURL[[as.character(climateTile)]], - preHash = preHashes, - function(url, preHash) { - remoteMD5 <- preHash[["remoteHash"]] - - if (utils::packageVersion("reproducible") >= "3.0.0.9026") { - outs <- preProcess( - url = googledriveIDtoHumanURL(url), - alsoExtract = climateVarsGrep, - fun = NA, - destinationPath = workingPath - ) #, - newFiles <- outs$checkSums$actualFile[outs$checkSums$checksum.x != "dir"] - } else { - remoteMD5 <- preHash[["remoteHash"]] - localFile <- preHash$targetFile - localMD5 <- if (file.exists(localFile)) unname(tools::md5sum(localFile)) else "" - if (!identical(remoteMD5, localMD5)) { - for (i in 1:2) { - message("Downloading from Google Drive...") - dwnld <- googledrive::drive_download( - file = googledrive::as_id(url), - verbose = TRUE, - overwrite = TRUE - ) - localFile <- file.path(getwd(), dwnld$local_path) - localMD5 <- unname(tools::md5sum(dwnld$name)) - if (identical(remoteMD5, localMD5)) { - break - } - if (i == 2) { - stop("Failed to correctly download file from Google Drive; please check connection") - } - } - } else { - message("skipping new download; local copy of zip already present and correct") - } - newFiles <- extractJustAFew(workingPath, localFile, climateVarsGrep) - - ## TODO: how to best use Cache here? - # Eliot: suggesting this simple Cache -- - # It means that the Cache will be on the tile by date, with essentially no - # digesting other than the url and the path, i.e., content is not assessed - # This will be fine for a single computer, and when there are no climate - # data updates - ## ELIOT again: now uses the new preProcess which tests remote data object; - # fixes the above issue - } - message("extracted to ", workingPath, ":\n", paste(newFiles, collapse = ", ")) - } - ) |> + archives <- climateURLs[[as.character(climateTile)]] + out <- Map(url = archives$url, md5 = archives$md5, function(url, md5) { + zip <- .fetchArchive(url, md5, workingPath) + newFiles <- extractJustAFew(workingPath, zip, climateVarsGrep) + message("extracted to ", workingPath, ":\n", paste(newFiles, collapse = ", ")) + }) |> Cache( .functionName = paste0( - "preProcess_climateData_", + "fetchClimateTiles_climateData_", basename(climatePath), "_", climateTileChar ), .cacheExtra = list( - preHashes = preHashes, + md5 = archives$md5, climateVarsGrep = climateVarsGrep, workingPath = workingPath ) ) - names(preProcessOut) <- rep(climateTileChar, length(preProcessOut)) + names(out) <- rep(climateTileChar, length(out)) - return(preProcessOut) + return(out) }) |> invisible() } diff --git a/R/archiveCheck.R b/R/archiveCheck.R index 397db6c..1318824 100644 --- a/R/archiveCheck.R +++ b/R/archiveCheck.R @@ -1,5 +1,5 @@ -## Checks of the published ClimateNA zips against what the tile index says they hold. -## Used by the maintainer scripts data-raw/04-audit_archives.R and 05-repair_archives.R. +## Checks of ClimateNA zips against what the tile index says they hold. Used by the pipeline +## (data-raw/pipeline/) when it runs ClimateNA and cuts the zips. ## ## A zip is complete when every expected folder is present and every expected variable ## file in it is present and non-empty. Small files and extra files are reported but @@ -16,7 +16,7 @@ if (length(multi) > 0) { stop( "Index rows for one archive", - if (!is.null(rows$gid)) paste0(" (Drive ID ", paste(unique(rows$gid), collapse = ", "), ")"), + if (!is.null(rows$key)) paste0(" (key ", paste(unique(rows$key), collapse = ", "), ")"), " disagree on ", paste(multi, collapse = ", "), ": ", @@ -133,35 +133,3 @@ .archiveComplete <- function(problems) { !any(problems$problem %in% .archiveFailing) } - -## Expected index rows (tile x msy [x gcm x ssp] x year or period) that the index lacks. -.archiveIndexGaps <- function(index, type) { - av <- available(type) - when <- if (is.null(av$years)) "period" else "year" - grid <- list(tileid = unique(index$tileid), msy = unique(index$msy)) - if (type %in% c("future", "future_normals")) { - grid <- c(grid, list(gcm = av$gcms, ssp = av$ssps)) - } - grid[[when]] <- if (when == "year") av$years else av$periods - full <- expand.grid(grid, stringsAsFactors = FALSE) - - keyCols <- names(grid) - have <- do.call(paste, c(unname(as.list(index[keyCols])), sep = "\r")) - want <- do.call(paste, c(unname(as.list(full[keyCols])), sep = "\r")) - full <- full[!want %in% have, , drop = FALSE] - rownames(full) <- NULL - full -} - -## Drive-side problems: IDs that are absent or trashed, and files whose name differs -## from the index's zip file name. -.driveProblems <- function(zips, meta) { - m <- meta[match(zips$gid, meta$id), , drop = FALSE] - problem <- ifelse( - is.na(m$id) | m$trashed %in% TRUE, - "drive_missing", - ifelse(m$name != basename(zips$zipfile), "name_mismatch", NA_character_) - ) - keep <- !is.na(problem) - data.frame(gid = zips$gid[keep], problem = problem[keep]) -} diff --git a/R/dataRelease.R b/R/dataRelease.R index 86fbc2c..13b70c5 100644 --- a/R/dataRelease.R +++ b/R/dataRelease.R @@ -1,12 +1,13 @@ #' Identify the climate data release behind the installed package #' #' Each climateData release ships a tile index pointing at one release of the ClimateNA -#' archives on Google Drive. Use this to tell releases apart, e.g. in the cache key of code that -#' caches `prepClimateLayers()` results, so a new data release isn't served from an old cache. +#' archives in the Arbutus bucket. Use this to tell releases apart, e.g. in the cache key of +#' code that caches `prepClimateLayers()` results, so a new data release isn't served from an +#' old cache. #' #' @return a list with `release_id` (e.g. `"cna-v7.70-3arcmin"`), `climatena_version` (the #' ClimateNA release that produced the data) and `dem_resolution` (e.g. `"3arcmin"`). Indexes -#' made before releases were recorded give `release_id = "pre-3.0.0"`. +#' made before releases were recorded (before climateData 2.3.0) give `release_id = "pre-2.3.0"`. #' #' @export #' @examples @@ -18,7 +19,7 @@ climateDataRelease <- function() { if (!DBI::dbExistsTable(db, "release")) { return(list( - release_id = "pre-3.0.0", + release_id = "pre-2.3.0", climatena_version = NA_character_, dem_resolution = "3arcmin" )) @@ -29,3 +30,24 @@ climateDataRelease <- function() { ) as.list(r[1, ]) } + +## The bucket's public URL from the index's release table: an archive's URL is +## /. Indexes from before climateData 2.3.0 point at Google Drive and have none. +.indexBaseUrl <- function(dbfile = ClimateNA_tiles_sqlite()) { + db <- sqlite_connect_db(dbfile, readonly = TRUE) + on.exit(DBI::dbDisconnect(db), add = TRUE) + url <- if ( + DBI::dbExistsTable(db, "release") && "base_url" %in% DBI::dbListFields(db, "release") + ) { + DBI::dbGetQuery(db, "SELECT base_url FROM release LIMIT 1")$base_url + } + if (length(url) != 1L || is.na(url) || !nzchar(url)) { + stop( + dbfile, + " has no bucket URL (release.base_url): it is a Drive index from before ", + "climateData 2.3.0, whose archives are no longer served. Update climateData.", + call. = FALSE + ) + } + url +} diff --git a/R/download.R b/R/download.R new file mode 100644 index 0000000..c62e04b --- /dev/null +++ b/R/download.R @@ -0,0 +1,63 @@ +## Downloading the archives: public objects in a bucket, each checked against the MD5 that the +## tile index records for it (archives.md5). + +## The request for `url`: up to 3 tries, retrying transient HTTP errors and network failures +## (e.g. a DNS timeout), which httr2 >= 1.0.4 retries only with `retry_on_failure`. +.archiveRequest <- function(url) { + httr2::request(url) |> httr2::req_retry(max_tries = 3, retry_on_failure = TRUE) +} + +## Download `url` to `destfile`; HTTP errors propagate once the tries are used up. +.downloadArchive <- function(url, destfile) { + httr2::req_perform(.archiveRequest(url), path = destfile) + invisible(destfile) +} + +## The archive at `url` as `/` with MD5 `md5`: kept when already there, +## otherwise downloaded (to a temporary file in `dir`, renamed into place once its MD5 matches). +## A mismatch is downloaded once more, then stops with the URL and both MD5s. +.fetchArchive <- function(url, md5, dir) { + dest <- file.path(dir, basename(url)) + if (file.exists(dest) && identical(unname(tools::md5sum(dest)), md5)) { + return(dest) + } + dir.create(dir, recursive = TRUE, showWarnings = FALSE) + .removeStaleParts(dir, basename(url)) + got <- NA_character_ + for (i in 1:2) { + tmp <- tempfile(paste0(basename(url), "."), tmpdir = dir, fileext = ".part") + on.exit(unlink(tmp), add = TRUE) + message("Downloading ", url) + .downloadArchive(url, tmp) + got <- unname(tools::md5sum(tmp)) + if (identical(got, md5)) { + unlink(dest) + if (!file.rename(tmp, dest)) { + stop("Couldn't move the download of ", url, " into place as ", dest, call. = FALSE) + } + return(dest) + } + unlink(tmp) + } + stop( + "The download of ", + url, + " doesn't match the tile index: expected MD5 ", + md5, + ", got ", + got, + ". Try again later; if it persists, report it at ", + "https://github.com/PredictiveEcology/climateData/issues", + call. = FALSE + ) +} + +## Remove `zip`'s partial downloads in `dir` (..part) left by a session killed +## mid-download, whose on.exit() never ran: those unmodified for a day, so never a download still +## running in another process. +.removeStaleParts <- function(dir, zip) { + f <- list.files(dir, all.files = TRUE, full.names = TRUE) + f <- f[startsWith(basename(f), paste0(zip, ".")) & endsWith(f, ".part")] + old <- difftime(Sys.time(), file.mtime(f), units = "days") > 1 + unlink(f[which(old)]) +} diff --git a/R/imports.R b/R/imports.R index 6428194..4e021e1 100644 --- a/R/imports.R +++ b/R/imports.R @@ -2,22 +2,11 @@ #' #' @importFrom utils getFromNamespace #' @keywords internal -#' @rdname imports -assessGoogle <- utils::getFromNamespace("assessGoogle", "reproducible") - #' @rdname imports .listFilesInArchive <- utils::getFromNamespace(".listFilesInArchive", "reproducible") #' @rdname imports .whichExtractFn <- utils::getFromNamespace(".whichExtractFn", "reproducible") -#' @rdname imports -getRemoteMetadata <- utils::getFromNamespace("getRemoteMetadata", "reproducible") - -#' @rdname imports -googledriveIDtoHumanURL <- utils::getFromNamespace("googledriveIDtoHumanURL", "reproducible") - -## reproducible downloads the climate tiles with httr2 but has it only in Suggests, so -## climateData imports it to make sure it is installed (see getClimateTiles()). -#' @importFrom httr2 request -NULL +## climateData downloads the climate archives and makeClimateDEM()'s DEM with httr2 itself +## (.downloadArchive()). diff --git a/R/latestHistoricalYear.R b/R/latestHistoricalYear.R index 242c8ef..a953268 100644 --- a/R/latestHistoricalYear.R +++ b/R/latestHistoricalYear.R @@ -26,7 +26,7 @@ latestHistoricalYear <- function(tile = NULL, msy = "MSY") { if (!is.null(tile)) { climate_df <- climate_df[climate_df$tileid %in% tile, ] } - climate_df <- climate_df[!is.na(climate_df$gid), ] + climate_df <- climate_df[!is.na(climate_df$key), ] tilesPerYear <- tapply(climate_df$tileid, climate_df$year, function(x) length(unique(x))) years <- as.integer(names(tilesPerYear)) diff --git a/R/makeClimateDEM.R b/R/makeClimateDEM.R index 5f853a5..b1d2ec8 100644 --- a/R/makeClimateDEM.R +++ b/R/makeClimateDEM.R @@ -21,7 +21,6 @@ #' #' @author Ian Eddy #' @export -#' @importFrom reproducible prepInputs #' @importFrom terra buffer compareGeom crop mask project resample same.crs trim vect writeRaster #' @rdname makeClimateDEM makeClimateDEM <- function( @@ -36,11 +35,7 @@ makeClimateDEM <- function( studyArea <- vect(studyArea) } - gtopo30N <- prepInputs( - url = "https://drive.google.com/file/d/14puAtns8oTZDtvWzpQ6_FgK4MbozGZFK/", - destinationPath = DEMdestinationPath, - overwrite = TRUE - ) + gtopo30N <- .gtopo30Canada(DEMdestinationPath) if (arcSecRes[1] != arcSecRes[2]) { stop(".asc format requires x and y dimensions to be equal. Please adjust arcSecRes.") @@ -68,3 +63,16 @@ makeClimateDEM <- function( return(gtopo30N) } + +## USGS GTOPO30 (30 arc-second elevation) mosaicked over Canada: one GeoTIFF in a zip, kept in the +## bucket beside the climate archives. Downloaded to `destinationPath` (checked against `md5`) and +## unzipped there. +.gtopo30Canada <- function( + destinationPath, + url = paste0(.indexBaseUrl(), "/climateData/dem/gtopo30Canada.zip"), + md5 = "8adc54c83fcca0301a9a2f716237d077" +) { + zip <- .fetchArchive(url, md5, destinationPath) + utils::unzip(zip, "gtopo30Canada.tif", exdir = destinationPath) + terra::rast(file.path(destinationPath, "gtopo30Canada.tif")) +} diff --git a/R/pipelineDem.R b/R/pipelineDem.R new file mode 100644 index 0000000..0abfe1e --- /dev/null +++ b/R/pipelineDem.R @@ -0,0 +1,154 @@ +## DEM tiles for ClimateNA: lon/lat, square cells at the release's resolution, and Windows (CRLF) +## line ends, which ClimateNA needs (rewrite_asc()). Used by the pipeline (data-raw/pipeline/). + +## The cell size, in degrees, of a release's `dem_resolution` (e.g. "3arcmin"). +.demResolutionDeg <- function(x) { + if (length(x) != 1L || !grepl("^[1-9][0-9]*arcmin$", x)) { + stop("dem_resolution must be like \"3arcmin\", not \"", x, "\"", call. = FALSE) + } + as.numeric(sub("arcmin$", "", x)) / 60 +} + +## Stops, naming `file`, unless it is an ASCII grid ClimateNA can use at `resolutionDeg`: CRLF line +## ends, square cells of that size, and a lon/lat extent. Returns `file` invisibly. +.demCheck <- function(file, resolutionDeg) { + fail <- function(...) stop(basename(file), ": ", ..., call. = FALSE) + b <- readBin(file, "raw", file.size(file)) + lf <- which(b == as.raw(10L)) + if (length(lf) < 6L) { + fail("no ASCII grid header") + } + if (lf[1] == 1L || any(b[lf - 1L] != as.raw(13L))) { + fail("line ends must be CRLF (Windows), as ClimateNA needs them; see rewrite_asc()") + } + + lines <- strsplit(rawToChar(b[seq_len(lf[6])]), "\r\n", fixed = TRUE)[[1]] + kv <- strsplit(trimws(lines), "[ \t]+") + h <- stats::setNames( + suppressWarnings(as.numeric(vapply(kv, `[`, "", 2))), + tolower(vapply(kv, `[`, "", 1)) + ) + if (!"cellsize" %in% names(h)) { + fail("cells must be square (one cellsize, not dx and dy)") + } + for (k in list("ncols", "nrows", c("xllcorner", "xllcenter"), c("yllcorner", "yllcenter"))) { + if (!any(k %in% names(h)) || is.na(h[[intersect(k, names(h))[1]]])) { + fail("its header has no ", paste(k, collapse = " or "), " line") + } + } + cs <- h[["cellsize"]] + if (is.na(cs) || abs(cs - resolutionDeg) > 1e-9) { + fail("cell size ", cs, " degrees, but the release's resolution is ", resolutionDeg) + } + corner <- function(axis) { + k <- paste0(axis, c("llcorner", "llcenter")) + if (k[1] %in% names(h)) h[[k[1]]] else h[[k[2]]] - cs / 2 + } + x0 <- corner("x") + y0 <- corner("y") + x1 <- x0 + h[["ncols"]] * cs + y1 <- y0 + h[["nrows"]] * cs + if (anyNA(c(x0, y0, x1, y1)) || x0 < -180 || x1 > 180 || y0 < -90 || y1 > 90) { + fail("its extent is not in lon/lat degrees") + } + invisible(file) +} + +## The tile grid (inst/extdata/tiles.gpkg) from a boundary (sf, lon/lat; GADM 4.1 level 0 Canada): +## holes filled, a 10 x 10 grid over its bounding box, the cells that intersect it kept and numbered +## in grid order. This reproduces the shipped grid exactly (checked 2026-12-03, 86 tiles). +.tileGrid <- function(boundary) { + geom <- lapply(sf::st_geometry(boundary), function(p) { + if (inherits(p, "MULTIPOLYGON")) { + sf::st_multipolygon(lapply(p, function(q) q[1])) + } else { + sf::st_polygon(p[1]) + } + }) + filled <- sf::st_sfc(geom, crs = sf::st_crs(boundary)) + grid <- sf::st_make_grid(filled, n = c(10, 10)) + grid <- grid[lengths(sf::st_intersects(grid, filled)) > 0] + sf::st_sf(id = seq_along(grid), geom = grid) +} + +## Whether two tile grids have the same ids and the same polygons (coordinates within 1e-9). +.sameTileGrid <- function(a, b) { + if (!identical(as.integer(a$id), as.integer(b$id))) { + return(FALSE) + } + ca <- sf::st_coordinates(sf::st_geometry(a)) + cb <- sf::st_coordinates(sf::st_geometry(b)) + identical(dim(ca), dim(cb)) && max(abs(ca[, 1:2] - cb[, 1:2])) < 1e-9 +} + +## DEM tiles from `dem` (SpatRaster; the GTOPO30 Canada mosaic), as data-raw/02 (removed in 2.3.0) +## made them: projected to lon/lat at `resolutionDeg`, cropped and masked to `boundary` (sf; holes +## filled), trimmed, and cut by the tile polygons into `/can_dem_.asc` with CRLF line +## ends. A tile with no DEM cell gets no file. terra::makeTiles() numbers its files by row, so +## `tiles$id` must be the row numbers (as in tiles.gpkg). Returns the files, by id. +.buildDemTiles <- function(dem, boundary, tiles, resolutionDeg, dir) { + if (!identical(as.integer(tiles$id), seq_len(nrow(tiles)))) { + stop("tile ids must be 1..n in row order, as in tiles.gpkg", call. = FALSE) + } + geom <- lapply(sf::st_geometry(boundary), function(p) { + if (inherits(p, "MULTIPOLYGON")) { + sf::st_multipolygon(lapply(p, function(q) q[1])) + } else { + sf::st_polygon(p[1]) + } + }) + land <- terra::vect(sf::st_sfc(geom, crs = sf::st_crs(boundary))) + dem <- terra::project(dem, "epsg:4326", res = resolutionDeg) |> + terra::crop(land) |> + terra::mask(land) |> + terra::trim() + dir.create(dir, recursive = TRUE, showWarnings = FALSE) + f <- terra::makeTiles( + dem, + terra::vect(tiles), + filename = file.path(dir, "can_dem_.asc"), + na.rm = TRUE, + overwrite = TRUE + ) + f <- f[order(tileID(f))] + for (x in f) { + .ascSpaceRows(x) + rewrite_asc(x) + .demCheck(x, resolutionDeg) + } + .demTilesInPolygons(f, tiles) + f +} + +## Stops, naming the file, unless each DEM tile (can_dem_.asc) lies within its tile polygon's +## bounding box, give or take one cell (cropping snaps outwards). The file names come from +## terra::makeTiles()'s numbering, which this checks against the tile ids. +.demTilesInPolygons <- function(files, tiles) { + for (f in files) { + id <- tileID(f) + r <- terra::rast(f) + e <- as.vector(terra::ext(r)) + b <- sf::st_bbox(tiles[tiles$id == id, ]) + cell <- max(terra::res(r)) + inside <- length(b) == 4 && + !anyNA(b) && + e[["xmin"]] >= b[["xmin"]] - cell && + e[["xmax"]] <= b[["xmax"]] + cell && + e[["ymin"]] >= b[["ymin"]] - cell && + e[["ymax"]] <= b[["ymax"]] + cell + if (!inside) { + stop(basename(f), " doesn't lie in tile ", id, "'s polygon", call. = FALSE) + } + } + invisible(files) +} + +## Starts every data row of an .asc file with a space, as in the DEM tiles the releases use: GDAL +## (3.8) writes rows that start with "nan", then can't read the file back. +.ascSpaceRows <- function(f) { + x <- readLines(f, warn = FALSE) + header <- grepl("^(ncols|nrows|xll|yll|cellsize|dx|dy|nodata_value)", x, ignore.case = TRUE) + bare <- !header & !startsWith(x, " ") + x[bare] <- paste0(" ", x[bare]) + writeLines(x, f) +} diff --git a/R/pipelineUpload.R b/R/pipelineUpload.R index 8fe4078..0523c9d 100644 --- a/R/pipelineUpload.R +++ b/R/pipelineUpload.R @@ -1,21 +1,23 @@ -#' What to do with a zip on Drive +#' What to do with a zip in the bucket #' -#' Given the files of the same name already in the zip's release folder: reuse one with the same -#' MD5 (`"found"`); else, if `replace`, replace a differing one in place (`"update"`), so its -#' Drive ID, which the index holds as `gid`, stays the same; else upload a new file (`"upload"`). -#' When several same-named files differ, the one with ID `gid` is updated; if none has it, this -#' stops. Without `replace`, a differing same-named file stops the upload, so a shipped -#' release's files change only when the maintainer asks (`replace_changed` in `_local.R`). +#' Given the objects already under the zip's key (one at most in a bucket): reuse one with the +#' same MD5 (`"found"`); else, if `replace`, replace a differing one in place (`"update"`); else +#' upload a new object (`"upload"`). When several candidates differ, the one with ID `key` is +#' updated; if none has it, this stops. Without `replace`, a differing object stops the upload, +#' so a release's files change only when the maintainer asks (`replace_changed` in `_local.R`). +#' An object a released index refers to (`released`) is never replaced: installed copies of that +#' release check downloads against its MD5, so a fix to released data needs a new release id. #' -#' @param there data.frame with columns `id` and `md5` (`NA` when Drive gives none). +#' @param there data.frame with columns `id` and `md5` (`NA` when the store gives none). #' @param md5 character. The zip's MD5. -#' @param gid character or `NULL`. The zip's Drive ID in the index, if it has one. -#' @param replace logical. Replace a differing same-named file in place? +#' @param key character or `NULL`. The zip's object key, if it has one. +#' @param replace logical. Replace a differing object in place? +#' @param released logical. Does a released index (the previous release's) refer to `key`? #' #' @return list: `action` (`"found"`, `"update"` or `"upload"`) and `id` (`NA` for `"upload"`). #' #' @keywords internal -.uploadAction <- function(there, md5, gid = NULL, replace = FALSE) { +.uploadAction <- function(there, md5, key = NULL, replace = FALSE, released = FALSE) { same <- which(there$md5 %in% md5) if (length(same) > 0) { return(list(action = "found", id = there$id[same[1]])) @@ -23,8 +25,8 @@ if (nrow(there) == 0) { return(list(action = "upload", id = NA_character_)) } - id <- if (!is.null(gid) && any(there$id %in% gid)) { - gid + id <- if (!is.null(key) && any(there$id %in% key)) { + key } else if (nrow(there) == 1) { there$id } else { @@ -34,11 +36,19 @@ ") and none is the index's; remove the stray ones" ) } + if (isTRUE(released)) { + stop( + "a released index refers to ", + id, + ", which differs from the zip. It is never replaced: installed copies check downloads ", + "against its MD5. A fix to released data needs a new release_id" + ) + } if (!isTRUE(replace)) { stop( - "the release folder's file of that name (", + "the bucket's object ", id, - ") differs from the zip; set replace_changed = TRUE in _local.R to replace it in place" + " differs from the zip; set replace_changed = TRUE in _local.R to replace it in place" ) } list(action = "update", id = id) diff --git a/R/prepClimateLayers.R b/R/prepClimateLayers.R index 2b90417..194e76b 100644 --- a/R/prepClimateLayers.R +++ b/R/prepClimateLayers.R @@ -123,7 +123,6 @@ extractTimes <- function(climateVarsList, type) { #' #' @examples #' if (require("archive", quietly = TRUE) && -#' require("googledrive", quietly = TRUE) && #' require("SpaDES.tools", quietly = TRUE) && #' !isTRUE(as.logical(Sys.getenv("CI", "false")))) { #' dPath <- file.path(tempdir(), "test_prepClimateLayers") @@ -173,7 +172,7 @@ extractTimes <- function(climateVarsList, type) { #' #' climateRasters <- prepClimateLayers( #' climateVarsList = climateVariables, -#' srcdir = climatePath, ## raw inputs, downloaded from Google Drive +#' srcdir = climatePath, ## raw inputs, downloaded from the bucket #' dstdir = climatePathOut, ## intermediate + final outputs #' gcm = GCM, #' ssp = SSP, diff --git a/_pkgdown.yml b/_pkgdown.yml index 3132719..028e455 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -43,7 +43,6 @@ reference: - title: Maintainer tools desc: For building the climate archives and the tile index. contents: - - ClimateNA_path - ClimateNA_sql - makeClimateDEM - rewrite_asc diff --git a/data-raw/01-ClimateNA_setup.R b/data-raw/01-ClimateNA_setup.R deleted file mode 100644 index 56b4d7a..0000000 --- a/data-raw/01-ClimateNA_setup.R +++ /dev/null @@ -1,69 +0,0 @@ -# load packages ------------------------------------------------------------------------------- - -## archives and up/downloads -library(archive) -# library(googledrive) - -## database -library(DBI) -library(dplyr) -#library(RSQLite) - -## parallel processing -library(future) -library(future.apply) -library(future.callr) -library(progressr) - -## geospatial -# library(geodata) -# library(nngeo) -library(sf) -library(terra) - -library(reproducible) -library(rprojroot) - -prjDir <- find_root(has_file("climateData.Rproj")) - -devtools::load_all(prjDir) - -# setup --------------------------------------------------------------------------------------- - -## adjust these values for your user / machine - -ClimateNAdir <- "C:/Climatena_v760" -ClimateNAexe <- "ClimateNA_v7.60.exe" -ClimateNAdata <- switch( - Sys.info()[["sysname"]], - Linux = "/mnt/data/climate/ClimateNA_data", - Windows = "C:/ClimateNA_data" -) -stopifnot(dir.exists(ClimateNAdata)) - -userEmail <- "achubaty@for-cast.ca" -oauthCachePath <- file.path(prjDir, ".secrets") -googledrive::drive_auth(email = userEmail, cache = oauthCachePath) - -maxCores <- parallelly::availableCores() * 0.75 - -handlers(global = TRUE) ## "subscribe" to progress updates - -## database tracks which data already processed / uploaded -## -## NOTE: the package version should be the canonical one. -## although it is useful to work on the shared one (addlDBfile) -## to allow multiple machines to use/update accordingly, -## sqlite databases can't always be opened from a network drive. -dbfile <- "ClimateNA_tiles.sqlite" -pkgDBfile <- file.path(prjDir, "inst", "extdata", dbfile) -addlDBfile <- file.path(ClimateNAdata, dbfile) -wrkngDBfile <- file.path(prjDir, "tmp", dbfile) ## local copy in current project - -if (!dir.exists(dirname(wrkngDBfile))) { - dir.create(dirname(wrkngDBfile)) -} - -if (!file.exists(wrkngDBfile)) { - file.copy(pkgDBfile, wrkngDBfile) ## always work on a copy -} diff --git a/data-raw/02-ClimateNA_tiles.R b/data-raw/02-ClimateNA_tiles.R deleted file mode 100644 index ac8cbad..0000000 --- a/data-raw/02-ClimateNA_tiles.R +++ /dev/null @@ -1,82 +0,0 @@ -source("data-raw/01-ClimateNA_setup.R") - -# create tiles -------------------------------------------------------------------------------- - -targetCRS <- "epsg:4326" ## ClimateNA needs lat/lon, and the DEM already uses this - -canada <- geodata::gadm(country = "CAN", level = 0, path = extdataPath, version = "4.1", resolution = 1) |> - st_as_sf() |> - st_transform(targetCRS) |> - nngeo::st_remove_holes() - -tiles0 <- st_make_grid(canada, n = c(10, 10)) - -idx <- st_intersects(tiles0, canada) |> - lapply(any) |> - unlist() |> - which() - -tiles <- tiles0[idx] |> - st_as_sf() |> - dplyr::mutate(id = dplyr::row_number(), .before = x) |> - dplyr::rename(geom = x) -st_write(tiles, file.path(extdataPath, "tiles.gpkg"), append = FALSE) ## can't write sqlite file to network drive -file.copy(from = file.path(extdataPath, "tiles.gpkg"), - to = file.path(ClimateNAdata, "tiles.gpkg"), - overwrite = TRUE) ## write locally; copy to share. - -if (interactive()) { - plot(st_geometry(tiles), col = "lightgrey") - plot(st_geometry(canada), add = TRUE) -} - -arcSecRes <- c(60, 60) ## .asc format needs these to be the same -gtopo30N <- prepInputs( - url = "https://drive.google.com/file/d/14puAtns8oTZDtvWzpQ6_FgK4MbozGZFK/", - destinationPath = extdataPath -) |> - project(targetCRS, res = arcSecRes/60/60) |> - crop(canada) |> - mask(canada) |> - trim() - -if (interactive()) { - plot(gtopo30N, legend = FALSE) - plot(st_geometry(tiles), add = TRUE, border = "blue", lwd = 2) - st_centroid(tiles) |> - st_coordinates() |> - text(col = "blue") -} - -dem_dir <- file.path(ClimateNAdata, "dem") -if (!dir.exists(dem_dir)) { - dir.create(dem_dir, recursive = TRUE) -} -dem_ff <- makeTiles( - x = gtopo30N, - y = vect(tiles), - filename = file.path(dem_dir, "can_dem_.asc"), - na.rm = TRUE -) - -## NOTE: rewrite line endings in asc files for windows -lapply(dem_ff, function(f) { - rewrite_asc(f) -}) - -if (interactive()) { - ## visually check that the raster ids match the polygon ids for the tiles - dem <- vrt(dem_ff) - plot(dem, legend = FALSE) - plot(st_geometry(tiles), add = TRUE) - - lapply(dem_ff, function(f) { - id <- tileID(f) - r <- rast(f) - text(cbind(xmin(r) + (xmax(r) - xmin(r)) / 2, ymin(r) + (ymax(r) - ymin(r)) / 2), id) - - return(id) - }) - - rm(vrt) -} diff --git a/data-raw/03-ClimateNA_future.R b/data-raw/03-ClimateNA_future.R deleted file mode 100644 index 2ead410..0000000 --- a/data-raw/03-ClimateNA_future.R +++ /dev/null @@ -1,398 +0,0 @@ -## 1. Create tiles for Canada for use with ClimateNA; -## 2. Download and process historical, projected, and normals data for each tile using ClimateNA; -## 3. Archive and upload each set of tiles for use with canClimateData. - -stop( - "Superseded by the targets pipeline in data-raw/pipeline/ (vignette 'maintaining-climate-data'). ", - "This script ends by copying its working index over the shipped release index.", - call. = FALSE -) - -# setup --------------------------------------------------------------------------------------- - -source("data-raw/01-ClimateNA_setup.R") - -runClimateNA <- FALSE ## TRUE -fileChecksums <- FALSE ## TRUE -createZips <- FALSE ## TRUE -uploadArchives <- FALSE ## TRUE -reuploadArchives <- FALSE ## TRUE - -climateType <- "future" - -if (isTRUE(fileChecksums)) { - csdb <- checksums_sql(wrkngDBfile, climateType) - checksums_db <- csdb[["db"]] - checksums_future_df <- csdb[["df"]] - rm(csdb) -} - -dbdf <- ClimateNA_sql(wrkngDBfile, climateType) -climate_db <- dbdf[["db"]] -future_climate_df <- dbdf[["df"]] -rm(dbdf) - -MSYs <- c("MSY", "M", "S", "Y") -GCMs <- available(climateType)[["gcms"]] -SSPs <- available(climateType)[["ssps"]] -future_years <- available(climateType)[["years"]] -future_decades <- (future_years %/% 10 * 10) |> unique() |> as.integer() - -if (!exists("dem_ff")) { - dem_ff <- list.files(file.path(ClimateNAdata, "dem"), pattern = "[.]asc$", full.names = TRUE) - stopifnot(length(dem_ff) > 0) -} - -plan("callr", workers = min(length(dem_ff), maxCores)) - -# get ClimateNA future time series ------------------------------------------------------------ - -new_rows_future <- future.apply::future_lapply( - dem_ff, - function(f) { - dbdf <- climateData::ClimateNA_sql(wrkngDBfile, climateType) - climate_db <- dbdf[["db"]] - future_climate_df <- dbdf[["df"]] - rm(dbdf) - - f <- normalizePath(f) - tile <- climateData::tileID(f) - - z <- lapply(GCMs, function(gcm) { - lapply(SSPs, function(ssp) { - lapply(MSYs, function(msy) { - ClimateNAout <- climateData::ClimateNA_path( - ClimateNAdata, - tile = tile, - type = climateType, - msy, - gcm, - ssp - ) - - lapply(future_years, function(yr) { - row <- dplyr::filter( - future_climate_df, - gcm == !!gcm & ssp == !!ssp & msy == !!msy & year == !!yr & tileid == !!tile - ) |> - dplyr::collect() - - if (nrow(row) == 0) { - if (isTRUE(runClimateNA)) { - withr::local_dir(ClimateNAdir) - sys::exec_wait( - ClimateNAexe, - args = c( - paste0("/", msy), - paste0("/", gcm, "_ssp", ssp, "@", yr, ".gcm"), - paste0("/", f), - paste0("/", ClimateNAout) - ) - ) - withr::deferred_run() - } - - new_row <- data.frame( - gcm = gcm, - ssp = ssp, - msy = msy, - year = yr, - tileid = tile, - created = file.info(ClimateNAout)$mtime, - stringsAsFactors = FALSE - ) - # rows_append(future_climate_df, new_row, copy = TRUE, in_place = TRUE) - } else { - new_row <- dplyr::mutate(row, created = file.info(ClimateNAout)$mtime) - # rows_update(future_climate_df, new_row, copy = TRUE, in_place = TRUE, unmatched = "ignore") - } - - return(new_row) - }) |> - dplyr::bind_rows() - }) |> - dplyr::bind_rows() - }) |> - dplyr::bind_rows() - }) |> - dplyr::bind_rows() - - DBI::dbDisconnect(climate_db) - - return(z) - }, - future.seed = NULL -) |> - dplyr::bind_rows() - -if (!"rowid" %in% colnames(new_rows_future)) { - new_rows_future <- tibble::rowid_to_column(new_rows_future) - dplyr::rows_append(future_climate_df, new_rows_future, copy = TRUE, in_place = TRUE) -} else { - dplyr::rows_update( - future_climate_df, - new_rows_future, - copy = TRUE, - in_place = TRUE, - unmatched = "ignore" - ) -} - -DBI::dbDisconnect(climate_db) - -file.copy(wrkngDBfile, addlDBfile, overwrite = TRUE) - -# checksums ----------------------------------------------------------------------------------- - -checksums_future <- future.apply::future_lapply( - dem_ff, - function(f) { - tile <- normalizePath(f) |> climateData::tileID() - - lapply(GCMs, function(gcm) { - lapply(SSPs, function(ssp) { - lapply(MSYs, function(msy) { - ClimateNAout <- climateData::ClimateNA_path( - ClimateNAdata, - tile = tile, - type = climateType, - msy, - gcm, - ssp - ) - - lapply(future_years, function(yr) { - digs <- file.path(ClimateNAout, paste0(tools::file_path_sans_ext(nrm), "Y")) |> - fs::dir_ls(type = "file") |> - vapply(digest::digest, file = TRUE, algo = "xxhash64", FUN.VALUE = character(1)) - - checksums <- data.frame( - gcm = gcm, - ssp = ssp, - msy = msy, - year = yr, - tileid = tile, - filename = basename(names(digs)), - filehash = unname(digs), - stringsAsFactors = FALSE - ) - - return(checksums) - }) |> - dplyr::bind_rows() - }) |> - dplyr::bind_rows() - }) |> - dplyr::bind_rows() - }) |> - dplyr::bind_rows() - }, - future.seed = NULL -) |> - dplyr::bind_rows() - -if (!"id" %in% colnames(new_rows_future)) { - dplyr::rows_append(checksums_future_df, checksums_future, copy = TRUE, in_place = TRUE) -} else { - dplyr::rows_update( - checksums_future_df, - checksums_future, - copy = TRUE, - in_place = TRUE, - unmatched = "ignore" - ) -} - -DBI::dbDisconnect(checksums_db) -DBI::dbDisconnect(climate_db) - -file.copy(wrkngDBfile, addlDBfile, overwrite = TRUE) - -# archive tilesets ---------------------------------------------------------------------------- - -if (createZips) { - ## future time series - new_rows_future <- future.apply::future_lapply(dem_ff, function(f) { - dbdf <- climateData::ClimateNA_sql(wrkngDBfile, climateType) - climate_db <- dbdf[["db"]] - future_climate_df <- dbdf[["df"]] - rm(dbdf) - - tile <- normalizePath(f) |> climateData::tileID() - - z <- lapply(GCMs, function(gcm) { - lapply(SSPs, function(ssp) { - lapply(MSYs, function(msy) { - lapply(future_decades, function(dcd) { - ClimateNAout <- climateData::ClimateNA_path( - ClimateNAdata, - tile = tile, - type = climateType, - msy, - gcm, - ssp - ) - fzip <- paste0(ClimateNAout, "_", gcm, "_", ssp, "_", msy, "_", dcd, ".zip") - - type <- paste0(climateType, "_", msy) - - row <- dplyr::filter( - future_climate_df, - gcm == !!gcm & - ssp == !!ssp & - msy == !!msy & - year %in% !!(dcd + 0:9) & - tileid == !!tile - ) |> - dplyr::collect() - - files2add <- fs::dir_ls( - ClimateNAout, - regexp = paste0("@(", paste(dcd + 0:9, collapse = "|"), ")", msy, "$") - ) |> - fs::dir_ls() |> - fs::path_rel(ClimateNAout) - - withr::local_dir(ClimateNAout) - archive_write_files(archive = fzip, files = files2add) - withr::deferred_run() - - new_row <- dplyr::mutate( - row, - archived = file.info(fzip)$mtime, - zipfile = fs::path_rel(fzip, ClimateNAdata) - ) - # rows_update(future_climate_df, new_row, copy = TRUE, in_place = TRUE, unmatched = "ignore") - - return(new_row) - }) |> - dplyr::bind_rows() - }) |> - dplyr::bind_rows() - }) |> - dplyr::bind_rows() - }) |> - dplyr::bind_rows() - - DBI::dbDisconnect(climate_db) - - return(z) - }) |> - dplyr::bind_rows() - - dplyr::rows_update( - future_climate_df, - new_rows_future, - copy = TRUE, - in_place = TRUE, - unmatched = "ignore" - ) - - DBI::dbDisconnect(climate_db) - - file.copy(wrkngDBfile, addlDBfile, overwrite = TRUE) -} - -# upload tilesets ----------------------------------------------------------------------------- - -if (uploadArchives) { - googledrive::drive_auth(email = userEmail, cache = oauthCachePath) - - plan("callr", workers = 16L) ## don't want too many parallel uploads - - gids_future <- googledrive::drive_ls(googledrive::as_id("1DH_JF6ZluYsZUpHGRXpXI8Q-DOUOE9AY")) |> - dplyr::select(name, id) |> - dplyr::mutate( - gcm = sapply(name, function(x) strsplit(x, "_")[[1]][1]), - ssp = sapply(name, function(x) strsplit(x, "(_ssp|_RCP)")[[1]][2]), - name = NULL, - .before = id - ) - - ## future time series - new_rows_future <- future.apply::future_lapply(dem_ff, function(f) { - dbdf <- ClimateNA_sql(wrkngDBfile, climateType) - climate_db <- dbdf[["db"]] - future_climate_df <- dbdf[["df"]] - rm(dbdf) - - tile <- normalizePath(f) |> climateData::tileID() - - z <- lapply(GCMs, function(gcm) { - lapply(SSPs, function(ssp) { - lapply(MSYs, function(msy) { - ## re-auth to avoid curl::curl_fetch_memory() "Error in the HTTP2 framing layer" - googledrive::drive_auth(email = userEmail, cache = oauthCachePath) - - gid <- dplyr::filter(gids_future, gcm == !!gcm, ssp == !!ssp)[["id"]] - drivefiles <- googledrive::drive_ls(gid) - - lapply(future_decades, function(dcd) { - ClimateNAout <- climateData::ClimateNA_path( - ClimateNAdata, - tile = tile, - type = climateType, - msy, - gcm, - ssp - ) - fzip <- paste0(ClimateNAout, "_", gcm, "_", ssp, "_", msy, "_", dcd, ".zip") - - type <- paste0(climateType, "_", msy) - - row <- dplyr::filter( - future_climate_df, - gcm == !!gcm & - ssp == !!ssp & - msy == !!msy & - year %in% !!(dcd + 0:9) & - tileid == !!tile - ) |> - dplyr::collect() - - if (reuploadArchives) { - gt <- googledrive::drive_put(media = fzip, path = googledrive::as_id(gid)) - } else { - gt <- dplyr::filter(drivefiles, name == basename(fzip)) - - if (nrow(gt) == 0) { - gt <- googledrive::drive_put(media = fzip, path = googledrive::as_id(gid)) - } - } - - new_row <- dplyr::mutate(row, uploaded = Sys.time(), gid = gt$id) - # rows_update(climate_hist_normals_df, new_row, copy = TRUE, in_place = TRUE, unmatched = "ignore") - - return(new_row) - }) |> - dplyr::bind_rows() - }) |> - dplyr::bind_rows() - }) |> - dplyr::bind_rows() - }) |> - dplyr::bind_rows() - - DBI::dbDisconnect(climate_db) - - return(z) - }) |> - dplyr::bind_rows() - - dplyr::rows_update( - future_climate_df, - new_rows_future, - copy = TRUE, - in_place = TRUE, - unmatched = "ignore" - ) - - DBI::dbDisconnect(climate_db) - - file.copy(wrkngDBfile, addlDBfile, overwrite = TRUE) -} - -## copy updated db to package data folder + remove working copy -file.copy(wrkngDBfile, addlDBfile, overwrite = TRUE) -file.copy(wrkngDBfile, pkgDBfile, overwrite = TRUE) -unlink(wrkngDBfile) diff --git a/data-raw/03-ClimateNA_future_normals.R b/data-raw/03-ClimateNA_future_normals.R deleted file mode 100644 index 04c7b47..0000000 --- a/data-raw/03-ClimateNA_future_normals.R +++ /dev/null @@ -1,359 +0,0 @@ -## 1. Create tiles for Canada for use with ClimateNA; -## 2. Download and process data for each tile using ClimateNA; -## 3. Archive and upload each set of tiles for use with canClimateData. - -stop( - "Superseded by the targets pipeline in data-raw/pipeline/ (vignette 'maintaining-climate-data'). ", - "This script ends by copying its working index over the shipped release index.", - call. = FALSE -) - -# setup --------------------------------------------------------------------------------------- - -source("data-raw/01-ClimateNA_setup.R") - -runClimateNA <- FALSE ## TRUE -fileChecksums <- FALSE ## TRUE -createZips <- FALSE ## TRUE -uploadArchives <- FALSE ## TRUE - -climateType <- "future_normals" - -if (isTRUE(fileChecksums)) { - csdb <- checksums_sql(wrkngDBfile, climateType) - checksums_db <- csdb[["db"]] - checksums_futu_normals_df <- csdb[["df"]] - rm(csdb) -} - -dbdf <- ClimateNA_sql(wrkngDBfile, climateType) -climate_db <- dbdf[["db"]] -climate_futu_normals_df <- dbdf[["df"]] -rm(dbdf) - -MSYs <- c("Y") -GCMs <- available(climateType)[["gcms"]] -SSPs <- available(climateType)[["ssps"]] -future_nrm_prds <- available(climateType)[["periods"]] -future_nrm <- paste0(future_nrm_prds, ".gcm") ## TODO: need to combine gcm, ssp, period - -if (!exists("dem_ff")) { - dem_ff <- list.files(file.path(ClimateNAdata, "dem"), pattern = "[.]asc$", full.names = TRUE) - stopifnot(length(dem_ff) > 0) -} - -plan("callr", workers = min(length(dem_ff), maxCores)) - -# get ClimateNA future normals -------------------------------------------------------------- - -new_rows_futu_normals <- future.apply::future_lapply( - dem_ff, - function(f) { - dbdf <- climateData::ClimateNA_sql(wrkngDBfile, climateType) - climate_db <- dbdf[["db"]] - climate_futu_normals_df <- dbdf[["df"]] - rm(dbdf) - - f <- normalizePath(f) - tile <- climateData::tileID(f) - - z <- lapply(MSYs, function(msy) { - lapply(future_nrm, function(nrm) { - ClimateNAout <- climateData::ClimateNA_path( - ClimateNAdata, - tile = tile, - type = climateType, - msy, - gcm, - ssp - ) - - period <- substr(nrm, 8, 16) - - row <- dplyr::filter( - climate_futu_normals_df, - gcm == !!gcm & ssp == !!ssp & msy == !!msy & period == !!period & tileid == !!tile - ) |> - dplyr::collect() - - if (nrow(row) == 0) { - if (isTRUE(runClimateNA)) { - withr::local_dir(ClimateNAdir) - sys::exec_wait( - ClimateNAexe, - args = c( - paste0("/", msy), - paste0("/", gcm, "_ssp", ssp, "@", nrm, ".gcm"), - paste0("/", f), - paste0("/", ClimateNAout) - ) - ) - withr::deferred_run() - } - - new_row <- data.frame( - msy = msy, - period = period, - tileid = tile, - created = file.info(ClimateNAout)$mtime, - stringsAsFactors = FALSE - ) - # rows_append(climate_futu_normals_df, new_row, copy = TRUE, in_place = TRUE) - } else { - new_row <- dplyr::mutate(row, created = file.info(ClimateNAout)$mtime) - # rows_update(climate_futu_normals_df, new_row, copy = TRUE, in_place = TRUE, unmatched = "ignore") - } - - return(new_row) - }) |> - dplyr::bind_rows() - }) |> - dplyr::bind_rows() - - DBI::dbDisconnect(climate_db) - - return(z) - }, - future.seed = NULL -) |> - dplyr::bind_rows() - -if (!"rowid" %in% colnames(new_rows_futu_normals)) { - new_rows_futu_normals <- tibble::rowid_to_column(new_rows_futu_normals) - dplyr::rows_append(climate_futu_normals_df, new_rows_futu_normals, copy = TRUE, in_place = TRUE) -} else { - dplyr::rows_update( - climate_futu_normals_df, - new_rows_futu_normals, - copy = TRUE, - in_place = TRUE, - unmatched = "ignore" - ) -} - -DBI::dbDisconnect(climate_db) - -file.copy(wrkngDBfile, addlDBfile, overwrite = TRUE) - -# checksums ----------------------------------------------------------------------------------- - -checksums_futu_normals <- future.apply::future_lapply( - dem_ff, - function(f) { - tile <- normalizePath(f) |> climateData::tileID() - - lapply(GCMs, function(gcm) { - lapply(SSPs, function(ssp) { - lapply(MSYs, function(msy) { - lapply(future_nrm, function(nrm) { - ClimateNAout <- climateData::ClimateNA_path( - ClimateNAdata, - tile = tile, - type = climateType, - msy, - gcm, - ssp - ) - - period <- substr(nrm, 8, 16) - - digs <- file.path(ClimateNAout, paste0(tools::file_path_sans_ext(nrm), "Y")) |> - fs::dir_ls(type = "file") |> - vapply(digest::digest, file = TRUE, algo = "xxhash64", FUN.VALUE = character(1)) - - checksums <- data.frame( - msy = msy, - period = period, - tileid = tile, - filename = basename(names(digs)), - filehash = unname(digs), - stringsAsFactors = FALSE - ) - - return(checksums) - }) |> - dplyr::bind_rows() - }) |> - dplyr::bind_rows() - }) |> - dplyr::bind_rows() - }) |> - dplyr::bind_rows() - }, - future.seed = NULL -) |> - dplyr::bind_rows() - -if (!"id" %in% colnames(checksums_futu_normals)) { - dplyr::rows_append( - checksums_futu_normals_df, - checksums_futu_normals, - copy = TRUE, - in_place = TRUE - ) -} else { - dplyr::rows_update( - checksums_futu_normals_df, - checksums_futu_normals, - copy = TRUE, - in_place = TRUE, - unmatched = "ignore" - ) -} - -DBI::dbDisconnect(checksums_db) -DBI::dbDisconnect(climate_db) - -file.copy(wrkngDBfile, addlDBfile, overwrite = TRUE) - -# archive tilesets ---------------------------------------------------------------------------- - -if (createZips) { - ## future normals - new_rows_futu_normals <- future.apply::future_lapply(dem_ff, function(f) { - dbdf <- climateData::ClimateNA_sql(wrkngDBfile, climateType) - climate_db <- dbdf[["db"]] - climate_futu_normals_df <- dbdf[["df"]] - rm(dbdf) - - tile <- normalizePath(f) |> climateData::tileID() - - z <- lapply(GCMs, function(gcm) { - lapply(SSPs, function(ssp) { - lapply(MSYs, function(msy) { - lapply(future_nrm, function(nrm) { - ClimateNAout <- climateData::ClimateNA_path( - ClimateNAdata, - tile = tile, - type = climateType, - msy, - gcm, - ssp - ) - - fzip <- paste0(ClimateNAout, "_normals_", msy, ".zip") - - row <- dplyr::filter( - climate_futu_normals_df, - gcm == !!gcm & ssp == !!ssp & msy == !!msy & period %in% !!period & tileid == !!tile - ) |> - dplyr::collect() - - archive::archive_write_dir(archive = fzip, dir = ClimateNAout) - - new_row <- dplyr::mutate( - row, - archived = file.info(fzip)$mtime, - zipfile = fs::path_rel(fzip, ClimateNAdata) - ) - # rows_update(climate_futu_normals_df, new_row, copy = TRUE, in_place = TRUE, unmatched = "ignore") - - return(new_row) - }) |> - dplyr::bind_rows() - }) |> - dplyr::bind_rows() - }) |> - dplyr::bind_rows() - }) |> - dplyr::bind_rows() - - DBI::dbDisconnect(climate_db) - - return(z) - }) |> - dplyr::bind_rows() - - dplyr::rows_update( - climate_futu_normals_df, - new_rows_futu_normals, - copy = TRUE, - in_place = TRUE, - unmatched = "ignore" - ) - - DBI::dbDisconnect(climate_db) - - file.copy(wrkngDBfile, addlDBfile, overwrite = TRUE) -} - -# upload tilesets ----------------------------------------------------------------------------- - -if (uploadArchives) { - plan("callr", workers = 8L) ## don't want too many parallel uploads - - gids_futu_normals <- list(Y = "1FStzgwcLMz4gky2UJtt9z5U8MWR1A94k") - - ## future normals - new_rows_futu_normals <- future.apply::future_lapply(dem_ff, function(f) { - googledrive::drive_auth(email = userEmail, cache = oauthCachePath) - - dbdf <- climateData::ClimateNA_sql(wrkngDBfile, climateType) - climate_db <- dbdf[["db"]] - climate_futu_normals_df <- dbdf[["df"]] - rm(dbdf) - - tile <- normalizePath(f) |> climateData::tileID() - - z <- lapply(GCMs, function(gcm) { - lapply(SSPs, function(ssp) { - lapply(MSYs, function(msy) { - lapply(future_nrm, function(nrm) { - ClimateNAout <- climateData::ClimateNA_path( - ClimateNAdata, - tile = tile, - type = climateType, - msy, - gcm, - ssp - ) - - fzip <- paste0(ClimateNAout, "_normals_", msy, ".zip") - - row <- dplyr::filter( - climate_futu_normals_df, - gcm == !!gcm & ssp == !!ssp & msy == !!msy & period %in% !!period & tileid == !!tile - ) |> - dplyr::collect() - - gt <- googledrive::drive_put( - media = fzip, - path = googledrive::as_id(gids_futu_normals[[msy]]) - ) - - new_row <- dplyr::mutate(row, uploaded = Sys.time(), gid = gt$id) - # rows_update(climate_futu_normals_df, new_row, copy = TRUE, in_place = TRUE, unmatched = "ignore") - - return(new_row) - }) |> - dplyr::bind_rows() - }) |> - dplyr::bind_rows() - }) |> - dplyr::bind_rows() - }) |> - dplyr::bind_rows() - - DBI::dbDisconnect(climate_db) - - return(z) - }) |> - dplyr::bind_rows() - - dplyr::rows_update( - climate_futu_normals_df, - new_rows_futu_normals, - copy = TRUE, - in_place = TRUE, - unmatched = "ignore" - ) - - DBI::dbDisconnect(climate_db) - - file.copy(wrkngDBfile, addlDBfile, overwrite = TRUE) -} - -## copy updated db to package data folder + remove working copy -file.copy(wrkngDBfile, addlDBfile, overwrite = TRUE) -file.copy(wrkngDBfile, pkgDBfile, overwrite = TRUE) -unlink(wrkngDBfile) diff --git a/data-raw/03-ClimateNA_historical.R b/data-raw/03-ClimateNA_historical.R deleted file mode 100644 index c642f57..0000000 --- a/data-raw/03-ClimateNA_historical.R +++ /dev/null @@ -1,416 +0,0 @@ -## 1. Create tiles for Canada for use with ClimateNA; -## 2. Download and process data for each tile using ClimateNA; -## 3. Archive and upload each set of tiles for use with canClimateData. - -stop( - "Superseded by the targets pipeline in data-raw/pipeline/ (vignette 'maintaining-climate-data'). ", - "This script ends by copying its working index over the shipped release index.", - call. = FALSE -) - -# setup --------------------------------------------------------------------------------------- - -source("data-raw/01-ClimateNA_setup.R") - -runClimateNA <- FALSE ## TRUE -fileChecksums <- TRUE -createZips <- FALSE ## TRUE -uploadArchives <- FALSE ## TRUE -reuploadArchives <- FALSE ## TRUE - -climateType <- "historical" - -if (isTRUE(fileChecksums)) { - csdb <- checksums_sql(wrkngDBfile, climateType) - checksums_db <- csdb[["db"]] - checksums_historical_df <- csdb[["df"]] - rm(csdb) -} - -dbdf <- ClimateNA_sql(wrkngDBfile, climateType) -climate_db <- dbdf[["db"]] -climate_historical_df <- dbdf[["df"]] -rm(dbdf) - -MSYs <- c("MSY", "M", "S", "Y") - -historical_years <- available(climateType)[["years"]] -# historical_years <- 1901L:1990L -# historical_years <- 1991L:2024L -historical_decades <- (historical_years %/% 10 * 10) |> unique() |> as.integer() -period_ann <- paste0("Year_", historical_years, ".ann") - -if (!exists("dem_ff")) { - dem_ff <- list.files(file.path(ClimateNAdata, "dem"), pattern = "[.]asc$", full.names = TRUE) - stopifnot(length(dem_ff) > 0) -} - -# plan(sequential) -plan("callr", workers = min(length(dem_ff), maxCores)) - -# get ClimateNA historical time series ---------------------------------------------------------- - -progressr::with_progress({ - p <- progressr::progressor(along = dem_ff) - new_rows_historic <- future.apply::future_lapply( - dem_ff, - function(f) { - dbdf <- climateData::ClimateNA_sql(wrkngDBfile, climateType) - climate_db <- dbdf[["db"]] - climate_historical_df <- dbdf[["df"]] - rm(dbdf) - - f <- normalizePath(f) - tile <- climateData::tileID(f) - - z <- lapply(MSYs, function(msy) { - lapply(period_ann, function(ann) { - ClimateNAout <- climateData::ClimateNA_path( - ClimateNAdata, - tile = tile, - type = climateType, - msy - ) - - yr <- as.integer(substr(ann, 6, 9)) - - row <- dplyr::filter( - climate_historical_df, - msy == !!msy & year == !!yr & tileid == !!tile - ) |> - dplyr::collect() - - if (nrow(row) == 0) { - if (isTRUE(runClimateNA)) { - message(glue::glue("Running ClimateNA for tile {tile}: {ann} {msy} ...")) - withr::local_dir(ClimateNAdir) - sys::exec_wait( - ClimateNAexe, - args = c( - paste0("/", msy), - paste0("/", ann), - paste0("/", f), - paste0("/", ClimateNAout) - ) - ) - withr::deferred_run() - message(glue::glue("... completed ClimateNA for tile {tile}: {ann} {msy}")) - } - - new_row <- data.frame( - ## id will be filled automatically - msy = msy, - year = yr, - tileid = tile, - created = file.info(ClimateNAout)$mtime, - stringsAsFactors = FALSE - ) - # rows_append(climate_historical_df, new_row, copy = TRUE, in_place = TRUE) - } else { - message(glue::glue("Skipping ClimateNA for tile {tile}: {ann} {msy}.")) - new_row <- dplyr::mutate(row, created = file.info(ClimateNAout)$mtime) - # rows_update(climate_historical_df, new_row, copy = TRUE, in_place = TRUE, unmatched = "ignore") - } - - return(new_row) - }) |> - dplyr::bind_rows() - }) |> - dplyr::bind_rows() - - DBI::dbDisconnect(climate_db) - - p(sprintf("tile = %g", tile)) - - return(z) - }, - future.seed = NULL - ) -}) -new_rows_historic <- dplyr::bind_rows(new_rows_historic) - -if (!"rowid" %in% colnames(new_rows_historic)) { - new_rows_historic <- tibble::rowid_to_column(new_rows_historic) - dplyr::rows_append(climate_historical_df, new_rows_historic, copy = TRUE, in_place = TRUE) -} else { - dplyr::rows_update( - climate_historical_df, - new_rows_historic, - copy = TRUE, - in_place = TRUE, - unmatched = "ignore" - ) -} - -DBI::dbDisconnect(climate_db) - -file.copy(wrkngDBfile, addlDBfile, overwrite = TRUE) - -# checksums ----------------------------------------------------------------------------------- - -# plan(sequential) -# plan("callr", workers = min(length(dem_ff), maxCores)) - -progressr::with_progress({ - p <- progressr::progressor(steps = length(dem_ff) * length(MSYs) * length(period_ann)) - checksums_historic <- future.apply::future_lapply( - dem_ff, - function(f) { - tile <- normalizePath(f) |> climateData::tileID() - - z <- lapply(MSYs, function(msy) { - zz <- lapply(period_ann, function(ann) { - ClimateNAout <- climateData::ClimateNA_path( - ClimateNAdata, - tile = tile, - type = climateType, - msy - ) - - yr <- as.integer(substr(ann, 6, 9)) - - digs <- file.path(ClimateNAout, paste0(tools::file_path_sans_ext(ann), msy)) |> - fs::dir_ls(type = "file") |> - vapply(digest::digest, file = TRUE, algo = "xxhash64", FUN.VALUE = character(1)) - - checksums <- data.frame( - msy = msy, - year = yr, - tileid = tile, - filename = basename(names(digs)), - filehash = unname(digs), - stringsAsFactors = FALSE - ) - - p(sprintf("tile = %g; MSY = %s; period_ann = %s", tile, msy, ann)) - - return(checksums) - }) |> - dplyr::bind_rows() - - return(zz) - }) |> - dplyr::bind_rows() - - return(z) - }, - future.globals = c("ClimateNAdata", "climateType", "MSYs", "period_ann", "p"), - future.seed = NULL - ) -}) -checksums_historic <- dplyr::bind_rows(checksums_historic) - -if (!"id" %in% colnames(checksums_historic)) { - dplyr::rows_append(checksums_historical_df, checksums_historic, copy = TRUE, in_place = TRUE) -} else { - dplyr::rows_update( - checksums_historical_df, - checksums_historic, - copy = TRUE, - in_place = TRUE, - unmatched = "ignore" - ) -} - -DBI::dbDisconnect(checksums_db) -DBI::dbDisconnect(climate_db) - -file.copy(wrkngDBfile, addlDBfile, overwrite = TRUE) - -# archive tilesets ---------------------------------------------------------------------------- - -if (createZips) { - # plan(sequential) - # plan("callr", workers = min(length(dem_ff), maxCores)) - - ## historical time series - progressr::with_progress({ - p <- progressr::progressor(steps = length(dem_ff) * length(MSYs) * length(historical_decades)) - new_rows_historic <- future.apply::future_lapply( - dem_ff, - function(f) { - dbdf <- climateData::ClimateNA_sql(wrkngDBfile, climateType) - climate_db <- dbdf[["db"]] - climate_historical_df <- dbdf[["df"]] - rm(dbdf) - - tile <- normalizePath(f) |> climateData::tileID() - - z <- lapply(MSYs, function(msy) { - ClimateNAout <- climateData::ClimateNA_path( - ClimateNAdata, - tile = tile, - type = climateType, - msy - ) - - lapply(historical_decades, function(dcd) { - fzip <- paste0(ClimateNAout, "_", msy, "_", dcd, ".zip") - - row <- dplyr::filter( - climate_historical_df, - msy == !!msy & year %in% !!(dcd + 0:9) & tileid == !!tile ## zip each decade - ) |> - dplyr::collect() - - files2add <- fs::dir_ls( - ClimateNAout, - regexp = paste0("Year_(", paste(dcd + 0:9, collapse = "|"), ")", msy, "$") - ) |> - fs::dir_ls() |> - fs::path_rel(ClimateNAout) - - withr::local_dir(ClimateNAout) - archive::archive_write_files(archive = fzip, files = files2add) - withr::deferred_run() - - new_row <- dplyr::mutate( - row, - archived = file.info(fzip)$mtime, - zipfile = fs::path_rel(fzip, ClimateNAdata) - ) - # rows_update(climate_historical_df, new_row, copy = TRUE, in_place = TRUE, unmatched = "ignore") - - p(sprintf("tile = %g; MSY = %s; historical_decade = %g", tile, msy, dcd)) - - return(new_row) - }) |> - dplyr::bind_rows() - }) |> - dplyr::bind_rows() - - DBI::dbDisconnect(climate_db) - - return(z) - }, - future.globals = c( - "ClimateNAdata", - "climateType", - "historical_decades", - "MSYs", - "p", - "wrkngDBfile" - ), - future.seed = NULL - ) - }) - new_rows_historic <- dplyr::bind_rows(new_rows_historic) - - rows_update( - climate_historical_df, - new_rows_historic, - copy = TRUE, - in_place = TRUE, - unmatched = "ignore" - ) - - DBI::dbDisconnect(climate_db) - - file.copy(wrkngDBfile, addlDBfile, overwrite = TRUE) -} - -# upload tilesets ----------------------------------------------------------------------------- - -if (uploadArchives) { - plan("callr", workers = 8L) ## don't want too many parallel uploads - - gids_historic <- list( - MSY = "1r9yZMlXDqEQxBX2aQeDBAkHlzegqZRLL", - M = "1E3PNXb_ti5a6JSzmBkrRP5UQ-y6Bco7A", - Y = "1bp6UX5b9nczub0OG41YAhOQUmyerywc6" - ) - - ## historical time series - progressr::with_progress({ - p <- progressr::progressor(steps = length(dem_ff) * length(MSYs) * length(historical_decades)) - new_rows_historic <- future.apply::future_lapply( - dem_ff, - function(f) { - googledrive::drive_auth(email = userEmail, cache = oauthCachePath) - - dbdf <- climateData::ClimateNA_sql(wrkngDBfile, climateType) - climate_db <- dbdf[["db"]] - climate_historical_df <- dbdf[["df"]] - rm(dbdf) - - tile <- normalizePath(f) |> climateData::tileID() - - z <- lapply(MSYs, function(msy) { - ClimateNAout <- climateData::ClimateNA_path( - ClimateNAdata, - tile = tile, - type = climateType, - msy - ) - - gid <- googledrive::as_id(gids_historic[[msy]]) - drivefiles <- googledrive::drive_ls(gid) - - lapply(historical_decades, function(dcd) { - fzip <- paste0(ClimateNAout, "_", msy, "_", dcd, ".zip") - - row <- dplyr::filter( - climate_historical_df, - msy == !!msy & year %in% !!(dcd + 0:9) & tileid == !!tile ## zip each decade - ) |> - dplyr::collect() - - if (reuploadArchives) { - gt <- googledrive::drive_put(media = fzip, path = googledrive::as_id(gid)) - } else { - gt <- dplyr::filter(drivefiles, name == basename(fzip)) - - if (nrow(gt) == 0) { - gt <- googledrive::drive_put(media = fzip, path = googledrive::as_id(gid)) - } - } - - new_row <- dplyr::mutate(row, uploaded = Sys.time(), gid = gt$id) - # rows_update(climate_hist_normals_df, new_row, copy = TRUE, in_place = TRUE, unmatched = "ignore") - - p(sprintf("tile = %g; MSY = %s; historical_decade = %g", tile, msy, dcd)) - - return(new_row) - }) |> - dplyr::bind_rows() - }) |> - dplyr::bind_rows() - - DBI::dbDisconnect(climate_db) - - return(z) - }, - future.globals = c( - "ClimateNAdata", - "climateType", - "gids_historic", - "historical_decades", - "MSYs", - "oauthCachePath", - "p", - "reuploadArchives", - "userEmail", - "wrkngDBfile" - ), - future.seed = NULL - ) - }) - new_rows_historic <- dplyr::bind_rows(new_rows_historic) - - rows_update( - climate_historical_df, - new_rows_historic, - copy = TRUE, - in_place = TRUE, - unmatched = "ignore" - ) - - DBI::dbDisconnect(climate_db) - - file.copy(wrkngDBfile, addlDBfile, overwrite = TRUE) -} - -## copy updated db to package data folder + remove working copy -file.copy(wrkngDBfile, addlDBfile, overwrite = TRUE) -file.copy(wrkngDBfile, pkgDBfile, overwrite = TRUE) -unlink(wrkngDBfile) diff --git a/data-raw/03-ClimateNA_historical_normals.R b/data-raw/03-ClimateNA_historical_normals.R deleted file mode 100644 index 1291169..0000000 --- a/data-raw/03-ClimateNA_historical_normals.R +++ /dev/null @@ -1,323 +0,0 @@ -## 1. Create tiles for Canada for use with ClimateNA; -## 2. Download and process data for each tile using ClimateNA; -## 3. Archive and upload each set of tiles for use with canClimateData. - -stop( - "Superseded by the targets pipeline in data-raw/pipeline/ (vignette 'maintaining-climate-data'). ", - "This script ends by copying its working index over the shipped release index.", - call. = FALSE -) - -# setup --------------------------------------------------------------------------------------- - -source("data-raw/01-ClimateNA_setup.R") - -runClimateNA <- FALSE ## TRUE -fileChecksums <- TRUE -createZips <- FALSE ## TRUE -uploadArchives <- FALSE ## TRUE - -climateType <- "historical_normals" - -if (isTRUE(fileChecksums)) { - csdb <- checksums_sql(wrkngDBfile, climateType) - checksums_db <- csdb[["db"]] - checksums_hist_normals_df <- csdb[["df"]] - rm(csdb) -} - -dbdf <- ClimateNA_sql(wrkngDBfile, climateType) -climate_db <- dbdf[["db"]] -climate_hist_normals_df <- dbdf[["df"]] -rm(dbdf) - -MSYs <- c("Y") -hist_nrm_prds <- available(climateType)[["periods"]] -period_nrm <- paste0("Normal_", hist_nrm_prds, ".nrm") - -if (!exists("dem_ff")) { - dem_ff <- list.files(file.path(ClimateNAdata, "dem"), pattern = "[.]asc$", full.names = TRUE) - stopifnot(length(dem_ff) > 0) -} - -plan("callr", workers = min(length(dem_ff), maxCores)) - -# get ClimateNA historical normals -------------------------------------------------------------- - -new_rows_hist_normals <- future.apply::future_lapply( - dem_ff, - function(f) { - dbdf <- climateData::ClimateNA_sql(wrkngDBfile, climateType) - climate_db <- dbdf[["db"]] - climate_hist_normals_df <- dbdf[["df"]] - rm(dbdf) - - f <- normalizePath(f) - tile <- climateData::tileID(f) - - z <- lapply(MSYs, function(msy) { - lapply(period_nrm, function(nrm) { - ClimateNAout <- climateData::ClimateNA_path( - ClimateNAdata, - tile = tile, - type = climateType, - msy = msy - ) - - period <- substr(nrm, 8, 16) - - row <- dplyr::filter( - climate_hist_normals_df, - msy == !!msy & period == !!period & tileid == !!tile - ) |> - dplyr::collect() - - if (nrow(row) == 0) { - if (isTRUE(runClimateNA)) { - withr::local_dir(ClimateNAdir) - sys::exec_wait( - ClimateNAexe, - args = c( - paste0("/", msy), - paste0("/", nrm), - paste0("/", f), - paste0("/", ClimateNAout) - ) - ) - withr::deferred_run() - } - - new_row <- data.frame( - msy = msy, - period = period, - tileid = tile, - created = file.info(ClimateNAout)$mtime, - stringsAsFactors = FALSE - ) - # rows_append(climate_hist_normals_df, new_row, copy = TRUE, in_place = TRUE) - } else { - new_row <- dplyr::mutate(row, created = file.info(ClimateNAout)$mtime) - # rows_update(climate_hist_normals_df, new_row, copy = TRUE, in_place = TRUE, unmatched = "ignore") - } - - return(new_row) - }) |> - dplyr::bind_rows() - }) |> - dplyr::bind_rows() - - DBI::dbDisconnect(climate_db) - - return(z) - }, - future.seed = NULL -) |> - dplyr::bind_rows() - -if (!"rowid" %in% colnames(new_rows_hist_normals)) { - new_rows_hist_normals <- tibble::rowid_to_column(new_rows_hist_normals) - dplyr::rows_append(climate_hist_normals_df, new_rows_hist_normals, copy = TRUE, in_place = TRUE) -} else { - dplyr::rows_update( - climate_hist_normals_df, - new_rows_hist_normals, - copy = TRUE, - in_place = TRUE, - unmatched = "ignore" - ) -} - -DBI::dbDisconnect(climate_db) - -file.copy(wrkngDBfile, addlDBfile, overwrite = TRUE) - -# checksums ----------------------------------------------------------------------------------- - -checksums_hist_normals <- future.apply::future_lapply( - dem_ff, - function(f) { - tile <- normalizePath(f) |> climateData::tileID() - - lapply(MSYs, function(msy) { - lapply(period_nrm, function(nrm) { - ClimateNAout <- climateData::ClimateNA_path( - ClimateNAdata, - tile = tile, - type = climateType, - msy = msy - ) - - period <- substr(nrm, 8, 16) - - digs <- file.path(ClimateNAout, paste0(tools::file_path_sans_ext(nrm), "Y")) |> - fs::dir_ls(type = "file") |> - vapply(digest::digest, file = TRUE, algo = "xxhash64", FUN.VALUE = character(1)) - - checksums <- data.frame( - msy = msy, - period = period, - tileid = tile, - filename = basename(names(digs)), - filehash = unname(digs), - stringsAsFactors = FALSE - ) - - return(checksums) - }) |> - dplyr::bind_rows() - }) |> - dplyr::bind_rows() - }, - future.seed = NULL -) |> - dplyr::bind_rows() - -if (!"id" %in% colnames(checksums_hist_normals)) { - dplyr::rows_append( - checksums_hist_normals_df, - checksums_hist_normals, - copy = TRUE, - in_place = TRUE - ) -} else { - dplyr::rows_update( - checksums_hist_normals_df, - checksums_hist_normals, - copy = TRUE, - in_place = TRUE, - unmatched = "ignore" - ) -} - -DBI::dbDisconnect(checksums_db) -DBI::dbDisconnect(climate_db) - -file.copy(wrkngDBfile, addlDBfile, overwrite = TRUE) - -# archive tilesets ---------------------------------------------------------------------------- - -if (createZips) { - ## historical normals - new_rows_hist_normals <- future.apply::future_lapply(dem_ff, function(f) { - dbdf <- climateData::ClimateNA_sql(wrkngDBfile, climateType) - climate_db <- dbdf[["db"]] - climate_hist_normals_df <- dbdf[["df"]] - rm(dbdf) - - tile <- normalizePath(f) |> climateData::tileID() - - z <- lapply(MSYs, function(msy) { - ClimateNAout <- climateData::ClimateNA_path( - ClimateNAdata, - tile = tile, - type = climateType, - msy = msy - ) - fzip <- paste0(ClimateNAout, "_normals_", msy, ".zip") - - row <- dplyr::filter( - climate_hist_normals_df, - msy == !!msy & tileid == !!tile ## all periods put into same zipfile - ) |> - dplyr::collect() - - archive::archive_write_dir(archive = fzip, dir = ClimateNAout) - - new_row <- dplyr::mutate( - row, - archived = file.info(fzip)$mtime, - zipfile = fs::path_rel(fzip, ClimateNAdata) - ) - # rows_update(climate_hist_normals_df, new_row, copy = TRUE, in_place = TRUE, unmatched = "ignore") - - return(new_row) - }) |> - dplyr::bind_rows() - - DBI::dbDisconnect(climate_db) - - return(z) - }) |> - dplyr::bind_rows() - - dplyr::rows_update( - climate_hist_normals_df, - new_rows_hist_normals, - copy = TRUE, - in_place = TRUE, - unmatched = "ignore" - ) - - DBI::dbDisconnect(climate_db) - - file.copy(wrkngDBfile, addlDBfile, overwrite = TRUE) -} - -# upload tilesets ----------------------------------------------------------------------------- - -if (uploadArchives) { - plan("callr", workers = 8L) ## don't want too many parallel uploads - - gids_hist_normals <- list(Y = "1FStzgwcLMz4gky2UJtt9z5U8MWR1A94k") - - ## historical normals - new_rows_hist_normals <- future.apply::future_lapply(dem_ff, function(f) { - googledrive::drive_auth(email = userEmail, cache = oauthCachePath) - - dbdf <- climateData::ClimateNA_sql(wrkngDBfile, climateType) - climate_db <- dbdf[["db"]] - climate_hist_normals_df <- dbdf[["df"]] - rm(dbdf) - - tile <- normalizePath(f) |> climateData::tileID() - - z <- lapply(MSYs, function(msy) { - ClimateNAout <- climateData::ClimateNA_path( - ClimateNAdata, - tile = tile, - type = climateType, - msy = msy - ) - fzip <- paste0(ClimateNAout, "_normals_", msy, ".zip") - - row <- dplyr::filter( - climate_hist_normals_df, - msy == !!msy & tileid == !!tile ## all periods put into same zipfile - ) |> - dplyr::collect() - - gt <- googledrive::drive_put( - media = fzip, - path = googledrive::as_id(gids_hist_normals[[msy]]) - ) - - new_row <- dplyr::mutate(row, uploaded = Sys.time(), gid = gt$id) - # rows_update(climate_hist_normals_df, new_row, copy = TRUE, in_place = TRUE, unmatched = "ignore") - - return(new_row) - }) |> - dplyr::bind_rows() - - DBI::dbDisconnect(climate_db) - - return(z) - }) |> - dplyr::bind_rows() - - dplyr::rows_update( - climate_hist_normals_df, - new_rows_hist_normals, - copy = TRUE, - in_place = TRUE, - unmatched = "ignore" - ) - - DBI::dbDisconnect(climate_db) - - file.copy(wrkngDBfile, addlDBfile, overwrite = TRUE) -} - -## copy updated db to package data folder + remove working copy -file.copy(wrkngDBfile, addlDBfile, overwrite = TRUE) -file.copy(wrkngDBfile, pkgDBfile, overwrite = TRUE) -unlink(wrkngDBfile) diff --git a/data-raw/04-audit_archives.R b/data-raw/04-audit_archives.R deleted file mode 100644 index 9ff4bb8..0000000 --- a/data-raw/04-audit_archives.R +++ /dev/null @@ -1,431 +0,0 @@ -## Audit of the published ClimateNA zips (read-only). -## -## For every zip listed in the tile index, check that it holds every year (or normals period) -## folder the index claims, with every expected variable file present and non-empty. Where the -## local zip on the share is the same file as on Google Drive (same MD5), check the local copy; -## otherwise download the Drive copy and check that. For each incomplete zip, check whether the -## raw ClimateNA outputs on the share are complete enough to rebuild it. -## -## Writes, in `auditDir` on the share: -## - zips.csv: one row per zip (Drive ID), with its check result and repair class; -## - report.csv: one row per problem found; -## - climatena_reruns.csv: raw output folders that are missing or incomplete; -## - summary.md: counts and the list of repairable zips; -## - downloads/: Drive copies of incomplete zips, kept as the backup source for the repair. -## -## Nothing is changed on Google Drive, in the index, or on the share outside `auditDir`. -## Repairs are made by 05-repair_archives.R, from a reviewed zips.csv. - -## To audit a release built by the pipeline (data-raw/pipeline/), set these before sourcing this -## script, after authenticating googledrive, from the package root: -## auditIndex <- "/ClimateNA_tiles.sqlite" # the release's index -## auditZipRoot <- "/zips" # its local zips, by the index's zipfile -## auditDriveFolders <- list(release = "") -## auditDir <- "/_audit/" -## auditTypes <- c("historical", "historical_normals", "future", "future_normals") -## The raw-output check (repair classes) applies only to the pre-pipeline share layout; for a -## release, an incomplete zip is classed "rerun_pipeline". -releaseAudit <- exists("auditIndex") -if (releaseAudit) { - stopifnot(exists("auditZipRoot"), exists("auditDriveFolders"), exists("auditDir")) - devtools::load_all(".", quiet = TRUE) -} else { - source("data-raw/01-ClimateNA_setup.R") - auditIndex <- wrkngDBfile - auditZipRoot <- ClimateNAdata - auditDir <- file.path(ClimateNAdata, "_audit", format(Sys.Date())) -} - -## set these before sourcing this script to audit a subset -if (!exists("auditTypes")) { - auditTypes <- c("historical", "historical_normals", "future") -} -if (!exists("auditTiles")) { - auditTiles <- NULL ## NULL means all tiles; otherwise an integer vector of tile IDs -} -nCores <- 16L ## parallel workers for reading local zips and raw folders on the share -downloadDir <- file.path(auditDir, "downloads") -dir.create(downloadDir, recursive = TRUE, showWarnings = FALSE) -checked <- as.numeric(Sys.time()) - -## Drive folders holding the published zips (from the upload sections of the 03-*.R scripts) -driveFolders <- list( - historical = c( - MSY = "1r9yZMlXDqEQxBX2aQeDBAkHlzegqZRLL", - M = "1E3PNXb_ti5a6JSzmBkrRP5UQ-y6Bco7A", - Y = "1bp6UX5b9nczub0OG41YAhOQUmyerywc6" - ), - historical_normals = c(Y = "1FStzgwcLMz4gky2UJtt9z5U8MWR1A94k"), - future = c(all = "1DH_JF6ZluYsZUpHGRXpXI8Q-DOUOE9AY") ## one subfolder per GCM x SSP -) -if (!releaseAudit) { - auditDriveFolders <- driveFolders[auditTypes] -} - -# index --------------------------------------------------------------------------------------- - -db <- DBI::dbConnect(RSQLite::SQLite(), auditIndex, flags = RSQLite::SQLITE_RO) -index <- lapply(auditTypes, function(type) { - x <- DBI::dbReadTable(db, type) - if (!is.null(auditTiles)) { - x <- x[x$tileid %in% auditTiles, , drop = FALSE] - } - x -}) |> - setNames(auditTypes) -DBI::dbDisconnect(db) - -zips <- lapply(auditTypes, function(type) { - x <- index[[type]] - keys <- intersect(c("gid", "zipfile", "tileid", "gcm", "ssp", "msy"), names(x)) - z <- unique(x[keys]) - z$type <- type - z -}) |> - dplyr::bind_rows() -## one zip per Drive ID: rows sharing a gid must agree on zipfile, tile, msy, gcm and ssp -dupGids <- unique(zips$gid[duplicated(zips$gid)]) -if (length(dupGids) > 0) { - stop( - "Index rows sharing a Drive ID disagree on the zip they describe (zipfile, tileid, ", - "msy, gcm or ssp). Drive IDs: ", - paste(dupGids, collapse = ", "), - call. = FALSE - ) -} - -message("Auditing ", nrow(zips), " zips in ", auditDir) - -## index rows that available() allows but the index lacks -indexGaps <- lapply(auditTypes, function(type) { - g <- .archiveIndexGaps(index[[type]], type) - if (nrow(g) == 0) { - return(NULL) - } - data.frame( - gid = NA_character_, - type = type, - zipfile = NA_character_, - tileid = g$tileid, - gcm = g$gcm %||% NA_character_, - ssp = g$ssp %||% NA_character_, - msy = g$msy, - decade_or_period = as.character(g$year %||% g$period), - problem = "index_gap", - item = as.character(g$year %||% g$period), - repair = NA_character_ - ) -}) |> - dplyr::bind_rows() - -# Drive metadata ------------------------------------------------------------------------------ - -driveMeta <- function(d) { - res <- d$drive_resource - data.frame( - id = d$id, - name = d$name, - md5 = vapply(res, \(r) r$md5Checksum %||% NA_character_, character(1)), - size = vapply(res, \(r) as.numeric(r$size %||% NA), numeric(1)), - trashed = vapply(res, \(r) isTRUE(r$trashed), logical(1)) - ) -} - -meta <- unlist(auditDriveFolders, use.names = FALSE) |> - lapply(\(f) googledrive::drive_ls(googledrive::as_id(f), recursive = TRUE)) |> - dplyr::bind_rows() |> - driveMeta() -meta <- meta[meta$id %in% zips$gid, , drop = FALSE] - -## IDs not found in the folders: look each one up (it may be trashed, moved, or gone) -notListed <- setdiff(zips$gid, meta$id) -if (length(notListed) > 0) { - message("Looking up ", length(notListed), " Drive IDs not found in the expected folders") - found <- lapply(notListed, function(id) { - tryCatch(googledrive::drive_get(googledrive::as_id(id)), error = \(e) NULL) - }) - found <- found[!vapply(found, is.null, logical(1))] - if (length(found) > 0) { - meta <- rbind(meta, driveMeta(dplyr::bind_rows(found))) - } -} - -driveProblems <- .driveProblems(zips, meta) -m <- meta[match(zips$gid, meta$id), , drop = FALSE] -zips$md5_drive <- m$md5 -zips$size <- m$size -zips$on_drive <- !zips$gid %in% driveProblems$gid[driveProblems$problem == "drive_missing"] - -# check each zip ------------------------------------------------------------------------------ - -rowsByGid <- lapply(index, \(x) split(x, x$gid)) |> unname() |> do.call(what = c) -expected <- lapply(seq_len(nrow(zips)), function(i) { - .archiveExpected(rowsByGid[[zips$gid[i]]], zips$type[i]) -}) - -## mclapply() returns a worker's error as a "try-error" value instead of stopping -stopOnWorkerErrors <- function(x, what) { - bad <- vapply(x, inherits, logical(1), "try-error") - if (any(bad)) { - stop(what, " failed for ", sum(bad), " zips; first error: ", x[[which(bad)[1]]], call. = FALSE) - } - x -} - -## local zips: MD5 and listing, in parallel (reads from the share) -## a zip that can't be read is reported (problem "unreadable_zip") and checked as empty, -## so its folders show as missing, rather than stopping the audit -readListing <- function(f) { - l <- tryCatch(.zipListing(f), error = \(e) e) - if (inherits(l, "error")) { - return(list( - listing = data.frame(path = character(0), size = numeric(0)), - error = conditionMessage(l) - )) - } - list(listing = l, error = NA_character_) -} - -message("Reading local zips") -local <- parallel::mclapply( - file.path(auditZipRoot, zips$zipfile), - function(f) { - if (!file.exists(f)) { - return(list(md5 = NA_character_, listing = NULL, error = NA_character_)) - } - c(list(md5 = unname(tools::md5sum(f))), readListing(f)) - }, - mc.cores = nCores -) |> - stopOnWorkerErrors("Reading the local zip") -zips$md5_local <- vapply(local, `[[`, character(1), "md5") - -## zips whose local copy is missing or differs from Drive: check the Drive copy -useLocal <- !is.na(zips$md5_local) & !is.na(zips$md5_drive) & zips$md5_local == zips$md5_drive -toDownload <- which(!useLocal & zips$on_drive) -message("Downloading ", length(toDownload), " zips whose local copy is missing or differs") -listings <- lapply(local, `[[`, "listing") -unreadable <- vapply(local, `[[`, character(1), "error") -unreadable[!useLocal] <- NA_character_ -zips$source <- ifelse(useLocal, "local", "none") -for (i in toDownload) { - dl <- file.path(downloadDir, basename(zips$zipfile[i])) - ok <- tryCatch( - { - googledrive::drive_download(googledrive::as_id(zips$gid[i]), path = dl, overwrite = TRUE) - TRUE - }, - error = function(e) { - message("Download failed for ", zips$zipfile[i], ": ", conditionMessage(e)) - FALSE - } - ) - if (ok) { - r <- readListing(dl) - listings[[i]] <- r$listing - unreadable[i] <- r$error - zips$source[i] <- "drive" - } -} - -## Expected names are those ClimateNA v7.60+ writes. Folders still holding the pre-v7.60 -## radiation names (Rad*, MAR) are checked against those names, so missing data stays -## visible; they are counted in `legacy_folders`, and their zips need regenerating. -checkListing <- function(listing, expected) { - e <- .archiveExpectedByVersion(listing, expected) - list(problems = .archiveCheck(listing, e$expected), legacy = length(e$legacyFolders)) -} - -checks <- lapply(seq_len(nrow(zips)), function(i) { - if (zips$source[i] == "none") { - return(list(problems = data.frame(problem = character(0), item = character(0)), legacy = NA)) - } - checkListing(listings[[i]], expected[[i]]) -}) -problems <- lapply(checks, `[[`, "problems") -zips$n_expected <- lengths(expected) -zips$n_files <- vapply(listings, \(l) if (is.null(l)) NA_integer_ else nrow(l), integer(1)) -zips$legacy_folders <- vapply(checks, \(x) as.integer(x$legacy), integer(1)) -zips$complete <- ifelse(zips$source == "none", NA, vapply(problems, .archiveComplete, logical(1))) -zips$local_complete <- vapply( - seq_len(nrow(zips)), - function(i) { - l <- local[[i]]$listing - if (is.null(l)) NA else .archiveComplete(checkListing(l, expected[[i]])$problems) - }, - logical(1) -) - -## keep downloads only for incomplete zips: they are the backup source for the repair -for (i in which(zips$source == "drive" & zips$complete %in% TRUE)) { - unlink(file.path(downloadDir, basename(zips$zipfile[i]))) -} - -# raw outputs for incomplete zips --------------------------------------------------------------- - -## the tile directory, without ClimateNA_path(), which creates directories -tileDirOf <- function(i) file.path(ClimateNAdata, dirname(zips$zipfile[i]), zips$tileid[i]) - -folderTime <- function(folder, msy) { - sub(paste0(msy, "$"), "", sub("^.*(@|Year_|Normal_)", "", folder)) -} - -incomplete <- which(zips$complete %in% FALSE) -## a release's raw outputs are the pipeline's, in its own layout: it reruns anything missing -raw <- if (releaseAudit) { - list() -} else { - message("Checking raw outputs for ", length(incomplete), " incomplete zips") - parallel::mclapply( - incomplete, - function(i) { - folders <- unique(dirname(expected[[i]])) - checkListing(.dirListing(tileDirOf(i), folders), expected[[i]])$problems - }, - mc.cores = nCores - ) |> - stopOnWorkerErrors("Checking the raw outputs") -} -## complete zips made before ClimateNA v7.60 need regenerating for the rsds names -## zips not checked (missing on Drive, or the download failed) get no repair class -zips$repair <- ifelse( - !zips$complete %in% TRUE, - NA_character_, - ifelse(zips$legacy_folders %in% 0L, "none", "regenerate_v760") -) -zips$repair[incomplete] <- if (releaseAudit) { - rep("rerun_pipeline", length(incomplete)) -} else { - ifelse(vapply(raw, .archiveComplete, logical(1)), "repairable", "needs_climatena") -} - -reruns <- lapply(seq_along(raw), function(k) { - i <- incomplete[k] - p <- raw[[k]] - p <- p[p$problem %in% .archiveFailing, , drop = FALSE] - if (nrow(p) == 0) { - return(NULL) - } - folder <- ifelse(p$problem == "missing_folder", p$item, dirname(p$item)) |> unique() - data.frame( - type = zips$type[i], - tileid = zips$tileid[i], - gcm = zips$gcm[i] %||% NA_character_, - ssp = zips$ssp[i] %||% NA_character_, - msy = zips$msy[i], - year_or_period = folderTime(folder, zips$msy[i]), - folder = folder - ) -}) |> - dplyr::bind_rows() - -# outputs ------------------------------------------------------------------------------------- - -decadeOf <- function(zipfile) { - ifelse(grepl("_\\d{4}[.]zip$", zipfile), sub("^.*_(\\d{4})[.]zip$", "\\1", zipfile), NA) -} -zipCols <- function(i) { - data.frame( - gid = zips$gid[i], - type = zips$type[i], - zipfile = zips$zipfile[i], - tileid = zips$tileid[i], - gcm = zips$gcm[i] %||% NA_character_, - ssp = zips$ssp[i] %||% NA_character_, - msy = zips$msy[i], - decade_or_period = decadeOf(zips$zipfile[i]) - ) -} - -report <- list(indexGaps) -for (k in seq_len(nrow(driveProblems))) { - i <- match(driveProblems$gid[k], zips$gid) - report[[length(report) + 1]] <- cbind( - zipCols(i), - problem = driveProblems$problem[k], - item = basename(zips$zipfile[i]) - ) -} -differs <- which(!is.na(zips$md5_local) & zips$on_drive & !useLocal) -for (i in differs) { - report[[length(report) + 1]] <- cbind( - zipCols(i), - problem = "md5_differs", - item = paste0("local ", zips$md5_local[i], " / drive ", zips$md5_drive[i]) - ) -} -for (i in which(!is.na(unreadable))) { - report[[length(report) + 1]] <- cbind( - zipCols(i), - problem = "unreadable_zip", - item = unreadable[i] - ) -} -for (i in which(vapply(problems, nrow, integer(1)) > 0)) { - report[[length(report) + 1]] <- cbind(zipCols(i), problems[[i]]) -} -report <- dplyr::bind_rows(report) -report$repair <- zips$repair[match(report$gid, zips$gid)] - -zips$checked <- checked -zipsOut <- zips[c( - "gid", - "type", - "zipfile", - "tileid", - intersect(c("gcm", "ssp"), names(zips)), - "msy", - "n_expected", - "n_files", - "size", - "md5_drive", - "md5_local", - "source", - "complete", - "legacy_folders", - "repair", - "local_complete", - "checked" -)] -utils::write.csv(zipsOut, file.path(auditDir, "zips.csv"), row.names = FALSE) -utils::write.csv(report, file.path(auditDir, "report.csv"), row.names = FALSE) -utils::write.csv(reruns, file.path(auditDir, "climatena_reruns.csv"), row.names = FALSE) - -counts <- if (nrow(report) > 0) table(report$type, report$problem) else table(character(0)) -summaryLines <- c( - paste("# ClimateNA archive audit,", format(Sys.Date())), - "", - paste0("- Zips audited: ", nrow(zips), " (types: ", paste(auditTypes, collapse = ", "), ")"), - paste0("- Tiles: ", if (is.null(auditTiles)) "all" else paste(auditTiles, collapse = ", ")), - paste0("- Checked from the local copy: ", sum(zips$source == "local")), - paste0("- Checked from a Drive download: ", sum(zips$source == "drive")), - paste0("- Not checked (missing on Drive or download failed): ", sum(zips$source == "none")), - paste0("- Complete: ", sum(zips$complete %in% TRUE)), - paste0(" - up to date (ClimateNA v7.60+ names): ", sum(zips$repair %in% "none")), - paste0( - " - to regenerate with ClimateNA v7.60+ (radiation named Rad*/MAR): ", - sum(zips$repair %in% "regenerate_v760") - ), - paste0("- Incomplete: ", sum(zips$complete %in% FALSE)), - paste0(" - repairable from raw outputs: ", sum(zips$repair %in% "repairable")), - paste0(" - needing ClimateNA reruns: ", sum(zips$repair %in% "needs_climatena")), - paste0(" - needing a pipeline rerun (a release): ", sum(zips$repair %in% "rerun_pipeline")), - paste0("- Raw folders to rerun in ClimateNA: ", nrow(reruns)), - paste0("- Total size on Drive: ", round(sum(zips$size, na.rm = TRUE) / 1024^3, 1), " GiB"), - "", - "## Problems by type", - "", - "```", - utils::capture.output(print(counts)), - "```", - "", - "## Repairable zips", - "", - if (any(zips$repair %in% "repairable")) { - paste0("- ", zips$zipfile[zips$repair %in% "repairable"]) - } else { - "None." - } -) -writeLines(summaryLines, file.path(auditDir, "summary.md")) -message("Audit written to ", auditDir) diff --git a/data-raw/05-repair_archives.R b/data-raw/05-repair_archives.R deleted file mode 100644 index e7d9f9e..0000000 --- a/data-raw/05-repair_archives.R +++ /dev/null @@ -1,210 +0,0 @@ -## Repair of incomplete ClimateNA zips, from a reviewed audit (see 04-audit_archives.R). -## -## Acts only on rows of the reviewed zips.csv whose `repair` is "repairable": the raw ClimateNA -## outputs on the share are complete for every folder the zip should hold. For each one: -## 1. rebuild the whole zip from the raw outputs (raw is the source of truth); -## 2. check the rebuilt zip; skip it if it is not complete; -## 3. check that the Drive file still holds what the audit saw (skip it if it changed), and -## copy those bytes to a dated backup folder on the share (Drive keeps old versions of -## binary files for only 30 days); -## 4. replace the Drive file's content in place, keeping its file ID, then the local zip; -## 5. update `archived` and `uploaded` in that zip's index rows (working copy). -## -## With `dryRun <- TRUE` (the default) only steps 1-3's checks run, and nothing on Drive, in -## the index, or in the published data on the share changes. Each zip's row is appended to -## /repairs.csv as soon as it is done, so a run that stops keeps its record; an -## error's status says whether the Drive file had already been replaced. -## -## Users who already downloaded a replaced zip keep their old copy: reproducible::preProcess() -## does not yet download an archive again when its content on Drive changes. - -source("data-raw/01-ClimateNA_setup.R") - -## set these before sourcing this script -if (!exists("reviewedZips")) { - reviewedZips <- NULL ## path to the reviewed /zips.csv -} -if (!exists("repairGids")) { - repairGids <- NULL ## NULL means every repairable row; otherwise a character vector of Drive IDs -} -if (!exists("dryRun")) { - dryRun <- TRUE -} - -stopifnot( - "set `reviewedZips` to the reviewed zips.csv" = !is.null(reviewedZips), - "`reviewedZips` not found" = file.exists(reviewedZips) -) - -## absolute, because the rebuild runs inside the raw tile directory -reviewedZips <- normalizePath(reviewedZips, mustWork = TRUE) -auditDir <- dirname(reviewedZips) -rebuiltDir <- file.path(auditDir, "rebuilt") -backupDir <- file.path(ClimateNAdata, "_replaced", format(Sys.Date())) -dir.create(rebuiltDir, showWarnings = FALSE) - -zips <- utils::read.csv(reviewedZips, colClasses = c(gid = "character", ssp = "character")) -zips <- zips[zips$repair %in% "repairable", , drop = FALSE] -if (!is.null(repairGids)) { - zips <- zips[zips$gid %in% repairGids, , drop = FALSE] -} -stopifnot(all(zips$type %in% c("historical", "historical_normals", "future"))) -message(nrow(zips), " zips to repair", if (dryRun) " (dry run)") - -db <- sqlite_connect_db(wrkngDBfile) - -md5 <- function(f) if (file.exists(f)) unname(tools::md5sum(f)) else NA_character_ - -## `progress` lets the caller record how far a zip got if repairOne() stops with an error -repairOne <- function(z, progress) { - progress$driveReplaced <- FALSE - progress$out <- out <- data.frame( - gid = z$gid, - zipfile = z$zipfile, - old_md5 = z$md5_drive, - new_md5 = NA_character_, - n_files = NA_integer_, - backup = file.path(backupDir, z$zipfile), - status = NA_character_, - time = as.numeric(Sys.time()) - ) - - rows <- DBI::dbGetQuery( - db, - paste0("SELECT * FROM ", z$type, " WHERE gid = ?"), - params = list(z$gid) - ) - if (nrow(rows) == 0) { - stop("no ", z$type, " index rows for Drive ID ", z$gid, call. = FALSE) - } - expected <- .archiveExpected(rows, z$type) - folders <- unique(dirname(expected)) - tileDir <- file.path(ClimateNAdata, dirname(z$zipfile), z$tileid) - - ## 1. rebuild from raw, leaving out anything not expected (e.g. Thumbs.db); folders made - ## before ClimateNA v7.60 keep their Rad*/MAR names, as in 04-audit_archives.R - raw <- .dirListing(tileDir, folders) - expected <- .archiveExpectedByVersion(raw, expected)$expected - files <- raw$path[raw$path %in% expected] - newZip <- file.path(rebuiltDir, basename(z$zipfile)) - unlink(newZip) - withr::with_dir(tileDir, archive::archive_write_files(newZip, files = files)) - out$new_md5 <- md5(newZip) - out$n_files <- nrow(.zipListing(newZip)) - progress$out <- out - - ## 2. check the rebuilt zip - if (!.archiveComplete(.archiveCheck(.zipListing(newZip), expected))) { - out$status <- "failed_check" - return(out) - } - - ## 3. the Drive file must still hold what the audit saw; then back up those bytes - current <- googledrive::drive_get(googledrive::as_id(z$gid))$drive_resource[[1]]$md5Checksum - if (!identical(current, z$md5_drive)) { - out$status <- "drive_changed" - return(out) - } - localZip <- file.path(ClimateNAdata, z$zipfile) - downloaded <- file.path(auditDir, "downloads", basename(z$zipfile)) - backupSource <- if (identical(md5(localZip), z$md5_drive)) { - localZip - } else if (identical(md5(downloaded), z$md5_drive)) { - downloaded - } else { - NA_character_ - } - if (is.na(backupSource)) { - out$status <- "no_backup_source" - return(out) - } - if (dryRun) { - out$status <- "dry_run" - return(out) - } - dir.create(dirname(out$backup), recursive = TRUE, showWarnings = FALSE) - file.copy(backupSource, out$backup, overwrite = FALSE, copy.date = TRUE) - stopifnot(identical(md5(out$backup), z$md5_drive)) - - ## 4. replace on Drive (same file ID), then the local zip - res <- googledrive::drive_update(googledrive::as_id(z$gid), media = newZip) - progress$driveReplaced <- TRUE - if (!identical(res$drive_resource[[1]]$md5Checksum, out$new_md5)) { - out$status <- "upload_md5_mismatch" - return(out) - } - file.copy(newZip, localZip, overwrite = TRUE) - stopifnot(identical(md5(localZip), out$new_md5)) - - ## 5. index rows (epoch seconds, as in the existing columns) - now <- as.numeric(Sys.time()) - DBI::dbExecute( - db, - paste0("UPDATE ", z$type, " SET archived = ?, uploaded = ? WHERE gid = ?"), - params = list(now, now, z$gid) - ) - - out$status <- "replaced" - out -} - -## one row per zip, appended as soon as it is done (earlier runs' rows are kept) -repairsFile <- file.path(auditDir, "repairs.csv") -appendRepair <- function(r) { - isNew <- !file.exists(repairsFile) - utils::write.table( - r, - repairsFile, - sep = ",", - qmethod = "double", - row.names = FALSE, - col.names = isNew, - append = !isNew - ) -} - -runRepairs <- function() { - on.exit( - { - DBI::dbExecute(db, "PRAGMA wal_checkpoint(TRUNCATE)") - DBI::dbDisconnect(db) - }, - add = TRUE - ) - vapply( - seq_len(nrow(zips)), - function(i) { - progress <- new.env() - r <- tryCatch(repairOne(zips[i, ], progress), error = function(e) { - r <- progress$out - if (is.null(r)) { - r <- data.frame( - gid = zips$gid[i], - zipfile = zips$zipfile[i], - old_md5 = zips$md5_drive[i], - new_md5 = NA_character_, - n_files = NA_integer_, - backup = NA_character_, - status = NA_character_, - time = as.numeric(Sys.time()) - ) - } - r$status <- paste0( - "error", - if (isTRUE(progress$driveReplaced)) " after the Drive file was replaced", - ": ", - conditionMessage(e) - ) - r - }) - appendRepair(r) - message(r$status, ": ", r$zipfile) - r$status - }, - character(1) - ) -} - -statuses <- runRepairs() -message("Repairs appended to ", repairsFile) -print(table(sub(":.*$", "", statuses))) diff --git a/data-raw/06-archive_fingerprints.R b/data-raw/06-archive_fingerprints.R deleted file mode 100644 index f7eae35..0000000 --- a/data-raw/06-archive_fingerprints.R +++ /dev/null @@ -1,57 +0,0 @@ -## Record one fingerprint per published ClimateNA zip in the tile index, and ship the index. -## -## Reads the zips.csv of the last full audit (04-audit_archives.R, run after any repairs with -## 05-repair_archives.R) and writes its Drive MD5, file count and size into the `archives` -## table. `verified` is the audit time for zips that passed the check, and NULL otherwise. -## Then copies the working index into the package (inst/extdata). The copy on the share -## (`addlDBfile`) is left alone: it holds the per-file checksum tables (millions of rows), -## which the package copy does not. - -stop( - "Superseded by the targets pipeline in data-raw/pipeline/, whose index has the archives ", - "table. This script copies the pre-pipeline working index over the shipped release index.", - call. = FALSE -) - -source("data-raw/01-ClimateNA_setup.R") - -if (!exists("finalZips")) { - finalZips <- NULL ## path to the zips.csv of the last full audit -} -stopifnot( - "set `finalZips` to the last full audit's zips.csv" = !is.null(finalZips), - "`finalZips` not found" = file.exists(finalZips) -) - -zips <- utils::read.csv(finalZips, colClasses = c(gid = "character")) -stopifnot(!anyDuplicated(zips$gid), !anyNA(zips$md5_drive)) - -fingerprints <- data.frame( - gid = zips$gid, - type = zips$type, - zipfile = zips$zipfile, - md5 = zips$md5_drive, - n_files = as.integer(zips$n_files), - size = as.numeric(zips$size), - verified = ifelse(zips$complete %in% TRUE, zips$checked, NA_real_) -) - -db <- sqlite_connect_db(wrkngDBfile) -.archivesCreate(db) -n <- .archivesUpsert(db, fingerprints) -message(n, " fingerprints written; ", sum(is.na(fingerprints$verified)), " zips not verified") -DBI::dbExecute(db, "PRAGMA wal_checkpoint(TRUNCATE)") -DBI::dbExecute(db, "PRAGMA journal_mode = DELETE") ## ship in rollback-journal mode: reading a WAL file writes -wal/-shm beside it -DBI::dbDisconnect(db) -stopifnot(!file.exists(paste0(wrkngDBfile, "-wal")) || file.size(paste0(wrkngDBfile, "-wal")) == 0) - -sizeBefore <- file.size(pkgDBfile) -file.copy(wrkngDBfile, pkgDBfile, overwrite = TRUE) -message( - "Shipped index grew by ", - round((file.size(pkgDBfile) - sizeBefore) / 1024^2, 2), - " MB (now ", - round(file.size(pkgDBfile) / 1024^2, 1), - " MB)" -) -unlink(paste0(wrkngDBfile, c("", "-wal", "-shm"))) diff --git a/data-raw/pipeline/R/catalogue.R b/data-raw/pipeline/R/catalogue.R new file mode 100644 index 0000000..22065b6 --- /dev/null +++ b/data-raw/pipeline/R/catalogue.R @@ -0,0 +1,26 @@ +## Refreshing the bucket's browsable catalogue (one index.html per folder, from buckethost's +## generateIndexes()) after uploads. It lists the bucket and rewrites every page outside the +## excluded folders, the pages of the bucket's other data too, so `settings` (release.yml's +## `catalogue` block: heading, disclaimer_html, host_note, exclude) must match the settings its +## other users run it with. + +## Rewrite the catalogue for `bucket` through the rclone `remote`; list(pages, at) or, in a dry +## run, NULL with nothing read or written. `index` only orders it after the index. `generate` is +## buckethost::generateIndexes() unless given (tests). +pipeline_catalogue <- function(index, bucket, remote, settings, dryRun, generate = NULL) { + if (isTRUE(dryRun)) { + return(NULL) + } + generate <- generate %||% buckethost::generateIndexes + pages <- generate( + container = bucket$container, + endpoint = bucket$endpoint, + remote = remote, + heading = settings$heading, + disclaimerHtml = settings$disclaimer_html %||% "", + hostNote = settings$host_note, + exclude = as.character(unlist(settings$exclude)), + quiet = TRUE + ) + list(pages = length(pages), at = as.numeric(Sys.time())) +} diff --git a/data-raw/pipeline/R/dem.R b/data-raw/pipeline/R/dem.R new file mode 100644 index 0000000..38923fc --- /dev/null +++ b/data-raw/pipeline/R/dem.R @@ -0,0 +1,58 @@ +## The DEM tiles (can_dem_.asc) a release's ClimateNA runs use. With `dem_dir` in _local.R +## the pipeline uses that folder (the 3 and 1 arcmin releases do: a rebuilt tile never matches their +## files byte for byte, and any change reruns every ClimateNA period of the tile). Without it, the +## pipeline builds them under /dem/ from the GTOPO30 Canada mosaic in the bucket, after +## checking that the tile grid rule still gives the shipped tiles.gpkg (R/pipelineDem.R). + +## Whether this release builds its own DEM tiles (no `dem_dir` in _local.R). +pipeline_dem_mode <- function(local) { + is.null(local$dem_dir) +} + +## The boundary file pipeline_canada() stores (a packed SpatVector), as sf in lon/lat. +pipeline_boundary_sf <- function(canadaFile) { + x <- readRDS(canadaFile) + if (inherits(x, "PackedSpatVector")) { + x <- terra::unwrap(x) + } + sf::st_transform(sf::st_as_sf(x), 4326) +} + +## The GTOPO30 Canada mosaic, from the release's bucket (`bucket`, release.yml's) into +## /dem-src/; returns the GeoTIFF. +pipeline_gtopo30 <- function(outRoot, bucket) { + dir <- file.path(outRoot, "dem-src") + dir.create(dir, recursive = TRUE, showWarnings = FALSE) + url <- paste(pipeline_s3_base_url(bucket), bucket$prefix, "dem", "gtopo30Canada.zip", sep = "/") + .gtopo30Canada(dir, url = url) + file.path(dir, "gtopo30Canada.tif") +} + +## Stops unless the tile grid rule (.tileGrid()) applied to the boundary gives the tile grid in +## `gpkg` (by default the shipped one); returns `gpkg`. +pipeline_tile_grid_check <- function(canadaFile, gpkg = ClimateNA_tiles_gpkg()) { + shipped <- sf::st_read(gpkg, quiet = TRUE) + if (!.sameTileGrid(.tileGrid(pipeline_boundary_sf(canadaFile)), shipped)) { + stop( + "the tile grid rule no longer gives ", + gpkg, + " (a changed boundary file?); tile ids would not match the published archives", + call. = FALSE + ) + } + gpkg +} + +## The DEM tiles at the release's `demResolution`, in /dem/ (earlier tiles removed first, +## so a tile that now has no DEM cell leaves no file behind). Returns the files. +pipeline_build_dem <- function(gtopo30, canadaFile, demResolution, outRoot, gpkg) { + dir <- file.path(outRoot, "dem") + unlink(list.files(dir, "^can_dem_[0-9]+[.]", full.names = TRUE)) + .buildDemTiles( + terra::rast(gtopo30), + pipeline_boundary_sf(canadaFile), + sf::st_read(gpkg, quiet = TRUE), + .demResolutionDeg(demResolution), + dir + ) +} diff --git a/data-raw/pipeline/R/index.R b/data-raw/pipeline/R/index.R index 08ea988..b401200 100644 --- a/data-raw/pipeline/R/index.R +++ b/data-raw/pipeline/R/index.R @@ -29,7 +29,7 @@ pipeline_index_rows <- function(spec, uploads, manifestById, outRoot) { created = unname(created), zipfile = rel, archived = as.numeric(file.mtime(pipeline_zip_path(outRoot, spec, subset))), - gid = up$gid[1], + key = up$key[1], uploaded = up$uploaded[1], climatena_version = version ) @@ -39,9 +39,10 @@ pipeline_index_rows <- function(spec, uploads, manifestById, outRoot) { do.call(rbind, rows) } -## Build /ClimateNA_tiles.sqlite for the release, from scratch: the four tile tables (via -## ClimateNA_sql(), with each row's ClimateNA version), the archives fingerprints, the release -## table and the filled land cells (`fillPoints`, from pipeline_fill_points()). Written to a +## Build /ClimateNA_tiles.sqlite for the release, from scratch: the archives fingerprints +## (with each zip's time), the four tile tables (via ClimateNA_sql(): each row's ClimateNA version +## and its archive's id, with the views that join them), the release table (with the bucket's +## `baseUrl`) and the filled land cells (`fillPoints`, from pipeline_fill_points()). Written to a ## temporary name and renamed, and left in rollback-journal mode with no -wal/-shm files. ## `uploads`, `specs` and `manifests` are all types' targets combined. build_index <- function( @@ -52,7 +53,8 @@ build_index <- function( releaseId, climatenaVersion, demResolution, - fillPoints + fillPoints, + baseUrl ) { manifestById <- as.list(manifests) names(manifestById) <- sub("[.]tsv$", "", basename(manifests)) @@ -60,13 +62,37 @@ build_index <- function( tmp <- tempfile("index-", tmpdir = outRoot, fileext = ".sqlite") on.exit(unlink(paste0(tmp, c("", "-wal", "-shm"))), add = TRUE) + db <- DBI::dbConnect(RSQLite::SQLite(), tmp) + .archivesCreate(db) + if (nrow(uploads) > 0) { + zips <- file.path(outRoot, "zips", uploads$zipfile) + .archivesUpsert( + db, + data.frame( + key = uploads$key, + type = sub("/.*", "", uploads$zipfile), + zipfile = uploads$zipfile, + md5 = uploads$md5, + n_files = vapply(zips, \(z) nrow(.zipListing(z)), integer(1)), + size = as.numeric(file.size(zips)), + archived = as.numeric(file.mtime(zips)), + verified = uploads$uploaded # public object's MD5 and size checked at upload + ) + ) + } + archives <- DBI::dbGetQuery(db, "SELECT id, zipfile FROM archives") + DBI::dbDisconnect(db) + + ## each row refers to its zip's archives row; the view gives back its path, key and times + archiveCols <- c("zipfile", "archived", "key", "uploaded") types <- vapply(specs, `[[`, character(1), "type") for (type in .batchTypes) { rows <- lapply(specs[types == type], pipeline_index_rows, uploads, manifestById, outRoot) rows <- do.call(rbind, rows) con <- ClimateNA_sql(tmp, type) # creates the table even when the release has no such rows if (!is.null(rows) && nrow(rows) > 0) { - DBI::dbAppendTable(con$db, type, rows) + rows$archive <- archives$id[match(rows$zipfile, archives$zipfile)] + DBI::dbAppendTable(con$db, paste0("tiles_", type), rows[setdiff(names(rows), archiveCols)]) } DBI::dbDisconnect(con$db) } @@ -79,25 +105,10 @@ build_index <- function( release_id = releaseId, climatena_version = climatenaVersion, dem_resolution = demResolution, + base_url = baseUrl, created = as.numeric(Sys.time()) ) ) - .archivesCreate(db) - if (nrow(uploads) > 0) { - zips <- file.path(outRoot, "zips", uploads$zipfile) - .archivesUpsert( - db, - data.frame( - gid = uploads$gid, - type = sub("/.*", "", uploads$zipfile), - zipfile = uploads$zipfile, - md5 = uploads$md5, - n_files = vapply(zips, \(z) nrow(.zipListing(z)), integer(1)), - size = as.numeric(file.size(zips)), - verified = uploads$uploaded # MD5 checked against Drive at upload - ) - ) - } .filledCellsCreate(db) .filledCellsWrite(db, fillPoints) DBI::dbExecute(db, "PRAGMA wal_checkpoint(TRUNCATE)") @@ -109,10 +120,14 @@ build_index <- function( path } -## Write /report.csv: every error and warning targets has recorded, and every subset zip -## that is missing from the uploads (its batch, zip or upload failed). Empty when all is well. -build_report <- function(index, specs, uploads, outRoot) { - meta <- targets::tar_meta(fields = c("error", "warnings"), store = targets::tar_path_store()) +## Write /report.csv: every error and warning targets has recorded for the pipeline's +## current targets, and every subset zip that is missing from the uploads (its batch, zip or upload +## failed), with `settings` rows. Empty when all is well. +build_report <- function(index, specs, uploads, outRoot, settings = NULL) { + meta <- pipeline_current_meta(targets::tar_meta( + fields = c("type", "children", "error", "warnings"), + store = targets::tar_path_store() + )) problems <- rbind( data.frame(target = meta$name, kind = "error", message = meta$error)[!is.na(meta$error), ], data.frame(target = meta$name, kind = "warning", message = meta$warnings)[ @@ -127,8 +142,62 @@ build_report <- function(index, specs, uploads, outRoot) { } data.frame(target = spec$id, kind = "incomplete", message = paste("not uploaded:", rel)) }) - problems <- do.call(rbind, c(list(problems), missing)) + ## `settings`: pipeline_settings_vs_available() + problems <- do.call(rbind, c(list(problems), missing, list(settings))) out <- file.path(outRoot, "report.csv") utils::write.csv(problems, out, row.names = FALSE) out } + +## The rows of `meta` (tar_meta(), with type and children) for targets the pipeline still has: a +## branch counts only while its pattern lists it. A branch the pipeline no longer makes (e.g. a +## tile dropped from the release) keeps its last error in the store until tar_prune(). +pipeline_current_meta <- function(meta) { + current <- unlist(meta$children[meta$type %in% "pattern"]) + meta[!(meta$type %in% "branch") | meta$name %in% current, , drop = FALSE] +} + +## release.yml's years, periods, GCMs and SSPs for each type it builds, against available() (what +## users can request): one "settings" row per field that differs. The old build scripts read these +## from available(); 2.2.3 shipped an index that stopped short of it. +pipeline_settings_vs_available <- function(cfg) { + span <- function(x) seq(as.integer(x[[1]]), as.integer(x[[2]])) + ours <- list( + historical = list(years = span(cfg$historical_years)), + future = list(years = span(cfg$future_years), gcms = unlist(cfg$gcms), ssps = unlist(cfg$ssps)), + historical_normals = list(periods = unlist(cfg$historical_periods)), + future_normals = list( + periods = unlist(cfg$future_periods), + gcms = unlist(cfg$gcms), + ssps = unlist(cfg$ssps) + ) + ) + listed <- function(x) if (length(x) == 0) "none" else paste(utils::head(x, 10), collapse = ", ") + rows <- list() + for (type in intersect(names(ours), unlist(cfg$types))) { + av <- available(type) + for (field in names(ours[[type]])) { + a <- as.character(ours[[type]][[field]]) + b <- as.character(av[[field]]) + if (!setequal(a, b)) { + rows[[length(rows) + 1]] <- data.frame( + target = "release.yml", + kind = "settings", + message = paste0( + type, + " ", + field, + ": not in release.yml: ", + listed(setdiff(b, a)), + "; not in available(): ", + listed(setdiff(a, b)) + ) + ) + } + } + } + if (length(rows) == 0) { + return(data.frame(target = character(0), kind = character(0), message = character(0))) + } + do.call(rbind, rows) +} diff --git a/data-raw/pipeline/R/paths.R b/data-raw/pipeline/R/paths.R new file mode 100644 index 0000000..340b555 --- /dev/null +++ b/data-raw/pipeline/R/paths.R @@ -0,0 +1,22 @@ +## Paths from _local.R reach zip, docker and rclone through the shell (system2()), unquoted: a path +## with a space or a quote would break those calls part-way through a run. + +## Stops, naming the settings, when a path in `local` (_local.R) holds a space or a quote. +pipeline_check_paths <- function(local) { + keys <- c("climatena_dir", "dem_dir", "out_root", "work_dir") + bad <- keys[vapply( + keys, + function(k) isTRUE(grepl("[[:space:]'\"]", local[[k]] %||% "")), + logical(1) + )] + if (length(bad) > 0) { + stop( + "_local.R: ", + paste(bad, collapse = ", "), + " must not hold spaces or quotes (the pipeline passes paths to zip, docker and rclone ", + "through the shell)", + call. = FALSE + ) + } + invisible(local) +} diff --git a/data-raw/pipeline/R/specs.R b/data-raw/pipeline/R/specs.R index 3e81e1a..0b9f2c7 100644 --- a/data-raw/pipeline/R/specs.R +++ b/data-raw/pipeline/R/specs.R @@ -19,8 +19,8 @@ pipeline_tiles <- function(demDir, subset = NULL) { } ## Canada, whose cells keep ClimateNA's values where the DEM has none: GADM 4.1, level 0, at its -## highest resolution, as data-raw/02-ClimateNA_tiles.R uses for the tiles. Downloaded once into -## /boundary/; returns the file. +## highest resolution, as the tile grid and the DEM tiles use (R/pipelineDem.R). Downloaded once +## into /boundary/; returns the file. pipeline_canada <- function(outRoot) { dir <- file.path(outRoot, "boundary") dir.create(dir, recursive = TRUE, showWarnings = FALSE) @@ -32,14 +32,20 @@ pipeline_canada <- function(outRoot) { f } -## Each tile's DEM file, named by tile; stops naming tiles without one. As a `format = "file"` -## target, it makes the targets built from the DEMs depend on the files' contents. -pipeline_dem_files <- function(demDir, tiles) { +## Each tile's DEM file, named by tile; stops naming tiles without one, or a file ClimateNA can't +## use at the release's `demResolution` (.demCheck(): CRLF, square cells of that size, lon/lat). +## As a `format = "file"` target, it makes the targets built from the DEMs depend on the files' +## contents. +pipeline_dem_files <- function(demDir, tiles, demResolution) { f <- stats::setNames(pipeline_dem_file(demDir, tiles), as.character(tiles)) missing <- names(f)[!file.exists(f)] if (length(missing) > 0) { stop("no DEM tile in ", demDir, " for tile(s) ", paste(missing, collapse = ", ")) } + res <- .demResolutionDeg(demResolution) + for (x in f) { + .demCheck(x, res) + } f } diff --git a/data-raw/pipeline/R/upload_drive.R b/data-raw/pipeline/R/upload_drive.R deleted file mode 100644 index 3721ad2..0000000 --- a/data-raw/pipeline/R/upload_drive.R +++ /dev/null @@ -1,255 +0,0 @@ -## Publishing a batch's zips to Google Drive, as files in the release's folder -## //[/_ssp]//, or as an earlier release's file -## when the zip is identical. This is the only Drive-specific code: another store (e.g. S3) would -## be an upload_.R with the same signature and result. -## -## Uploads run on the main node (where the maintainer's OAuth token is cached), in parallel on the -## "uploads" crew controller; `drive_email` in _local.R tells googledrive which token to use. The -## release's folders are created first, on the main process, so parallel uploads never race to -## create the same folder. - -## Drive folder ids looked up or created in this session, keyed by path below the parent. -pipeline_drive_folders <- new.env(parent = emptyenv()) - -## The id of the folder ///..., creating any that are missing. -pipeline_drive_folder <- function(parentId, segments) { - id <- parentId - for (i in seq_along(segments)) { - key <- paste(c(parentId, segments[seq_len(i)]), collapse = "/") - if (is.null(pipeline_drive_folders[[key]])) { - found <- googledrive::drive_ls(googledrive::as_id(id), type = "folder") - found <- found[found$name == segments[i], ] - if (nrow(found) > 1) { - stop("several Drive folders named ", key) - } - pipeline_drive_folders[[key]] <- if (nrow(found) == 1) { - as.character(found$id) - } else { - googledrive::with_drive_quiet(googledrive::drive_mkdir( - segments[i], - path = googledrive::as_id(id) - ))$id |> - as.character() - } - } - id <- pipeline_drive_folders[[key]] - } - id -} - -## Create the release's Drive folder for every zip directory it can produce (e.g. -## "historical/MSY"), and write their ids (NA in a dry run), named by the directory below the -## release folder, to /drive_folders.rds. Returns only the map's path, the release and -## the dry-run flag, so adding folders (a new GCM or SSP) changes nothing the existing upload -## branches depend on. -pipeline_release_folders <- function(specs, releaseId, driveParent, dryRun, outRoot) { - dirs <- unique(dirname(unlist(lapply(specs, pipeline_zip_relpaths)))) - ids <- if (isTRUE(dryRun)) { - rep(NA_character_, length(dirs)) - } else { - vapply( - dirs, - \(d) pipeline_drive_folder(driveParent, c(releaseId, strsplit(d, "/")[[1]])), - character(1) - ) - } - path <- file.path(outRoot, "drive_folders.rds") - saveRDS(stats::setNames(ids, dirs), path) - list(path = path, release_id = releaseId, dry_run = dryRun) -} - -## Every zip path below the release folder that a batch can produce. -pipeline_zip_relpaths <- function(spec) { - vapply(pipeline_subsets(spec$type), \(s) pipeline_zip_relpath(spec, s), character(1)) -} - -## The previous release's archives rows that this release could reuse, written once to a small -## lookup database (indexed, rollback-journal mode, so upload workers can open it read-only and -## query only their own zips). Returns only the path, so its value never changes: the rows change -## whenever a scenario is added (they are cut to specs_all), and a value that followed them would -## rerun every upload branch. An upload that already ran needs no new lookup. -pipeline_previous_lookup <- function(index, specs, outRoot) { - prev <- pipeline_previous_archives(index) - prev <- prev[prev$zipfile %in% unlist(lapply(specs, pipeline_zip_relpaths)), , drop = FALSE] - prev <- prev[order(prev$zipfile), , drop = FALSE] - path <- file.path(outRoot, "previous_archives.sqlite") - tmp <- paste0(path, ".tmp") - unlink(tmp) - db <- DBI::dbConnect(RSQLite::SQLite(), tmp) - DBI::dbExecute(db, "CREATE TABLE prev (zipfile TEXT, gid TEXT, md5 TEXT)") - DBI::dbAppendTable(db, "prev", prev[c("zipfile", "gid", "md5")]) - DBI::dbExecute(db, "CREATE INDEX prev_zipfile ON prev (zipfile)") - DBI::dbDisconnect(db) - file.rename(tmp, path) - list(path = path) -} - -## The previous release's rows for one batch's zips, from pipeline_previous_lookup(). -pipeline_previous_rows <- function(lookup, spec) { - db <- DBI::dbConnect(RSQLite::SQLite(), lookup$path, flags = RSQLite::SQLITE_RO) - on.exit(DBI::dbDisconnect(db)) - DBI::dbGetQuery( - db, - "SELECT gid, zipfile, md5 FROM prev WHERE zipfile = ?", - params = list(unname(pipeline_zip_relpaths(spec))) - ) -} - -## Drive's createdTime (or, for a file replaced in place, modifiedTime; RFC 3339, UTC) as epoch -## seconds. -pipeline_drive_time <- function(resource, field = "createdTime") { - as.numeric(as.POSIXct(resource[[field]], format = "%Y-%m-%dT%H:%M:%OS", tz = "UTC")) -} - -## The `archives` rows (gid, zipfile, md5) of an earlier release's index, for reusing its Drive -## files; none when the file is missing or has no archives table. Read from a copy: the shipped -## index is in WAL mode, which a read-only connection can't open in place. -pipeline_previous_archives <- function(index) { - none <- data.frame(gid = character(0), zipfile = character(0), md5 = character(0)) - if (length(index) == 0 || !file.exists(index)) { - return(none) - } - tmp <- tempfile(fileext = ".sqlite") - on.exit(unlink(paste0(tmp, c("", "-wal", "-shm"))), add = TRUE) - for (ext in c("", "-wal", "-shm")) { - if (file.exists(paste0(index, ext))) { - file.copy(paste0(index, ext), paste0(tmp, ext)) - } - } - db <- DBI::dbConnect(RSQLite::SQLite(), tmp) - on.exit(DBI::dbDisconnect(db), add = TRUE, after = FALSE) - if (!DBI::dbExistsTable(db, "archives")) { - return(none) - } - x <- DBI::dbGetQuery(db, "SELECT gid, zipfile, md5 FROM archives WHERE gid IS NOT NULL") - if (nrow(x) == 0) none else x -} - -## An earlier release's Drive file for this zip: same path below the release folder and same MD5, -## and still on Drive (not trashed) with that MD5. NULL when there is none. -pipeline_reusable_file <- function(previous, rel, md5) { - prev <- previous[previous$zipfile == rel & previous$md5 == md5, , drop = FALSE] - if (nrow(prev) == 0) { - return(NULL) - } - file <- tryCatch(googledrive::drive_get(googledrive::as_id(prev$gid[1])), error = \(e) NULL) - r <- if (!is.null(file) && nrow(file) == 1) file$drive_resource[[1]] - if (is.null(r) || isTRUE(r$trashed) || !identical(r$md5Checksum, md5)) { - return(NULL) - } - file -} - -## Upload one batch's zips. Each zip is, in order of preference: -## - "reused": an earlier release (`lookup`, from pipeline_previous_lookup()) has the identical -## zip on Drive; -## - "found": the release folder already has a file of that name and MD5 (an interrupted run); -## - "updated": the release folder has a file of that name with another MD5 (the zip was -## rebuilt, e.g. with masked cells), replaced in place so its Drive ID stays the same -## (.uploadAction() decides which file when there are several). Only with replaceChanged -## (replace_changed in _local.R); otherwise the upload stops, naming the zip; -## - "uploaded" as a new file. -## With dryRun nothing on Drive is read or written: `source` is "reused" (gid from `lookup`, not -## checked) or "dry run" (gid NA). `folders` is pipeline_release_folders(). Returns one row per -## zip: subset, gid, md5, zipfile (path below the release folder), uploaded (Drive's createdTime, -## epoch seconds; NA in a dry run) and source. -upload_zips <- function( - zips, - spec, - folders, - dryRun, - lookup, - driveEmail = NULL, - replaceChanged = FALSE -) { - pipeline_load() # .uploadAction(); an upload worker starts without the package - if (!is.null(driveEmail)) { - options(gargle_oauth_email = driveEmail) # a worker process doesn't see _local.R's options - } - previous <- if (length(zips) > 0) pipeline_previous_rows(lookup, spec) - rows <- lapply(zips, function(zip) { - subset <- basename(dirname(zip)) - rel <- pipeline_zip_relpath(spec, subset) - out <- data.frame( - subset = subset, - gid = NA_character_, - md5 = unname(tools::md5sum(zip)), - zipfile = rel, - uploaded = NA_real_, - source = "dry run" - ) - if (isTRUE(dryRun)) { - prev <- previous$gid[previous$zipfile == rel & previous$md5 == out$md5] - if (length(prev) > 0) { - out$gid <- prev[1] - out$source <- "reused" - } - return(out) - } - - file <- pipeline_reusable_file(previous, rel, out$md5) - out$source <- "reused" - if (is.null(file)) { - folder <- unname(readRDS(folders$path)[dirname(rel)]) - if (length(folder) != 1 || is.na(folder)) { - stop("no release folder for ", dirname(rel)) - } - there <- googledrive::drive_ls( - googledrive::as_id(folder), - q = sprintf("name = '%s'", basename(zip)) - ) - md5s <- vapply(there$drive_resource, \(r) r$md5Checksum %||% NA_character_, character(1)) - ## a changed zip replaces its file in this release's folder in place, keeping the Drive ID - ## the index holds; files outside this folder (earlier releases) are never touched - gid <- previous$gid[previous$zipfile == rel] - act <- tryCatch( - .uploadAction( - data.frame(id = as.character(there$id), md5 = md5s), - out$md5, - if (length(gid) > 0) gid[1], - replace = replaceChanged - ), - error = \(e) stop(rel, ": ", conditionMessage(e), call. = FALSE) - ) - if (act$action == "found") { - file <- there[there$id == act$id, ] - out$source <- "found" - } else { - file <- googledrive::with_drive_quiet( - if (act$action == "update") { - googledrive::drive_update(googledrive::as_id(act$id), media = zip) - } else { - googledrive::drive_upload( - zip, - path = googledrive::as_id(folder), - name = basename(zip), - overwrite = NA - ) - } - ) - if (!identical(file$drive_resource[[1]]$md5Checksum, out$md5)) { - stop("MD5 mismatch after uploading ", rel, " (Drive file ", file$id, ")") - } - out$source <- if (act$action == "update") "updated" else "uploaded" - } - } - out$gid <- as.character(file$id) - out$uploaded <- pipeline_drive_time( - file$drive_resource[[1]], - if (identical(out$source, "updated")) "modifiedTime" else "createdTime" - ) - out - }) - if (length(rows) == 0) { - ## an errored zips branch (error = "null") - return(data.frame( - subset = character(0), - gid = character(0), - md5 = character(0), - zipfile = character(0), - uploaded = numeric(0), - source = character(0) - )) - } - do.call(rbind, rows) -} diff --git a/data-raw/pipeline/R/upload_s3.R b/data-raw/pipeline/R/upload_s3.R new file mode 100644 index 0000000..56a9124 --- /dev/null +++ b/data-raw/pipeline/R/upload_s3.R @@ -0,0 +1,282 @@ +## Publishing a batch's zips to the release's bucket (Arbutus object storage, S3 through rclone), +## as objects //, or as an earlier release's object when the zip is +## identical. `bucket` is release.yml's `bucket` block: endpoint, container (project id and +## bucket, as in the public URL) and prefix. +## +## Uploads run on the main node, where the rclone remote (`rclone_remote` in _local.R) is set up, +## in parallel on the "uploads" crew controller. Every object is uploaded public (new objects are +## private otherwise) and in a single part, so its ETag is its MD5; each is then checked with an +## anonymous HEAD, as a user's download sees it. + +.s3UploadFlags <- c("--s3-acl", "public-read", "--s3-upload-cutoff", "1G") + +## The bucket's public URL; an object's URL is /. +pipeline_s3_base_url <- function(bucket) { + paste0(bucket$endpoint, "/", bucket$container) +} + +## The object key of a zip of the release. +pipeline_s3_key <- function(bucket, releaseId, zipfile) { + paste(bucket$prefix, releaseId, zipfile, sep = "/") +} + +## rclone's path for a key: the remote and the bare bucket name (the container without the +## project id). +pipeline_s3_path <- function(remote, bucket, key) { + paste0(remote, ":", sub("^.*:", "", bucket$container), "/", key) +} + +## Run rclone; list(status, stdout, stderr). +pipeline_rclone <- function(args) { + err <- tempfile() + on.exit(unlink(err)) + out <- suppressWarnings(system2("rclone", args, stdout = TRUE, stderr = err)) + list( + status = attr(out, "status") %||% 0L, + stdout = out, + stderr = if (file.exists(err)) readLines(err, warn = FALSE) else character(0) + ) +} + +## What the key holds, from an authenticated listing: 0 rows (no object) or 1 row (id = key, +## md5). Stops naming the key when rclone fails. +pipeline_s3_state <- function(remote, bucket, key) { + r <- pipeline_rclone(c( + "lsjson", + "--hash", + "--hash-type", + "MD5", + "--files-only", + pipeline_s3_path(remote, bucket, key) + )) + if (r$status != 0) { + stop("rclone couldn't list ", key, ": ", paste(r$stderr, collapse = " ")) + } + x <- jsonlite::fromJSON(paste(r$stdout, collapse = ""), simplifyVector = FALSE) + if (length(x) == 0) { + return(data.frame(id = character(0), md5 = character(0))) + } + data.frame(id = key, md5 = x[[1]]$Hashes$md5 %||% NA_character_) +} + +## Upload a zip as the key's object, public and in a single part. Stops naming the key when +## rclone fails. +pipeline_s3_put <- function(remote, bucket, key, zip) { + r <- pipeline_rclone(c("copyto", .s3UploadFlags, zip, pipeline_s3_path(remote, bucket, key))) + if (r$status != 0) { + stop("rclone couldn't upload ", key, ": ", paste(r$stderr, collapse = " ")) + } + invisible(key) +} + +## An anonymous HEAD of a public URL, as a user's download sees it: list(status, size, md5 (the +## ETag), modified (epoch seconds)). An HTTP error status is returned, not raised. +pipeline_s3_head <- function(url) { + resp <- httr2::req_perform(pipeline_s3_head_request(url)) + hdr <- function(name) httr2::resp_header(resp, name) %||% NA_character_ + modified <- hdr("Last-Modified") + list( + status = httr2::resp_status(resp), + size = as.numeric(hdr("Content-Length")), + md5 = gsub('"', "", hdr("ETag")), + modified = if (is.na(modified)) NA_real_ else as.numeric(curl::parse_date(modified)) + ) +} + +## The HEAD request: up to 3 tries, retrying transient HTTP errors and network failures (a DNS +## timeout failed four upload branches of the 3 arcmin release at once). +pipeline_s3_head_request <- function(url) { + httr2::request(url) |> + httr2::req_method("HEAD") |> + httr2::req_error(is_error = function(resp) FALSE) |> + httr2::req_retry(max_tries = 3, retry_on_failure = TRUE) +} + +## Every zip path below the release that a batch can produce. +pipeline_zip_relpaths <- function(spec) { + vapply(pipeline_subsets(spec$type), \(s) pipeline_zip_relpath(spec, s), character(1)) +} + +## The `archives` rows (key, zipfile, md5) of an earlier release's index whose objects are in this +## bucket (`baseUrl`), for reusing them; none when the file is missing, has no archives, or its +## release has another base URL or none (a Drive index, before climateData 2.3.0). Read from a +## copy, so the index is never opened in place. +pipeline_previous_archives <- function(index, baseUrl) { + none <- data.frame(key = character(0), zipfile = character(0), md5 = character(0)) + if (length(index) == 0 || !file.exists(index)) { + return(none) + } + tmp <- tempfile(fileext = ".sqlite") + on.exit(unlink(paste0(tmp, c("", "-wal", "-shm"))), add = TRUE) + for (ext in c("", "-wal", "-shm")) { + if (file.exists(paste0(index, ext))) { + file.copy(paste0(index, ext), paste0(tmp, ext)) + } + } + db <- DBI::dbConnect(RSQLite::SQLite(), tmp) + on.exit(DBI::dbDisconnect(db), add = TRUE, after = FALSE) + tables <- DBI::dbListTables(db) + if (!all(c("archives", "release") %in% tables)) { + return(none) + } + if (!"base_url" %in% DBI::dbListFields(db, "release")) { + return(none) + } + url <- DBI::dbGetQuery(db, "SELECT base_url FROM release LIMIT 1")$base_url + if (!identical(url, baseUrl)) { + return(none) + } + x <- DBI::dbGetQuery(db, "SELECT key, zipfile, md5 FROM archives WHERE key IS NOT NULL") + if (nrow(x) == 0) none else x +} + +## The previous release's archives rows that this release could reuse, written once to a small +## lookup database (indexed, rollback-journal mode, so upload workers can open it read-only and +## query only their own zips). Returns only the path, so its value never changes: the rows change +## whenever a scenario is added (they are cut to specs_all), and a value that followed them would +## rerun every upload branch. An upload that already ran needs no new lookup. +pipeline_previous_lookup <- function(index, specs, outRoot, baseUrl) { + prev <- pipeline_previous_archives(index, baseUrl) + prev <- prev[prev$zipfile %in% unlist(lapply(specs, pipeline_zip_relpaths)), , drop = FALSE] + prev <- prev[order(prev$zipfile), , drop = FALSE] + path <- file.path(outRoot, "previous_archives.sqlite") + tmp <- paste0(path, ".tmp") + unlink(tmp) + db <- DBI::dbConnect(RSQLite::SQLite(), tmp) + DBI::dbExecute(db, "CREATE TABLE prev (zipfile TEXT, key TEXT, md5 TEXT)") + DBI::dbAppendTable(db, "prev", prev[c("zipfile", "key", "md5")]) + DBI::dbExecute(db, "CREATE INDEX prev_zipfile ON prev (zipfile)") + DBI::dbDisconnect(db) + file.rename(tmp, path) + list(path = path) +} + +## The previous release's rows for one batch's zips, from pipeline_previous_lookup(). +pipeline_previous_rows <- function(lookup, spec) { + db <- DBI::dbConnect(RSQLite::SQLite(), lookup$path, flags = RSQLite::SQLITE_RO) + on.exit(DBI::dbDisconnect(db)) + DBI::dbGetQuery( + db, + "SELECT key, zipfile, md5 FROM prev WHERE zipfile = ?", + params = list(unname(pipeline_zip_relpaths(spec))) + ) +} + +## Upload one zip (see upload_zips()); its row, with key, uploaded and source set. +pipeline_upload_zip <- function(zip, out, previous, bucket, releaseId, remote, replaceChanged) { + baseUrl <- pipeline_s3_base_url(bucket) + same <- previous[previous$zipfile == out$zipfile & previous$md5 == out$md5, , drop = FALSE] + if (nrow(same) > 0) { + h <- pipeline_s3_head(paste0(baseUrl, "/", same$key[1])) + if (identical(as.integer(h$status), 200L) && identical(h$md5, out$md5)) { + out$key <- same$key[1] + out$uploaded <- h$modified + out$source <- "reused" + return(out) + } + } + + key <- pipeline_s3_key(bucket, releaseId, out$zipfile) + act <- .uploadAction( + pipeline_s3_state(remote, bucket, key), + out$md5, + key, + replace = replaceChanged, + released = key %in% previous$key + ) + if (act$action != "found") { + pipeline_s3_put(remote, bucket, key, zip) + } + + url <- paste0(baseUrl, "/", key) + h <- pipeline_s3_head(url) + ## found with the zip's MD5 but not public (an upload without the ACL): every rerun would find + ## it and fail here, so the same bytes go up again, public + if (act$action == "found" && !identical(as.integer(h$status), 200L)) { + pipeline_s3_put(remote, bucket, key, zip) + act$action <- "upload" + h <- pipeline_s3_head(url) + } + if (!identical(as.integer(h$status), 200L)) { + stop("not public: an anonymous HEAD of ", url, " gave HTTP ", h$status) + } + if (!identical(h$md5, out$md5) || !isTRUE(h$size == file.size(zip))) { + stop( + "the public object's MD5 and size (", + h$md5, + ", ", + h$size, + ") differ from the zip's (", + out$md5, + ", ", + file.size(zip), + ")" + ) + } + out$key <- key + out$uploaded <- h$modified + out$source <- c(found = "found", update = "updated", upload = "uploaded")[[act$action]] + out +} + +## Upload one batch's zips. Each zip is, in order of preference: +## - "reused": an earlier release (`lookup`, from pipeline_previous_lookup()) has the identical +## zip in this bucket, still public with that MD5; +## - "found": the zip's key already holds it (an interrupted run); +## - "updated": the key holds another MD5 (the zip was rebuilt), replaced in place. Only with +## replaceChanged (replace_changed in _local.R), and never for a key the previous release's +## index refers to (.uploadAction() stops); otherwise the upload stops, naming the zip; +## - "uploaded" as a new object. +## Every object is then checked with an anonymous HEAD: public, with the zip's MD5 and size. +## With dryRun nothing in the bucket is read or written: `source` is "reused" (key from `lookup`, +## not checked) or "dry run" (key NA). Returns one row per zip: subset, key, md5, zipfile (path +## below the release), uploaded (the object's Last-Modified, epoch seconds; NA in a dry run) and +## source. +upload_zips <- function( + zips, + spec, + bucket, + releaseId, + dryRun, + lookup, + remote = "arbutus", + replaceChanged = FALSE +) { + pipeline_load() # .uploadAction(); an upload worker starts without the package + previous <- if (length(zips) > 0) pipeline_previous_rows(lookup, spec) + rows <- lapply(zips, function(zip) { + subset <- basename(dirname(zip)) + out <- data.frame( + subset = subset, + key = NA_character_, + md5 = unname(tools::md5sum(zip)), + zipfile = pipeline_zip_relpath(spec, subset), + uploaded = NA_real_, + source = "dry run" + ) + if (isTRUE(dryRun)) { + prev <- previous$key[previous$zipfile == out$zipfile & previous$md5 == out$md5] + if (length(prev) > 0) { + out$key <- prev[1] + out$source <- "reused" + } + return(out) + } + tryCatch( + pipeline_upload_zip(zip, out, previous, bucket, releaseId, remote, replaceChanged), + error = \(e) stop(out$zipfile, ": ", conditionMessage(e), call. = FALSE) + ) + }) + if (length(rows) == 0) { + ## an errored zips branch (error = "null") + return(data.frame( + subset = character(0), + key = character(0), + md5 = character(0), + zipfile = character(0), + uploaded = numeric(0), + source = character(0) + )) + } + do.call(rbind, rows) +} diff --git a/data-raw/pipeline/R/zips.R b/data-raw/pipeline/R/zips.R index 8bb06a0..ce635d4 100644 --- a/data-raw/pipeline/R/zips.R +++ b/data-raw/pipeline/R/zips.R @@ -10,7 +10,7 @@ pipeline_zip_path <- function(outRoot, spec, subset) { file.path(outRoot, "zips", pipeline_zip_relpath(spec, subset)) } -## The zip's path below /zips (and below the release's Drive folder), e.g. +## The zip's path below /zips (and below the release's prefix in the bucket), e.g. ## historical/MSY/39_MSY_2020.zip; this is the index's `zipfile`. pipeline_zip_relpath <- function(spec, subset) { scen <- if (is.na(spec$gcm)) character(0) else paste0(spec$gcm, "_ssp", spec$ssp) @@ -51,7 +51,7 @@ pipeline_zip_rows <- function(spec, subset, zipfile) { ## byte-identical whenever the files are (names, contents and modification times): names in ## C-locale order, no directory entries (-D), and no extra attributes such as access times or ## owners (-X). An unchanged zip then keeps its MD5 when it is rebuilt, and the next release can -## reuse its Drive file. Needs the `zip` program. +## reuse its object in the bucket. Needs the `zip` program. pipeline_write_zip <- function(zip, dir, files = NULL) { zip <- normalizePath(zip, mustWork = FALSE) owd <- setwd(dir) diff --git a/data-raw/pipeline/README.md b/data-raw/pipeline/README.md index f405323..b17ff2e 100644 --- a/data-raw/pipeline/README.md +++ b/data-raw/pipeline/README.md @@ -1,15 +1,17 @@ # ClimateNA data pipeline -A [targets](https://docs.ropensci.org/targets/) pipeline that builds one data release of climateData's tile archives. It runs ClimateNA in the Docker image from `docker/climatena/`, checks every output, cuts the zips, uploads them to Google Drive and builds the tile index. +A [targets](https://docs.ropensci.org/targets/) pipeline that builds one data release of climateData's tile archives. It runs ClimateNA in the Docker image from `docker/climatena/`, checks every output, cuts the zips, uploads them to a public bucket on Arbutus (the Alliance's object storage, through rclone) and builds the tile index. ClimateNA writes values even where the DEM tile has no elevation, computed at the wrong elevation. When the zips are cut, those cells are set to NODATA unless their centre lies in Canada (GADM 4.1, level 0, holes filled, downloaded once to `/boundary/`); the raw outputs keep ClimateNA's values (#40). ClimateNA also leaves some land cells (cells with a DEM elevation) empty: its future data miss some coastal cells, and a few cells get no values at all. Each such cell gets ClimateNA's point-mode output at the nearest land cell it covers (within `fill_max_km` in `release.yml`), run with the empty cell's own elevation. The cells and their sources are found once per release from one reference period per class (historical: the last historical year; future: the first scenario's first year); the point-mode outputs are stored beside the raw period zips (`.fill-.csv`) and written into the zips when they are cut. The index lists every filled cell (`filled_cells`). -- `release.yml`: the release (committed): ClimateNA version, years, scenarios, image, Drive folder. -- `_local.R`: per machine (gitignored; copy `_local.R.example`): paths, the container user, how many workers, dry run, and whether a changed zip may replace its file on Drive (`replace_changed`, off by default). The pipeline uses at most half of each node's cores: a larger worker count is lowered, with a message. +- `release.yml`: the release (committed): ClimateNA version, years, scenarios, image, bucket. +- `_local.R`: per machine (gitignored; copy `_local.R.example`): paths, the container user, how many workers, dry run, the rclone remote for the bucket, and whether a changed zip may replace its object (`replace_changed`, off by default; never an object a released index refers to). The pipeline uses at most half of each node's cores: a larger worker count is lowered, with a message. Paths must not hold spaces or quotes. - `_targets.R`, `R/`: the pipeline. +Uploads need an rclone remote with the bucket's S3 keys on the node that runs `tar_make()`; the maintainer vignette shows how to get them. After a run whose uploads changed, the `catalogue` target rewrites the bucket's browsable catalogue (every page outside the excluded folders) with buckethost's `generateIndexes()` and the `catalogue` settings in `release.yml`, which must match those of the bucket's other users. Its failure is reported and leaves the archives as they are. + Run from the package root on a compute node: ```r @@ -21,7 +23,34 @@ targets::tar_make( See the maintainer vignette, `vignette("maintaining-climate-data")`, for the full workflow. -## Prototype checks (2026-11-04) +## Bucket devtest (2026-12-03) + +Tile 39 at 3 arcmin, ClimateNA v7.70, uploaded from a compute node to a scratch prefix (`climateData-devtest/`) in the real bucket. The prefix was deleted afterwards. + +| Check | Result | +|---|---| +| First run | 14 zips (22 MB) uploaded, no errors or warnings. The index's keys are under the scratch prefix and its `base_url` is set. An anonymous HEAD of three objects gave 200 with ETag = MD5. | +| Rerun | No upload branches ran. | +| A changed zip (one byte appended), through `upload_zips()` (the pipeline recuts a zip changed in its store) | Without `replace_changed`: stopped, naming the zip and `replace_changed`. With it: `updated`, and the public object's MD5 changed. The original was then put back. | +| The same changed zip, with the first run's index as the released index | Stopped with "released index", with or without `replace_changed`. The public object kept its MD5. | +| A second release whose previous index is the first's | All 14 zips `reused`, keys under the first release's prefix. Nothing uploaded. | +| The largest 1 arcmin zip (294 MB) | One part (ETag = MD5), 97 s: 2.9 MiB/s for one stream. The 11.8 MiB/s measured earlier was a multipart upload. | +| Catalogue, dry run, whole bucket | Stopped after 90 min. The bucket holds 2.9 million objects in 130,358 folders, nearly all under `wbi/`. buckethost 0.3.2 checks every key once per folder: 0.12 s per folder, about 4.5 h to build the pages, then about 14 h to upload them one at a time (0.39 s each). | +| Catalogue, dry run, `wbi/` excluded (as the live catalogue is) | 16 pages in 1 s. | + +## DEM devtest (2026-12-03) + +A 3 arcmin release with no `dem_dir` (the pipeline builds its DEM tiles), historical 2020-2021, tiles 7, 8, 9, 39 and 68, dry run, on a compute node. + +| Check | Result | +|---|---| +| Tile grid rule on the GADM boundary | The shipped `tiles.gpkg`: the same 86 tiles and coordinates. | +| DEM tiles built from GTOPO30 | 81 tiles in 19 s, with the 3 arcmin release's ids and grids. Every cell with an elevation in both has the same value. Tiles 7, 8, 9 and 68 have no elevation in 13, 2, 4 and 1 cells that the release's tiles have, all outside Canada. | +| Reading the built tiles | The DEM checks pass and terra reads them. Every data row starts with a space, as in the release's tiles: GDAL 3.8 can't read back rows that start with `nan`. | +| ClimateNA on a built tile | Tile 39, 2020-2021: all 265 output files byte-identical to the release's. Tiles 7, 8, 9 and 68 differ, as their DEM tiles do. | +| A failed GTOPO30 download (first run) | The DEM build went on with no input; the download now stops the run. | + +## Prototype checks (2026-11-04, uploads to Google Drive) One tile (39) at 3 arcmin, ClimateNA v7.70, `crew_controller_local(workers = 4)`, dry run. A ClimateNA run took about 45 s per year, so a decade batch takes about 8 minutes. diff --git a/data-raw/pipeline/_local.R.example b/data-raw/pipeline/_local.R.example index ec0d3bf..91fa830 100644 --- a/data-raw/pipeline/_local.R.example +++ b/data-raw/pipeline/_local.R.example @@ -8,7 +8,10 @@ local <- list( ## an unpacked ClimateNA release, mounted read-only into the containers climatena_dir = "/path/to/ClimateNA_v7.70", - ## DEM tiles (can_dem_.asc, Windows line endings) at the release's resolution + ## DEM tiles (can_dem_.asc, Windows line endings) at the release's resolution. Leave it out + ## for a new release: the pipeline then builds them under /dem/ from the GTOPO30 mosaic. + ## The 3 and 1 arcmin releases set it (their own DEM folders), since a rebuilt tile never matches + ## a used one byte for byte, and any change reruns every ClimateNA period of that tile. dem_dir = "/path/to/ClimateNA_data/dem", ## everything the pipeline writes: raw/, zips/, _targets/, logs, the index and the report. @@ -27,23 +30,26 @@ local <- list( ## NULL for all tiles with a DEM, or a subset for testing, e.g. 39L tiles = NULL, - ## TRUE: build everything but upload nothing to Drive + ## TRUE: build everything but read or write nothing in the bucket dry_run = TRUE, - ## TRUE: when a rebuilt zip differs from the file of that name in the release's Drive folder, - ## replace that file in place (same Drive ID). FALSE: such an upload stops with an error, so a - ## shipped release's files change only when you ask. + ## TRUE: when a rebuilt zip differs from the object under its key in the bucket, replace that + ## object in place. FALSE: such an upload stops with an error, so a release's files change + ## only when you ask. Never applies to an object the previous release's index refers to: + ## installed copies of that release check downloads against its MD5, so a fix to released + ## data needs a new release_id. replace_changed = FALSE, - ## the Google account for uploads: its OAuth token must be cached on this machine - ## (googledrive::drive_auth() once, interactively) - drive_email = NULL, # e.g. "you@example.org" + ## the rclone remote for the bucket, set up on this machine with its EC2 keys (see the + ## maintainer vignette) + rclone_remote = "arbutus", ## how many uploads at once, on this machine upload_workers = 8L, - ## the previous release's index: zips identical to its (same path and MD5) reuse its Drive - ## files instead of being uploaded again. NULL for the package's shipped index. + ## the previous release's index: zips identical to its (same path and MD5) reuse its objects + ## in the bucket instead of being uploaded again. NULL for the package's shipped index; a + ## missing file means nothing to reuse. previous_index = NULL, ## seconds before a ClimateNA run is stopped and its period counted as failed diff --git a/data-raw/pipeline/_targets.R b/data-raw/pipeline/_targets.R index 706ca30..f1bda07 100644 --- a/data-raw/pipeline/_targets.R +++ b/data-raw/pipeline/_targets.R @@ -25,7 +25,8 @@ container_uid <- local$uid container_gid <- local$gid tile_subset <- local$tiles dry_run <- local$dry_run -## replace a release folder's file in place when its rebuilt zip differs; otherwise that stops +## replace a key's object in place when its rebuilt zip differs (never one a released index +## refers to); otherwise that stops replace_changed <- isTRUE(local$replace_changed) run_timeout <- local$run_timeout %||% 3600 # seconds per ClimateNA run ## the previous release's index, whose identical zips are reused rather than uploaded again @@ -36,10 +37,8 @@ previous_index_path <- local$previous_index %||% "inst/extdata/ClimateNA_tiles.s if (!is.null(local$work_dir)) { Sys.setenv(CLIMATENA_WORK_DIR = local$work_dir) } -drive_email <- local$drive_email # the Google account whose cached token uploads use -if (!is.null(drive_email)) { - options(gargle_oauth_email = drive_email) -} +## the rclone remote, set up on this node with the bucket's EC2 keys, that uploads use +rclone_remote <- local$rclone_remote %||% "arbutus" devtools::load_all(".", quiet = TRUE) # the main process uses the checkout too @@ -75,7 +74,7 @@ tar_option_set( ## include the load_all()ed climateData, which isn't installed; pipeline_load() loads it packages = character(0), ## ClimateNA runs go to climatena_controller; uploads to a few local workers on this node, - ## where the Drive token is + ## where the rclone remote is controller = crew::crew_controller_group( climatena_controller, crew::crew_controller_local(name = "uploads", workers = upload_workers) @@ -87,6 +86,9 @@ tar_option_set( ) tar_source("data-raw/pipeline/R") +## paths reach zip, docker and rclone through the shell unquoted (paths.R) +pipeline_check_paths(local) + ## one set of targets per archive type mapped <- tar_map( values = data.frame(type = unlist(cfg$types)), @@ -175,17 +177,19 @@ mapped <- tar_map( deployment = "worker" ), - ## each zip as an earlier release's identical file, or a file in the release's Drive folder - ## (replaced in place when the zip changed, with replace_changed; otherwise that stops) + ## each zip as an earlier release's identical object, or an object under the release's prefix + ## in the bucket (replaced in place when the zip changed, with replace_changed, unless a + ## released index refers to it; otherwise that stops) tar_target( uploads, upload_zips( zips, specs, - release_folders, + bucket, + release_id, dry_run, previous_lookup, - drive_email, + rclone_remote, replace_changed ), pattern = map(zips, specs), @@ -202,9 +206,28 @@ list( tar_target(climatena_version, cfg[["climatena_version"]]), tar_target(dem_resolution, cfg[["dem_resolution"]]), tar_target(image, cfg[["image"]]), - tar_target(drive_parent, cfg[["drive_parent"]]), + ## the bucket the archives go to, and its public URL (an archive's URL is base_url/key) + tar_target(bucket, cfg[["bucket"]]), + tar_target(base_url, pipeline_s3_base_url(bucket)), + tar_target(catalogue_settings, cfg[["catalogue"]]), tar_target(climatena_dir, climatena_dir_path), - tar_target(dem_dir, dem_dir_path), + ## the DEM tiles: the folder _local.R names, or (with none) built from the GTOPO30 mosaic once + ## the tile grid rule is shown to give the shipped tiles.gpkg (data-raw/pipeline/R/dem.R) + if (pipeline_dem_mode(local)) { + list( + tar_target(gtopo30, pipeline_gtopo30(out_root, bucket), format = "file", error = "stop"), + tar_target(tile_grid, pipeline_tile_grid_check(canada), format = "file", error = "stop"), + tar_target( + dem_built, + pipeline_build_dem(gtopo30, canada, dem_resolution, out_root, tile_grid), + format = "file", + error = "stop" + ), + tar_target(dem_dir, dirname(dem_built[1])) + ) + } else { + tar_target(dem_dir, dem_dir_path) + }, tar_target(out_root, out_root_path), ## the DEM folder's tiles, listed on every run: adding or removing a DEM file changes neither ## dem_dir nor the tile subset (an unchanged list rebuilds nothing) @@ -212,16 +235,26 @@ list( ## the DEM files themselves, so what is built from them follows their contents. This and the ## other release-wide inputs stop the run when they fail: under error = "null" one failure ## would become an error in every branch - tar_target(dem_files, pipeline_dem_files(dem_dir, tiles), format = "file", error = "stop"), + tar_target( + dem_files, + pipeline_dem_files(dem_dir, tiles, dem_resolution), + format = "file", + error = "stop" + ), ## the cells each tile's zips set to NODATA (no DEM elevation, centre outside Canada; #40), ## and its land cells tar_target(canada, pipeline_canada(out_root), format = "file"), tar_target(tile_masks, pipeline_tile_masks(canada, dem_files), error = "stop"), - tar_target(previous_index, previous_index_path, format = "file"), + ## none for a resolution's first release: nothing to reuse + tar_target( + previous_index, + if (file.exists(previous_index_path)) previous_index_path else character(0), + format = "file" + ), mapped, - ## all types together, for the Drive folders and the index + ## all types together, for the previous-release lookup and the index tar_combine(specs_all, mapped[["specs"]], command = c(!!!.x), iteration = "list"), ## land cells ClimateNA leaves empty, and the nearest land cell it covers for each (checked @@ -250,11 +283,12 @@ list( error = "stop" ), tar_target( - release_folders, - pipeline_release_folders(specs_all, release_id, drive_parent, dry_run, out_root) + previous_lookup, + pipeline_previous_lookup(previous_index, specs_all, out_root, base_url) ), - tar_target(previous_lookup, pipeline_previous_lookup(previous_index, specs_all, out_root)), tar_combine(uploads_all, mapped[["uploads"]], command = rbind(!!!.x)), + ## release.yml's years, periods, GCMs and SSPs against available() + tar_target(settings_check, pipeline_settings_vs_available(cfg)), tar_combine(manifests, mapped[["batch"]], command = c(!!!.x)), ## the release's ClimateNA_tiles.sqlite @@ -268,15 +302,27 @@ list( release_id, climatena_version, dem_resolution, - fill_points + fill_points, + base_url ), format = "file" ), - ## errors, warnings and missing zips, refreshed on every run (empty when all is well) + ## the bucket's browsable catalogue, rewritten once per run whose uploads changed (never in a + ## dry run). A failure is recorded in the report; the data are fine without it + tar_target(catalogue, { + uploads_all + pipeline_catalogue(index, bucket, rclone_remote, catalogue_settings, dry_run) + }), + + ## errors, warnings, missing zips and settings that differ from available(), refreshed on every + ## run (empty when all is well); after the catalogue, so its error is in this run's report tar_target( report, - build_report(index, specs_all, uploads_all, out_root), + { + catalogue + build_report(index, specs_all, uploads_all, out_root, settings_check) + }, format = "file", cue = tar_cue(mode = "always") ) diff --git a/data-raw/pipeline/release.yml b/data-raw/pipeline/release.yml index 790179a..1ce3e08 100644 --- a/data-raw/pipeline/release.yml +++ b/data-raw/pipeline/release.yml @@ -32,5 +32,20 @@ min_version: image: ghcr.io/predictiveecology/climatena-wine:latest -## Drive folder holding the archives; each release gets a subfolder named release_id -drive_parent: 1ldnlPHklhJsyJ8YBdI7IqUTxX9aW6UIc +## The bucket holding the archives (Arbutus object storage, S3): each zip is the object +## //, public at //. The container is +## the project id and the bucket name, as in the public URL. +bucket: + endpoint: https://object-arbutus.alliancecan.ca + container: "529feda02d404836b0e91b1d360b4df0:predictiveecology" + prefix: climateData + +## The bucket's browsable catalogue (buckethost::generateIndexes()), refreshed after uploads. It +## rewrites every page outside the excluded folders, so these match the settings of the bucket's +## other users: a heading of null shows the bucket's name. `exclude`: folders left out of the catalogue (the +## live catalogue leaves out wbi/, about 2.9 million objects). +catalogue: + heading: null + disclaimer_html: "" + host_note: "Hosted on an S3-compatible object store." + exclude: [wbi] diff --git a/inst/extdata/ClimateNA_tiles.sqlite b/inst/extdata/ClimateNA_tiles.sqlite index 9723134..9947bd9 100755 Binary files a/inst/extdata/ClimateNA_tiles.sqlite and b/inst/extdata/ClimateNA_tiles.sqlite differ diff --git a/man/ClimateNA_path.Rd b/man/ClimateNA_path.Rd deleted file mode 100644 index b36818a..0000000 --- a/man/ClimateNA_path.Rd +++ /dev/null @@ -1,35 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/ClimateNA_createTiles.R -\name{ClimateNA_path} -\alias{ClimateNA_path} -\title{Construct target output paths for ClimateNA data} -\usage{ -ClimateNA_path( - dataPath, - tile = NULL, - type = NULL, - msy = NULL, - gcm = NULL, - ssp = NULL -) -} -\arguments{ -\item{dataPath}{character. path to ClimateNA data directory.} - -\item{tile}{integer. tile id (e.g., the output of \code{tileID()}).} - -\item{type}{character. denotes the table in the sqlite database to access. -one of 'historical', 'future', 'historical_normals', or 'future_normals'.} - -\item{msy}{character. one of 'MSY', 'M', or 'Y', corresponding to all, monthly, or yearly data.} - -\item{gcm}{character. name of GCM available in ClimateNA.} - -\item{ssp}{integer. one of the available SSPs in ClimateNA (e.g., \code{370} or \code{585})} -} -\value{ -character string representing the path to the target output directory -} -\description{ -Construct target output paths for ClimateNA data -} diff --git a/man/ClimateNA_sql.Rd b/man/ClimateNA_sql.Rd index b035e02..b638ed9 100644 --- a/man/ClimateNA_sql.Rd +++ b/man/ClimateNA_sql.Rd @@ -2,12 +2,9 @@ % Please edit documentation in R/ClimateNA_createTiles.R \name{ClimateNA_sql} \alias{ClimateNA_sql} -\alias{checksums_sql} -\title{Connect to ClimateNA tile and checksums database} +\title{Connect to a table of the ClimateNA tile index} \usage{ ClimateNA_sql(dbfile, type, readonly = FALSE) - -checksums_sql(dbfile, type) } \arguments{ \item{dbfile}{path to \code{.sqlite} database file} @@ -21,8 +18,12 @@ table is not created). Use for lookups, so that many processes can read one data \value{ named list containing: - \code{db}, the database connection; -- \code{df}, a lazy \code{tbl_dbi} object (see \code{dbplyr}). +- \code{df}, a lazy \code{tbl_dbi} object of the type's view (see \code{dbplyr}). } \description{ -Connect to ClimateNA tile and checksums database +A type's rows are in the table \verb{tiles_}, each referring to its archive (the \code{archives} +table) by id. The view named for the type gives each row with its archive's \code{zipfile}, +\code{archived}, \code{key} and \code{uploaded} (the archive's \code{verified}), and is what \code{df} reads. With +\code{readonly = FALSE}, the tables and the view are created when missing; rows are written to +\verb{tiles_}. } diff --git a/man/climateDataRelease.Rd b/man/climateDataRelease.Rd index fc11136..d6929d2 100644 --- a/man/climateDataRelease.Rd +++ b/man/climateDataRelease.Rd @@ -9,12 +9,13 @@ climateDataRelease() \value{ a list with \code{release_id} (e.g. \code{"cna-v7.70-3arcmin"}), \code{climatena_version} (the ClimateNA release that produced the data) and \code{dem_resolution} (e.g. \code{"3arcmin"}). Indexes -made before releases were recorded give \code{release_id = "pre-3.0.0"}. +made before releases were recorded (before climateData 2.3.0) give \code{release_id = "pre-2.3.0"}. } \description{ Each climateData release ships a tile index pointing at one release of the ClimateNA -archives on Google Drive. Use this to tell releases apart, e.g. in the cache key of code that -caches \code{prepClimateLayers()} results, so a new data release isn't served from an old cache. +archives in the Arbutus bucket. Use this to tell releases apart, e.g. in the cache key of +code that caches \code{prepClimateLayers()} results, so a new data release isn't served from an +old cache. } \examples{ climateDataRelease()$release_id diff --git a/man/dot-uploadAction.Rd b/man/dot-uploadAction.Rd index 456b39d..9851ec0 100644 --- a/man/dot-uploadAction.Rd +++ b/man/dot-uploadAction.Rd @@ -2,28 +2,31 @@ % Please edit documentation in R/pipelineUpload.R \name{.uploadAction} \alias{.uploadAction} -\title{What to do with a zip on Drive} +\title{What to do with a zip in the bucket} \usage{ -.uploadAction(there, md5, gid = NULL, replace = FALSE) +.uploadAction(there, md5, key = NULL, replace = FALSE, released = FALSE) } \arguments{ -\item{there}{data.frame with columns \code{id} and \code{md5} (\code{NA} when Drive gives none).} +\item{there}{data.frame with columns \code{id} and \code{md5} (\code{NA} when the store gives none).} \item{md5}{character. The zip's MD5.} -\item{gid}{character or \code{NULL}. The zip's Drive ID in the index, if it has one.} +\item{key}{character or \code{NULL}. The zip's object key, if it has one.} -\item{replace}{logical. Replace a differing same-named file in place?} +\item{replace}{logical. Replace a differing object in place?} + +\item{released}{logical. Does a released index (the previous release's) refer to \code{key}?} } \value{ list: \code{action} (\code{"found"}, \code{"update"} or \code{"upload"}) and \code{id} (\code{NA} for \code{"upload"}). } \description{ -Given the files of the same name already in the zip's release folder: reuse one with the same -MD5 (\code{"found"}); else, if \code{replace}, replace a differing one in place (\code{"update"}), so its -Drive ID, which the index holds as \code{gid}, stays the same; else upload a new file (\code{"upload"}). -When several same-named files differ, the one with ID \code{gid} is updated; if none has it, this -stops. Without \code{replace}, a differing same-named file stops the upload, so a shipped -release's files change only when the maintainer asks (\code{replace_changed} in \verb{_local.R}). +Given the objects already under the zip's key (one at most in a bucket): reuse one with the +same MD5 (\code{"found"}); else, if \code{replace}, replace a differing one in place (\code{"update"}); else +upload a new object (\code{"upload"}). When several candidates differ, the one with ID \code{key} is +updated; if none has it, this stops. Without \code{replace}, a differing object stops the upload, +so a release's files change only when the maintainer asks (\code{replace_changed} in \verb{_local.R}). +An object a released index refers to (\code{released}) is never replaced: installed copies of that +release check downloads against its MD5, so a fix to released data needs a new release id. } \keyword{internal} diff --git a/man/getClimateTiles.Rd b/man/getClimateTiles.Rd index a3dbe33..5da03e8 100644 --- a/man/getClimateTiles.Rd +++ b/man/getClimateTiles.Rd @@ -9,7 +9,8 @@ getClimateTiles(tile, climateURLs, climatePath, needVars = NULL) \arguments{ \item{tile}{integer. tile id (e.g., the output of \code{tileID()}).} -\item{climateURLs}{list of lists of tile URLs, with outer list names corresponding to tile ids.} +\item{climateURLs}{list of data frames of tile archives (\code{url} and \code{md5}, as returned by +\code{\link[=getClimateURLs]{getClimateURLs()}}), named by tile id.} \item{climatePath}{character string specifying the directory path to put climate data.} @@ -19,7 +20,9 @@ e.g., \code{c("historical_CMD_sm", "future_CMD_sp")}. If \code{NULL}, the default, then all files will be extracted.} } \value{ -(invisibly) a list of length \code{tileIDs} containing the result of \code{preProcess()} calls +(invisibly) a list with one element per tile, of no use: \code{getClimateTiles()} is called +for its side effect, the tile's archives downloaded to and extracted in +\verb{/}. } \description{ Download and extract multiple archives per tile (by decade) diff --git a/man/getClimateURLs.Rd b/man/getClimateURLs.Rd index 358d70a..169f677 100644 --- a/man/getClimateURLs.Rd +++ b/man/getClimateURLs.Rd @@ -28,7 +28,8 @@ one of 'historical', 'future', 'historical_normals', or 'future_normals'.} \item{ssp}{integer. one of the available SSPs in ClimateNA (e.g., \code{370} or \code{585})} } \value{ -list of Google Drive ids, with names corresponding the tile ids. +list of data frames, one per tile (named by tile id), with one row per archive: +\code{url}, the archive's public URL, and \code{md5}, its MD5 checksum as recorded in the tile index. } \description{ Look up the URLs for a set of climate tiles diff --git a/man/imports.Rd b/man/imports.Rd index b843fdb..99d070a 100644 --- a/man/imports.Rd +++ b/man/imports.Rd @@ -1,29 +1,13 @@ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/imports.R -\name{assessGoogle} -\alias{assessGoogle} +\name{.listFilesInArchive} \alias{.listFilesInArchive} \alias{.whichExtractFn} -\alias{getRemoteMetadata} -\alias{googledriveIDtoHumanURL} \title{non-exported objects and functions from other packages} \usage{ -assessGoogle( - url, - archive = NULL, - targetFile = NULL, - destinationPath = getOption("reproducible.destinationPath", "."), - verbose = getOption("reproducible.verbose", 1), - team_drive = NULL -) - .listFilesInArchive(archive, dontUse = NULL) .whichExtractFn(archive, args, dontUse = NULL) - -getRemoteMetadata(targetFile, isGDurl, url) - -googledriveIDtoHumanURL(id) } \description{ non-exported objects and functions from other packages diff --git a/man/prepClimateLayers.Rd b/man/prepClimateLayers.Rd index 7f89698..9501f60 100644 --- a/man/prepClimateLayers.Rd +++ b/man/prepClimateLayers.Rd @@ -74,7 +74,6 @@ from earlier releases are not used again and can be deleted. } \examples{ if (require("archive", quietly = TRUE) && - require("googledrive", quietly = TRUE) && require("SpaDES.tools", quietly = TRUE) && !isTRUE(as.logical(Sys.getenv("CI", "false")))) { dPath <- file.path(tempdir(), "test_prepClimateLayers") @@ -124,7 +123,7 @@ if (require("archive", quietly = TRUE) && climateRasters <- prepClimateLayers( climateVarsList = climateVariables, - srcdir = climatePath, ## raw inputs, downloaded from Google Drive + srcdir = climatePath, ## raw inputs, downloaded from the bucket dstdir = climatePathOut, ## intermediate + final outputs gcm = GCM, ssp = SSP, diff --git a/man/rewrite_asc.Rd b/man/rewrite_asc.Rd index 18e5061..2259b95 100644 --- a/man/rewrite_asc.Rd +++ b/man/rewrite_asc.Rd @@ -2,7 +2,7 @@ % Please edit documentation in R/ClimateNA_createTiles.R \name{rewrite_asc} \alias{rewrite_asc} -\title{Rewrite a \code{.asc} raster file to use Windows (CR) line-endings} +\title{Rewrite a \code{.asc} raster file to use Windows (CRLF) line-endings} \usage{ rewrite_asc(f) } @@ -10,5 +10,6 @@ rewrite_asc(f) \item{f}{character. path to a \code{.asc} raster file} } \description{ -Rewrite a \code{.asc} raster file to use Windows (CR) line-endings +ClimateNA reads DEM files only with Windows line endings. The file is rewritten with CRLF line +endings on every platform. } diff --git a/tests/testthat/_snaps/archiveCheck.md b/tests/testthat/_snaps/archiveCheck.md index 6eca77a..65444b1 100644 --- a/tests/testthat/_snaps/archiveCheck.md +++ b/tests/testthat/_snaps/archiveCheck.md @@ -4,5 +4,5 @@ .archiveExpected(rows, "historical") Condition Error: - ! Index rows for one archive (Drive ID 1aBcDeFgHiJkLmNoPqRsTuVwXyZ012345) disagree on zipfile: historical/yearly/39_Y_2010.zip, historical/yearly/39_Y_2020.zip + ! Index rows for one archive (key climateData/r1/historical/Y/39_Y_2010.zip) disagree on zipfile: historical/yearly/39_Y_2010.zip, historical/yearly/39_Y_2020.zip diff --git a/tests/testthat/helper-index.R b/tests/testthat/helper-index.R new file mode 100644 index 0000000..cf369e2 --- /dev/null +++ b/tests/testthat/helper-index.R @@ -0,0 +1,50 @@ +## A small tile index in the current schema, for tests that mock ClimateNA_tiles_sqlite(): +## historical MSY for tile 39, 2011-2020 in one zip of release r1 and 2021 in a zip that r1 reuses +## from release r0, both under the bucket URL https://h/c:b. Removed when `env` ends. +testIndexKeys <- c( + r1 = "climateData/r1/historical/MSY/39_MSY_2011.zip", + r0 = "climateData/r0/historical/MSY/39_MSY_2021.zip" +) +testIndexMd5 <- c(r1 = strrep("1", 32), r0 = strrep("0", 32)) + +local_test_index <- function(env = parent.frame()) { + f <- file.path(withr::local_tempdir(.local_envir = env), "ClimateNA_tiles.sqlite") + x <- ClimateNA_sql(f, "historical") # the tile table, the archives table and the view + db <- x$db + .archivesUpsert( + db, + data.frame( + key = unname(testIndexKeys), + type = "historical", + zipfile = sub("^climateData/r[01]/", "", testIndexKeys), + md5 = unname(testIndexMd5), + n_files = 1L, + size = 1, + verified = NA_real_ + ) + ) + ids <- DBI::dbGetQuery(db, "SELECT id, key FROM archives") + DBI::dbAppendTable( + db, + "tiles_historical", + data.frame( + msy = "MSY", + year = 2011:2021, + tileid = 39L, + archive = ids$id[match(rep(testIndexKeys, c(10, 1)), ids$key)] + ) + ) + .releaseCreate(db) + .releaseWrite( + db, + data.frame( + release_id = "r1", + climatena_version = "7.70", + dem_resolution = "3arcmin", + base_url = "https://h/c:b", + created = 0 + ) + ) + DBI::dbDisconnect(db) + f +} diff --git a/tests/testthat/test-archiveCheck.R b/tests/testthat/test-archiveCheck.R index 10ade2a..39ae3cf 100644 --- a/tests/testthat/test-archiveCheck.R +++ b/tests/testthat/test-archiveCheck.R @@ -31,8 +31,12 @@ test_that(".archiveExpected names historical, future and normals members", { test_that(".archiveExpected stops when one zip's index rows disagree", { rows <- rbind(rowsH(2013), rowsH(2014, zip = "historical/yearly/39_Y_2020.zip")) - rows$gid <- "1aBcDeFgHiJkLmNoPqRsTuVwXyZ012345" - expect_error(.archiveExpected(rows, "historical"), rows$gid[1], fixed = TRUE) + rows$key <- "climateData/r1/historical/Y/39_Y_2010.zip" + expect_error( + .archiveExpected(rows, "historical"), + paste0("(key ", rows$key[1], ")"), + fixed = TRUE + ) expect_snapshot(.archiveExpected(rows, "historical"), error = TRUE) }) @@ -138,44 +142,3 @@ test_that(".archiveExpected names future normals folders as ClimateNA writes the expect_length(e, 50) expect_contains(e, "CanESM5_ssp245_2011-2040Y/rsds.asc") }) - -test_that(".archiveIndexGaps finds years the index lacks", { - idx <- rowsH(setdiff(available("historical")$years, 2013L)) - g <- .archiveIndexGaps(idx, "historical") - expect_equal(g$year, 2013L) - expect_equal(g$tileid, 39L) -}) - -test_that(".archiveIndexGaps finds future normals scenarios the index lacks", { - av <- available("future_normals") - full <- expand.grid( - tileid = 39L, - msy = "Y", - gcm = av$gcms, - ssp = av$ssps, - period = av$periods, - stringsAsFactors = FALSE - ) - idx <- full[!(full$gcm == av$gcms[1] & full$ssp == av$ssps[1]), ] - g <- .archiveIndexGaps(idx, "future_normals") - expect_equal(nrow(g), length(av$periods)) - expect_equal(unique(g$gcm), av$gcms[1]) - expect_equal(unique(g$ssp), av$ssps[1]) -}) - -test_that(".driveProblems classifies missing, trashed and renamed files", { - zips <- data.frame( - gid = c("a", "b", "c", "d"), - zipfile = paste0("x/", c("a", "b", "c", "d"), ".zip") - ) - meta <- data.frame( - id = c("a", "b", "c"), - name = c("a.zip", "b.zip", "renamed.zip"), - md5 = "m", - size = 1, - trashed = c(FALSE, TRUE, FALSE) - ) - p <- .driveProblems(zips, meta) - expect_equal(p$gid, c("b", "c", "d")) - expect_equal(p$problem, c("drive_missing", "name_mismatch", "drive_missing")) -}) diff --git a/tests/testthat/test-archivesTable.R b/tests/testthat/test-archivesTable.R index 7427d58..e82f8c5 100644 --- a/tests/testthat/test-archivesTable.R +++ b/tests/testthat/test-archivesTable.R @@ -4,17 +4,24 @@ test_that("archives table has the declared column types", { withr::defer(DBI::dbDisconnect(db)) .archivesCreate(db) info <- DBI::dbGetQuery(db, "PRAGMA table_info(archives)") - expect_equal(info$name, c("gid", "type", "zipfile", "md5", "n_files", "size", "verified")) - expect_equal(info$type, c("TEXT", "TEXT", "TEXT", "TEXT", "INTEGER", "REAL", "REAL")) + expect_equal( + info$name, + c("id", "key", "type", "zipfile", "md5", "n_files", "size", "archived", "verified") + ) + expect_equal( + info$type, + c("INTEGER", "TEXT", "TEXT", "TEXT", "TEXT", "INTEGER", "REAL", "REAL", "REAL") + ) + expect_equal(info$pk, c(1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L)) }) -test_that(".archivesUpsert replaces rows by gid", { +test_that(".archivesUpsert replaces rows by key", { skip_if_not_installed("withr") db <- sqlite_connect_db(file.path(withr::local_tempdir(), "t.sqlite")) withr::defer(DBI::dbDisconnect(db)) .archivesCreate(db) df <- data.frame( - gid = c("a", "b"), + key = c("a", "b"), type = "future", zipfile = c("x/a.zip", "x/b.zip"), md5 = c("m1", "m2"), @@ -23,9 +30,11 @@ test_that(".archivesUpsert replaces rows by gid", { verified = c(1.7e9, NA) ) expect_equal(.archivesUpsert(db, df), 2L) + ids <- DBI::dbGetQuery(db, "SELECT id FROM archives ORDER BY key")$id df$md5[1] <- "m9" .archivesUpsert(db, df[1, ]) - out <- DBI::dbGetQuery(db, "SELECT gid, md5, size, verified FROM archives ORDER BY gid") + out <- DBI::dbGetQuery(db, "SELECT id, key, md5, size, verified FROM archives ORDER BY key") + expect_identical(out$id, ids) ## the tile tables refer to it expect_equal(out$md5, c("m9", "m2")) expect_equal(out$size, c(3e9, 3e9)) expect_equal(is.na(out$verified), c(FALSE, TRUE)) @@ -39,10 +48,40 @@ test_that("shipped index: one archives row per published zip", { withr::defer(DBI::dbDisconnect(con)) skip_if_not("archives" %in% DBI::dbListTables(con), "archives table not yet filled") types <- intersect(.allowedClimateTypes, DBI::dbListTables(con)) - gids <- DBI::dbGetQuery(con, paste("SELECT gid FROM", types, collapse = " UNION "))$gid - a <- DBI::dbGetQuery(con, "SELECT gid, md5 FROM archives") - expect_setequal(a$gid, gids) + keys <- DBI::dbGetQuery(con, paste("SELECT key FROM", types, collapse = " UNION "))$key + a <- DBI::dbGetQuery(con, "SELECT key, md5, verified FROM archives") + ## NA on both sides would still be set-equal + expect_false(anyNA(keys)) + expect_false(anyNA(a$key)) + expect_setequal(a$key, keys) expect_match(a$md5, "^[0-9a-f]{32}$") + expect_false(anyNA(a$verified)) + expect_match(.indexBaseUrl(f), "^https://object-arbutus[.]alliancecan[.]ca/") + ## the normalized index: rows refer to archives by id (it was 52 MB with paths in every row) + expect_true(DBI::dbExistsTable(con, "tiles_historical")) + expect_lt(file.size(f), 25e6) +}) + +## Each tile table row refers to its archive by id (tiles_.archive); a view with the type's +## name gives readers the archive's object key (see release.base_url), path and times, as the tile +## tables themselves held them before the index was normalized (a third of the size). +test_that("tile tables hold an archive id; views give readers the archive's columns", { + skip_if_not_installed("withr") + f <- file.path(withr::local_tempdir(), "t.sqlite") + archive <- c("zipfile", "archived", "key", "uploaded") + for (type in c("historical", "historical_normals", "future", "future_normals")) { + x <- ClimateNA_sql(f, type) + when <- if (endsWith(type, "_normals")) "period" else "year" + scenario <- if (startsWith(type, "future")) c("gcm", "ssp") + expect_identical( + DBI::dbListFields(x$db, type), + c("id", scenario, "msy", when, "tileid", "created", archive, "climatena_version") + ) + base <- DBI::dbListFields(x$db, paste0("tiles_", type)) + expect_contains(base, "archive") + expect_false(any(c(archive, "gid") %in% base)) + DBI::dbDisconnect(x$db) + } }) test_that("index tables declare a climatena_version column", { diff --git a/tests/testthat/test-dataRelease.R b/tests/testthat/test-dataRelease.R index d28bb1f..c0edfff 100644 --- a/tests/testthat/test-dataRelease.R +++ b/tests/testthat/test-dataRelease.R @@ -11,6 +11,7 @@ test_that("climateDataRelease reads the release table", { release_id = "cna-v7.70-3arcmin", climatena_version = "7.70", dem_resolution = "3arcmin", + base_url = "https://h/c:b", created = 1.7e9 ) ) @@ -22,12 +23,13 @@ test_that("climateDataRelease reads the release table", { expect_identical(r$dem_resolution, "3arcmin") }) -test_that("climateDataRelease reports an index without a release table as pre-3.0.0", { +## the release table arrived in 2.3.0 (#39); 3.0.0 is the 1 arcmin release +test_that("climateDataRelease reports an index without a release table as pre-2.3.0", { skip_if_not_installed("withr") f <- file.path(withr::local_tempdir(), "t.sqlite") DBI::dbDisconnect(sqlite_connect_db(f)) testthat::local_mocked_bindings(ClimateNA_tiles_sqlite = function() f) - expect_identical(climateDataRelease()$release_id, "pre-3.0.0") + expect_identical(climateDataRelease()$release_id, "pre-2.3.0") }) ## canClimateData calls it on every run, in many processes at once: it must read the shipped @@ -63,6 +65,7 @@ test_that(".releaseWrite keeps a single row", { release_id = "a", climatena_version = "7.70", dem_resolution = "3arcmin", + base_url = "https://h/c:b", created = 1 ) .releaseWrite(db, row) @@ -71,6 +74,26 @@ test_that(".releaseWrite keeps a single row", { expect_identical(DBI::dbGetQuery(db, "SELECT release_id FROM release")$release_id, "b") }) +## an archive's URL is the bucket's base URL plus its key: stored once, so a move of the bucket +## changes one value +test_that(".releaseWrite stores the bucket's base URL", { + skip_if_not_installed("withr") + db <- sqlite_connect_db(file.path(withr::local_tempdir(), "t.sqlite")) + withr::defer(DBI::dbDisconnect(db)) + .releaseCreate(db) + .releaseWrite( + db, + data.frame( + release_id = "a", + climatena_version = "7.70", + dem_resolution = "3arcmin", + base_url = "https://h/c:b", + created = 1 + ) + ) + expect_identical(DBI::dbGetQuery(db, "SELECT base_url FROM release")$base_url, "https://h/c:b") +}) + ## A new release's zips keep the old names. In a srcdir filled from the old index, reproducible ## found 39_Y_2020.zip and its extracted files present, skipped the new download, and the old ## data (MAR, no rsds) were used (checked 2026-11-05). diff --git a/tests/testthat/test-download.R b/tests/testthat/test-download.R new file mode 100644 index 0000000..13e9b04 --- /dev/null +++ b/tests/testthat/test-download.R @@ -0,0 +1,244 @@ +## The archives are public objects in a bucket: getClimateURLs() gives each zip's URL (the +## index's base_url and key) and MD5, and .fetchArchive() downloads it and checks it against that +## MD5 (R/download.R). + +test_that("getClimateURLs gives one row per zip", { + skip_if_not_installed("withr") + f <- local_test_index() + testthat::local_mocked_bindings(ClimateNA_tiles_sqlite = function() f) + u <- getClimateURLs("historical", tile = 39, years = 2011:2020, msy = "MSY") + expect_named(u, "39") + expect_named(u[["39"]], c("url", "md5")) + expect_identical(nrow(u[["39"]]), 1L) + expect_identical(u[["39"]]$url, paste0("https://h/c:b/", testIndexKeys[["r1"]])) + expect_identical(u[["39"]]$md5, testIndexMd5[["r1"]]) +}) + +test_that("getClimateURLs uses the stored key, whatever release it is under", { + skip_if_not_installed("withr") + f <- local_test_index() + testthat::local_mocked_bindings(ClimateNA_tiles_sqlite = function() f) + u <- getClimateURLs("historical", tile = 39, years = 2011:2021, msy = "MSY")[["39"]] + expect_identical(nrow(u), 2L) + r0 <- u[u$url == "https://h/c:b/climateData/r0/historical/MSY/39_MSY_2021.zip", ] + expect_identical(r0$md5, testIndexMd5[["r0"]]) +}) + +test_that("an index without a base URL stops naming the file", { + skip_if_not_installed("withr") + ## a release table as written before climateData 2.3.0, and no release table at all + old <- file.path(withr::local_tempdir(), "old.sqlite") + db <- sqlite_connect_db(old) + DBI::dbExecute( + db, + "CREATE TABLE release (release_id TEXT, climatena_version TEXT, dem_resolution TEXT, + created REAL)" + ) + DBI::dbDisconnect(db) + none <- file.path(withr::local_tempdir(), "none.sqlite") + DBI::dbDisconnect(sqlite_connect_db(none)) + for (f in c(old, none)) { + expect_error(.indexBaseUrl(f), "Drive index.*2[.]3[.]0") + expect_error(.indexBaseUrl(f), f, fixed = TRUE) + } +}) + +## makeClimateDEM()'s DEMdestinationPath, like prepInputs() before it, need not exist yet +test_that("a download creates its folder", { + skip_if_not_installed("withr") + d <- file.path(withr::local_tempdir(), "not", "yet") + url <- "https://h/c:b/climateData/dem/gtopo30Canada.zip" + full <- withr::local_tempfile() + writeLines("zip", full) + testthat::local_mocked_bindings(.downloadArchive = function(url, destfile) { + file.copy(full, destfile, overwrite = TRUE) + invisible(destfile) + }) + p <- .fetchArchive(url, unname(tools::md5sum(full)), d) + expect_identical(p, file.path(d, basename(url))) + expect_true(file.exists(p)) +}) + +test_that("a local zip with the right MD5 isn't downloaded", { + skip_if_not_installed("withr") + d <- withr::local_tempdir() + url <- "https://h/c:b/climateData/r1/historical/MSY/39_MSY_2011.zip" + writeLines("zip", file.path(d, basename(url))) + good <- unname(tools::md5sum(file.path(d, basename(url)))) + calls <- 0L + testthat::local_mocked_bindings(.downloadArchive = function(url, destfile) { + calls <<- calls + 1L + invisible(destfile) + }) + expect_identical(.fetchArchive(url, good, d), file.path(d, basename(url))) + expect_identical(calls, 0L) +}) + +test_that("a local zip with the wrong MD5 is downloaded again", { + skip_if_not_installed("withr") + d <- withr::local_tempdir() + url <- "https://h/c:b/climateData/r1/historical/MSY/39_MSY_2011.zip" + full <- withr::local_tempfile() + writeLines(c("the", "whole", "zip"), full) + good <- unname(tools::md5sum(full)) + p <- file.path(d, basename(url)) + writeLines("the", p) ## a partial download left behind + calls <- 0L + testthat::local_mocked_bindings(.downloadArchive = function(url, destfile) { + calls <<- calls + 1L + file.copy(full, destfile, overwrite = TRUE) + invisible(destfile) + }) + expect_identical(.fetchArchive(url, good, d), p) + expect_identical(calls, 1L) + expect_identical(unname(tools::md5sum(p)), good) +}) + +test_that("a bad download is retried once, then stops with both MD5s", { + skip_if_not_installed("withr") + d <- withr::local_tempdir() + url <- "https://h/c:b/climateData/r1/historical/MSY/39_MSY_2011.zip" + good <- strrep("a", 32) + badFile <- withr::local_tempfile() + writeLines("corrupt", badFile) + bad <- unname(tools::md5sum(badFile)) + calls <- 0L + testthat::local_mocked_bindings(.downloadArchive = function(url, destfile) { + calls <<- calls + 1L + file.copy(badFile, destfile, overwrite = TRUE) + invisible(destfile) + }) + expect_error(.fetchArchive(url, good, d), paste0(good, ".*", bad)) + expect_identical(calls, 2L) + expect_identical(list.files(d, all.files = TRUE, no.. = TRUE), character(0)) +}) + +## a rename that fails (a folder in the way, or a file lock on Windows) must not return a path +## that holds no zip +test_that("a download that can't be moved into place stops, naming the file", { + skip_if_not_installed("withr") + d <- withr::local_tempdir() + url <- "https://h/c:b/climateData/r1/historical/MSY/39_MSY_2011.zip" + dir.create(file.path(d, basename(url), "x"), recursive = TRUE) + full <- withr::local_tempfile() + writeLines("zip", full) + testthat::local_mocked_bindings(.downloadArchive = function(url, destfile) { + file.copy(full, destfile, overwrite = TRUE) + invisible(destfile) + }) + expect_error( + suppressWarnings(.fetchArchive(url, unname(tools::md5sum(full)), d)), + "39_MSY_2011[.]zip" + ) +}) + +## a session killed mid-download (on.exit never runs) leaves its .part file behind; the next fetch +## of that archive removes those unmodified for a day, never a download still running elsewhere +test_that("a fetch removes this archive's day-old partial downloads", { + skip_if_not_installed("withr") + d <- withr::local_tempdir() + url <- "https://h/c:b/climateData/r1/historical/MSY/39_MSY_2011.zip" + old <- file.path(d, "39_MSY_2011.zip.abc.part") + new <- file.path(d, "39_MSY_2011.zip.def.part") + other <- file.path(d, "39_MSY_2012.zip.ghi.part") + file.create(c(old, new, other)) + Sys.setFileTime(c(old, other), Sys.time() - 2 * 86400) + full <- withr::local_tempfile() + writeLines("zip", full) + testthat::local_mocked_bindings(.downloadArchive = function(url, destfile) { + file.copy(full, destfile, overwrite = TRUE) + invisible(destfile) + }) + .fetchArchive(url, unname(tools::md5sum(full)), d) + expect_false(file.exists(old)) + expect_true(file.exists(new)) + expect_true(file.exists(other)) +}) + +## an index whose tile rows refer to an archive its archives table lacks is broken: say which +## rows, rather than fail later on an NA key or MD5 +test_that("getClimateURLs stops naming the rows with no archive", { + skip_if_not_installed("withr") + f <- local_test_index() + db <- sqlite_connect_db(f) + DBI::dbExecute(db, "DELETE FROM archives WHERE key = ?", params = list(testIndexKeys[["r0"]])) + DBI::dbDisconnect(db) + testthat::local_mocked_bindings(ClimateNA_tiles_sqlite = function(...) f) + expect_error( + getClimateURLs("historical", tile = 39, years = 2011:2021, msy = "MSY"), + "archives.*tile 39 2021 MSY" + ) +}) + +test_that("getClimateTiles extracts nothing when the download stays bad", { + skip_if_not_installed("withr") + withr::local_options(reproducible.useCache = FALSE) + src <- withr::local_tempdir() + dir.create(file.path(src, "2011")) + writeLines("1", file.path(src, "2011", "MAT.asc")) + fixture <- file.path(withr::local_tempdir(), "39_MSY_2011.zip") + withr::with_dir(src, utils::zip(fixture, file.path("2011", "MAT.asc"), flags = "-q")) + testthat::local_mocked_bindings(.downloadArchive = function(url, destfile) { + writeLines("corrupt", destfile) + invisible(destfile) + }) + urls <- list( + "39" = data.frame( + url = paste0("https://h/c:b/", testIndexKeys[["r1"]]), + md5 = unname(tools::md5sum(fixture)) + ) + ) + d <- withr::local_tempdir() + expect_error(getClimateTiles(39, urls, d, needVars = "historical_MAT"), "doesn't match") + expect_identical(list.files(d, recursive = TRUE, all.files = TRUE), character(0)) +}) + +test_that("getClimateTiles extracts only the requested variables", { + skip_if_not_installed("withr") + withr::local_options(reproducible.useCache = FALSE) + src <- withr::local_tempdir() + dir.create(file.path(src, "2011")) + for (v in c("MAT.asc", "PPT01.asc")) { + writeLines("1", file.path(src, "2011", v)) + } + fixture <- file.path(withr::local_tempdir(), "39_MSY_2011.zip") + withr::with_dir( + src, + utils::zip(fixture, file.path("2011", c("MAT.asc", "PPT01.asc")), flags = "-q") + ) + testthat::local_mocked_bindings(.downloadArchive = function(url, destfile) { + file.copy(fixture, destfile, overwrite = TRUE) + invisible(destfile) + }) + urls <- list( + "39" = data.frame( + url = paste0("https://h/c:b/", testIndexKeys[["r1"]]), + md5 = unname(tools::md5sum(fixture)) + ) + ) + d <- withr::local_tempdir() + getClimateTiles(39, urls, d, needVars = "historical_MAT") + expect_true(file.exists(file.path(d, "39", "2011", "MAT.asc"))) + expect_false(file.exists(file.path(d, "39", "2011", "PPT01.asc"))) +}) + +test_that("one zip downloads from the bucket and matches the shipped index", { + skip_on_cran() + skip_if_not_installed("withr") + skip_if_offline("object-arbutus.alliancecan.ca") + db <- sqlite_connect_db(ClimateNA_tiles_sqlite(), readonly = TRUE) + row <- DBI::dbGetQuery( + db, + "SELECT key, md5 FROM archives WHERE type = 'historical_normals' ORDER BY size LIMIT 1" + ) + DBI::dbDisconnect(db) + p <- .fetchArchive(paste0(.indexBaseUrl(), "/", row$key), row$md5, withr::local_tempdir()) + expect_identical(unname(tools::md5sum(p)), row$md5) +}) + +## a DNS or connection failure (curl error, no HTTP status) is retried, not only HTTP errors +test_that("archive downloads retry network failures", { + p <- .archiveRequest("https://h/c:b/climateData/r1/historical/MSY/39_MSY_2011.zip")$policies + expect_true(p$retry_on_failure) + expect_identical(p$retry_max_tries, 3) +}) diff --git a/tests/testthat/test-makeClimateDEM.R b/tests/testthat/test-makeClimateDEM.R index 5705587..7bf7a4b 100644 --- a/tests/testthat/test-makeClimateDEM.R +++ b/tests/testthat/test-makeClimateDEM.R @@ -1,9 +1,45 @@ +## makeClimateDEM() starts from a GTOPO30 mosaic of Canada (gtopo30Canada.zip, one GeoTIFF) in the +## bucket, checked against its MD5 (.gtopo30Canada()) +test_that("the GTOPO30 mosaic is unzipped from the checked download", { + skip_if_not_installed("withr") + src <- withr::local_tempdir() + r <- terra::rast(nrows = 2, ncols = 2, vals = 1:4) + terra::writeRaster(r, file.path(src, "gtopo30Canada.tif")) + fixture <- file.path(withr::local_tempdir(), "gtopo30Canada.zip") + withr::with_dir(src, utils::zip(fixture, "gtopo30Canada.tif", flags = "-q")) + testthat::local_mocked_bindings(.downloadArchive = function(url, destfile) { + file.copy(fixture, destfile, overwrite = TRUE) + invisible(destfile) + }) + d <- withr::local_tempdir() + dem <- .gtopo30Canada( + d, + url = "https://h/c:b/climateData/dem/gtopo30Canada.zip", + md5 = unname(tools::md5sum(fixture)) + ) + expect_s4_class(dem, "SpatRaster") + expect_identical(as.vector(terra::values(dem)), 1:4) +}) + +test_that("the GTOPO30 mosaic downloads from the bucket", { + skip_on_cran() + skip_on_ci() ## an 89 MB download + skip_if_not_installed("withr") + skip_if_offline("object-arbutus.alliancecan.ca") + d <- withr::local_tempdir() + dem <- .gtopo30Canada(d) + expect_s4_class(dem, "SpatRaster") + expect_identical( + unname(tools::md5sum(file.path(d, "gtopo30Canada.zip"))), + "8adc54c83fcca0301a9a2f716237d077" + ) +}) + test_that("makeClimateDEM works", { skip_on_cran() - skip_on_ci() ## needs to authorize googledrive package for downloads + skip_on_ci() ## large downloads skip_if_not(identical(tolower(.Platform$OS.type), "windows")) skip_if_not_installed("geodata") - skip_if_not_installed("googledrive") skip_if_not_installed("withr") dPath <- withr::local_tempdir("test_makeClimateDEM_") diff --git a/tests/testthat/test-pipelineCatalogue.R b/tests/testthat/test-pipelineCatalogue.R new file mode 100644 index 0000000..56ecf6b --- /dev/null +++ b/tests/testthat/test-pipelineCatalogue.R @@ -0,0 +1,93 @@ +## pipeline_catalogue() (data-raw/pipeline/R/catalogue.R) refreshes the bucket's browsable +## catalogue after uploads. It rewrites every page in the bucket, the pages of other people's +## data too, so it must pass the bucket's live settings and never run in a dry run. +catalogueEnv <- function() { + f <- test_path("..", "..", "data-raw", "pipeline", "R", "catalogue.R") + skip_if_not(file.exists(f), "data-raw/pipeline not available") + e <- new.env() + sys.source(f, envir = e) + e +} + +catalogueBucket <- list( + endpoint = "https://object-arbutus.alliancecan.ca", + container = "529feda02d404836b0e91b1d360b4df0:predictiveecology", + prefix = "climateData" +) +catalogueSettings <- list( + heading = NULL, + disclaimer_html = "", + host_note = "Hosted on an S3-compatible object store." +) + +test_that("the catalogue isn't touched in a dry run", { + e <- catalogueEnv() + called <- FALSE + expect_null(e$pipeline_catalogue( + "idx", + catalogueBucket, + "arbutus", + catalogueSettings, + TRUE, + generate = \(...) called <<- TRUE + )) + expect_false(called) +}) + +test_that("the catalogue is generated with the bucket and the live settings", { + e <- catalogueEnv() + args <- NULL + out <- e$pipeline_catalogue( + "idx", + catalogueBucket, + "arbutus", + catalogueSettings, + FALSE, + generate = function(...) { + args <<- list(...) + c(a = "", b = "") + } + ) + expect_identical(args$container, catalogueBucket$container) + expect_identical(args$endpoint, catalogueBucket$endpoint) + expect_identical(args$remote, "arbutus") + expect_true("heading" %in% names(args)) + expect_null(args$heading) + expect_identical(args$disclaimerHtml, "") + expect_identical(args$hostNote, "Hosted on an S3-compatible object store.") + expect_identical(out$pages, 2L) +}) + +test_that("the catalogue leaves out the folders the bucket's other users exclude", { + e <- catalogueEnv() + args <- NULL + e$pipeline_catalogue( + "idx", + catalogueBucket, + "arbutus", + c(catalogueSettings, list(exclude = "wbi")), + FALSE, + generate = function(...) { + args <<- list(...) + character(0) + } + ) + expect_identical(args$exclude, "wbi") +}) + +test_that("the catalogue excludes nothing when release.yml lists no folders", { + e <- catalogueEnv() + args <- NULL + e$pipeline_catalogue( + "idx", + catalogueBucket, + "arbutus", + catalogueSettings, + FALSE, + generate = function(...) { + args <<- list(...) + character(0) + } + ) + expect_identical(args$exclude, character(0)) +}) diff --git a/tests/testthat/test-pipelineDem.R b/tests/testthat/test-pipelineDem.R new file mode 100644 index 0000000..e510148 --- /dev/null +++ b/tests/testthat/test-pipelineDem.R @@ -0,0 +1,206 @@ +## DEM tiles for ClimateNA (R/pipelineDem.R): lon/lat, square cells at the release's resolution, +## and Windows (CRLF) line ends, which ClimateNA needs. +writeAsc <- function(f, header, rows = "1 2", eol = "\r\n") { + writeBin(charToRaw(paste0(paste(c(header, rows), collapse = eol), eol)), f) + f +} + +ascHeader <- function(cellsize = 0.05, x = -96.8, y = 58.25, cellLines = NULL) { + c( + "ncols 2", + "nrows 1", + sprintf("xllcorner %.12f", x), + sprintf("yllcorner %.12f", y), + cellLines %||% sprintf("cellsize %.12f", cellsize), + "NODATA_value nan" + ) +} + +test_that("DEM resolutions are read from the release's dem_resolution", { + expect_equal(.demResolutionDeg("3arcmin"), 0.05) + expect_equal(.demResolutionDeg("1arcmin"), 1 / 60) + expect_error(.demResolutionDeg("3arcsec"), "3arcsec") +}) + +test_that("a lon/lat DEM tile with CRLF line ends at the release's cell size passes", { + skip_if_not_installed("withr") + f <- writeAsc(withr::local_tempfile(fileext = ".asc"), ascHeader()) + expect_no_error(.demCheck(f, 0.05)) +}) + +test_that("a DEM tile with LF line ends stops, naming the file", { + skip_if_not_installed("withr") + f <- writeAsc(withr::local_tempfile(fileext = ".asc"), ascHeader(), eol = "\n") + expect_error(.demCheck(f, 0.05), basename(f), fixed = TRUE) + expect_error(.demCheck(f, 0.05), "CRLF") +}) + +test_that("a DEM tile at another resolution stops", { + skip_if_not_installed("withr") + f <- writeAsc(withr::local_tempfile(fileext = ".asc"), ascHeader(cellsize = 1 / 60)) + expect_error(.demCheck(f, 0.05), "cell size") +}) + +test_that("a DEM tile with cells that aren't square stops", { + skip_if_not_installed("withr") + f <- writeAsc( + withr::local_tempfile(fileext = ".asc"), + ascHeader(cellLines = c("dx 0.05", "dy 0.04")) + ) + expect_error(.demCheck(f, 0.05), "square") +}) + +test_that("a DEM tile whose header lacks a line stops, naming it", { + skip_if_not_installed("withr") + f <- writeAsc(withr::local_tempfile(fileext = ".asc"), ascHeader()[-1], rows = c("1 2", "3 4")) + expect_error(.demCheck(f, 0.05), "ncols") + f <- writeAsc(withr::local_tempfile(fileext = ".asc"), ascHeader()[-3], rows = c("1 2", "3 4")) + expect_error(.demCheck(f, 0.05), "xllcorner") +}) + +test_that("a projected DEM tile stops", { + skip_if_not_installed("withr") + f <- writeAsc(withr::local_tempfile(fileext = ".asc"), ascHeader(x = 500000, y = 6e6)) + expect_error(.demCheck(f, 0.05), "lon/lat") +}) + +test_that("rewrite_asc() writes CRLF line ends on every platform", { + skip_if_not_installed("withr") + f <- writeAsc(withr::local_tempfile(fileext = ".asc"), ascHeader(), eol = "\n") + rewrite_asc(f) + b <- readBin(f, "raw", file.size(f)) + lf <- which(b == as.raw(10)) + expect_length(lf, 7) + expect_true(all(b[lf - 1] == as.raw(13))) + expect_no_error(.demCheck(f, 0.05)) +}) + +## The tile grid (inst/extdata/tiles.gpkg): a 10 x 10 grid over the boundary's bounding box, holes +## filled, keeping the cells that intersect it, numbered in grid order. An L-shaped "country" whose +## upper-right notch starts at 5.5 drops the 16 cells wholly inside the notch; a hole covering four +## whole cells drops none of them. +lShape <- function(hole = FALSE) { + outer <- rbind(c(0, 0), c(10, 0), c(10, 5.5), c(5.5, 5.5), c(5.5, 10), c(0, 10), c(0, 0)) + rings <- list(outer) + if (hole) { + rings <- c(rings, list(rbind(c(1.5, 1.5), c(1.5, 4.5), c(4.5, 4.5), c(4.5, 1.5), c(1.5, 1.5)))) + } + sf::st_sf(geom = sf::st_sfc(sf::st_polygon(rings), crs = 4326)) +} + +test_that("the tile grid keeps the cells that intersect the boundary, numbered in grid order", { + g <- .tileGrid(lShape()) + expect_named(g, c("id", "geom")) + expect_identical(g$id, 1:84) + first <- sf::st_bbox(g[1, ]) + expect_equal(unname(as.vector(first)), c(0, 0, 1, 1)) + centres <- sf::st_coordinates(sf::st_centroid(sf::st_geometry(g))) + expect_false(any(centres[, "X"] > 6 & centres[, "Y"] > 6)) +}) + +test_that("the tile grid fills holes, as data-raw/02 did", { + expect_identical(nrow(.tileGrid(lShape(hole = TRUE))), 84L) +}) + +test_that("tile grids compare equal only with the same ids and polygons", { + a <- .tileGrid(lShape()) + expect_true(.sameTileGrid(a, a)) + shifted <- a + sf::st_geometry(shifted) <- sf::st_geometry(a) + c(0.01, 0) + sf::st_crs(shifted) <- 4326 + expect_false(.sameTileGrid(a, shifted)) + renumbered <- a + renumbered$id <- rev(a$id) + expect_false(.sameTileGrid(a, renumbered)) +}) + +## DEM tiles from the GTOPO30 mosaic: resampled to the release's resolution, masked to the boundary, +## cut by the tile polygons into can_dem_.asc (CRLF). A tile with no DEM cell gets no file, as +## tile 53 at 3 arcmin. +demInput <- function() { + r <- terra::rast( + nrows = 40, + ncols = 80, + xmin = 0, + xmax = 2, + ymin = 0, + ymax = 1, + crs = "EPSG:4326" + ) + terra::values(r) <- seq_len(terra::ncell(r)) + r +} +twoTiles <- function() { + sq <- function(x, y) { + sf::st_polygon(list(rbind(c(x, y), c(x + 1, y), c(x + 1, y + 1), c(x, y + 1), c(x, y)))) + } + sf::st_sf(id = 1:2, geom = sf::st_sfc(sq(0, 0), sq(5, 5), crs = 4326)) +} +box <- function() { + sf::st_sf( + geom = sf::st_sfc( + sf::st_polygon(list(rbind(c(0, 0), c(2, 0), c(2, 1), c(0, 1), c(0, 0)))), + crs = 4326 + ) + ) +} + +test_that("DEM tiles are cut by tile id, at the release's resolution, with CRLF line ends", { + skip_if_not_installed("withr") + d <- withr::local_tempdir() + f <- .buildDemTiles(demInput(), box(), twoTiles(), 0.1, d) + expect_identical(basename(f), "can_dem_1.asc") + expect_no_error(.demCheck(f, 0.1)) + r <- terra::rast(f) + expect_equal(c(terra::nrow(r), terra::ncol(r)), c(10, 10)) + expect_identical(sum(!is.na(terra::values(r))), 100L) + expect_false(file.exists(file.path(d, "can_dem_2.asc"))) +}) + +## GDAL (3.8) writes .asc rows that start with "nan" and then can't read them back; the DEM tiles +## the releases use start every data row with a space, which GDAL and ClimateNA both read +test_that("DEM tiles whose rows start with a missing cell read back", { + skip_if_not_installed("withr") + dem <- demInput() + v <- terra::values(dem, mat = FALSE) + xy <- terra::xyFromCell(dem, seq_along(v)) + v[xy[, 1] < 0.1 & xy[, 2] > 0.8] <- NA ## the first data row starts with a missing cell + terra::values(dem) <- v + f <- .buildDemTiles(dem, box(), twoTiles(), 0.1, withr::local_tempdir()) + rows <- readLines(f)[-(1:6)] + expect_true(all(startsWith(rows, " "))) + expect_true(any(startsWith(rows, " nan"))) + r <- terra::values(terra::rast(f), mat = FALSE) + expect_gt(sum(is.na(r)), 0) + expect_gt(sum(!is.na(r)), 0) +}) + +test_that("DEM tiles need tile ids in row order", { + skip_if_not_installed("withr") + tiles <- twoTiles() + tiles$id <- 2:1 + expect_error(.buildDemTiles(demInput(), box(), tiles, 0.1, withr::local_tempdir()), "row order") +}) + +## the file names come from terra::makeTiles()'s numbering: a DEM tile must lie in its tile's +## polygon, or a release's tile ids would point at another area's data +test_that("a DEM tile outside its tile's polygon stops, naming the file", { + skip_if_not_installed("withr") + d <- withr::local_tempdir() + r <- terra::rast( + nrows = 10, + ncols = 10, + xmin = 5, + xmax = 6, + ymin = 5, + ymax = 6, + crs = "EPSG:4326" + ) + terra::values(r) <- 1 + f <- file.path(d, "can_dem_1.asc") + terra::writeRaster(r, f) + expect_error(.demTilesInPolygons(f, twoTiles()), "can_dem_1[.]asc") + g <- file.path(d, "can_dem_2.asc") + terra::writeRaster(r, g) + expect_no_error(.demTilesInPolygons(g, twoTiles())) +}) diff --git a/tests/testthat/test-pipelineDemTargets.R b/tests/testthat/test-pipelineDemTargets.R new file mode 100644 index 0000000..c3e4268 --- /dev/null +++ b/tests/testthat/test-pipelineDemTargets.R @@ -0,0 +1,92 @@ +## The pipeline's DEM mode (data-raw/pipeline/R/dem.R): with no dem_dir in _local.R, a release +## builds its own DEM tiles from the GTOPO30 mosaic and proves the shipped tile grid; with one, it +## uses that folder as before. +demEnv <- function() { + f <- test_path("..", "..", "data-raw", "pipeline", "R", "dem.R") + skip_if_not(dir.exists(dirname(f)), "data-raw/pipeline not available") + e <- new.env() + sys.source(f, envir = e) + e +} + +## a boundary as pipeline_canada() stores it (a packed SpatVector in an .rds), and a tile grid file +writeBoundary <- function(dir, x) { + f <- file.path(dir, "boundary.rds") + saveRDS(terra::wrap(terra::vect(x)), f) + f +} +writeGrid <- function(dir, grid) { + f <- file.path(dir, "tiles.gpkg") + sf::st_write(grid, f, layer = "tiles", quiet = TRUE, delete_dsn = TRUE) + f +} +square <- function(x0, y0, x1, y1) { + sf::st_polygon(list(rbind(c(x0, y0), c(x1, y0), c(x1, y1), c(x0, y1), c(x0, y0)))) +} + +## the release's own bucket, not the one the checkout's shipped index names +test_that("the pipeline fetches GTOPO30 from the release's bucket", { + skip_if_not_installed("withr") + e <- demEnv() + sys.source(test_path("..", "..", "data-raw", "pipeline", "R", "upload_s3.R"), envir = e) + got <- NULL + e$.gtopo30Canada <- function(destinationPath, url, ...) { + got <<- url + invisible(destinationPath) + } + bucket <- list(endpoint = "https://e", container = "p:b", prefix = "pre") + e$pipeline_gtopo30(withr::local_tempdir(), bucket) + expect_identical(got, "https://e/p:b/pre/dem/gtopo30Canada.zip") +}) + +test_that("the DEM tiles are built when _local.R names no DEM folder", { + e <- demEnv() + expect_true(e$pipeline_dem_mode(list(out_root = "x"))) + expect_false(e$pipeline_dem_mode(list(dem_dir = "/data/dem"))) +}) + +test_that("the tile grid check passes for the grid its rule gives, and stops otherwise", { + skip_if_not_installed("withr") + e <- demEnv() + d <- withr::local_tempdir() + land <- sf::st_sf(geom = sf::st_sfc(square(0, 0, 10, 10), crs = 4326)) + b <- writeBoundary(d, land) + good <- writeGrid(withr::local_tempdir(), .tileGrid(land)) + expect_identical(e$pipeline_tile_grid_check(b, good), good) + moved <- .tileGrid(land) + sf::st_geometry(moved) <- sf::st_geometry(moved) + c(0.5, 0) + sf::st_crs(moved) <- 4326 + bad <- writeGrid(withr::local_tempdir(), moved) + expect_error(e$pipeline_tile_grid_check(b, bad), "tile grid") +}) + +test_that("the DEM tiles go to /dem, replacing any earlier ones", { + skip_if_not_installed("withr") + e <- demEnv() + out <- withr::local_tempdir() + r <- terra::rast( + nrows = 40, + ncols = 80, + xmin = 0, + xmax = 2, + ymin = 0, + ymax = 1, + crs = "EPSG:4326" + ) + terra::values(r) <- seq_len(terra::ncell(r)) + tif <- file.path(withr::local_tempdir(), "gtopo30Canada.tif") + terra::writeRaster(r, tif) + b <- writeBoundary( + withr::local_tempdir(), + sf::st_sf(geom = sf::st_sfc(square(0, 0, 2, 1), crs = 4326)) + ) + grid <- writeGrid( + withr::local_tempdir(), + sf::st_sf(id = 1:2, geom = sf::st_sfc(square(0, 0, 1, 1), square(5, 5, 6, 6), crs = 4326)) + ) + dir.create(file.path(out, "dem")) + writeLines("old", file.path(out, "dem", "can_dem_2.asc")) + f <- e$pipeline_build_dem(tif, b, "6arcmin", out, grid) + expect_identical(f, file.path(out, "dem", "can_dem_1.asc")) + expect_false(file.exists(file.path(out, "dem", "can_dem_2.asc"))) +}) diff --git a/tests/testthat/test-pipelineIndex.R b/tests/testthat/test-pipelineIndex.R new file mode 100644 index 0000000..118bac8 --- /dev/null +++ b/tests/testthat/test-pipelineIndex.R @@ -0,0 +1,110 @@ +## build_index() (data-raw/pipeline/R/index.R): the release's tile index, from the uploads. Each +## row names its archive by object key; the release table holds the bucket's base URL. + +## A one-batch release (tile 39, 2011-2012) with real zips for every subset and a manifest; the +## index built from `uploads`. Returns the index path. +indexFixture <- function(uploads, env = parent.frame()) { + pipe <- test_path("..", "..", "data-raw", "pipeline", "R") + skip_if_not(dir.exists(pipe), "data-raw/pipeline not available") + skip_if_not_installed("withr") + e <- new.env() + for (f in c("index.R", "zips.R")) { + sys.source(file.path(pipe, f), envir = e) + } + outRoot <- withr::local_tempdir(.local_envir = env) + spec <- .batchSpecs("historical", tiles = 39L, years = 2011:2012)[[1]] + folders <- .periodFolder(spec$type, spec$periods, spec$msy, spec$gcm, spec$ssp) + + ## a zip per subset, each holding one file per year + src <- withr::local_tempdir(.local_envir = env) + for (f in folders) { + dir.create(file.path(src, f)) + writeLines("1", file.path(src, f, "MAT.asc")) + } + for (subset in e$pipeline_subsets(spec$type)) { + zip <- e$pipeline_zip_path(outRoot, spec, subset) + dir.create(dirname(zip), recursive = TRUE, showWarnings = FALSE) + withr::with_dir(src, utils::zip(zip, file.path(folders, "MAT.asc"), flags = "-q")) + } + + dir.create(file.path(outRoot, "raw")) + manifest <- file.path(outRoot, "raw", paste0(spec$id, ".tsv")) + utils::write.table( + data.frame( + folder = folders, + n_files = 1L, + climatena_version = "7.70", + dem_hash = "h", + time = "1700000000" + ), + manifest, + sep = "\t", + quote = FALSE, + row.names = FALSE + ) + fill <- as.data.frame(stats::setNames( + replicate(length(.filledCellsColumns), character(0), simplify = FALSE), + .filledCellsColumns + )) + e$build_index( + uploads, + list(spec), + manifest, + outRoot, + "r1", + "7.70", + "3arcmin", + fill, + "https://h/c:b" + ) +} + +## one upload, for the MSY zip +indexUploads <- data.frame( + subset = "MSY", + key = "climateData/r1/historical/MSY/39_MSY_2010.zip", + md5 = "0123456789abcdef0123456789abcdef", + zipfile = "historical/MSY/39_MSY_2010.zip", + uploaded = 1.7e9, + source = "uploaded" +) + +test_that("build_index writes object keys and the bucket's base URL", { + path <- indexFixture(indexUploads) + db <- DBI::dbConnect(RSQLite::SQLite(), path) + withr::defer(DBI::dbDisconnect(db)) + expect_identical(DBI::dbGetQuery(db, "SELECT base_url FROM release")$base_url, "https://h/c:b") + hist <- DBI::dbGetQuery(db, "SELECT key, year FROM historical ORDER BY year") + expect_identical(unique(hist$key), indexUploads$key) + expect_identical(hist$year, 2011:2012) + a <- DBI::dbGetQuery(db, "SELECT key, md5, n_files FROM archives") + expect_identical(a$key, indexUploads$key) + expect_identical(a$md5, indexUploads$md5) + expect_identical(a$n_files, 2L) +}) + +## each row refers to its archive by id; the zip's time and upload time are the archive's, and the +## view gives them per row as the tile tables did +test_that("build_index refers each row to its archive by id", { + path <- indexFixture(indexUploads) + db <- DBI::dbConnect(RSQLite::SQLite(), path) + withr::defer(DBI::dbDisconnect(db)) + a <- DBI::dbGetQuery(db, "SELECT id, zipfile, archived, verified FROM archives") + base <- DBI::dbGetQuery(db, "SELECT archive FROM tiles_historical") + expect_identical(unique(base$archive), a$id) + zip <- file.path(dirname(path), "zips", a$zipfile) + expect_equal(a$archived, as.numeric(file.mtime(zip))) + v <- DBI::dbGetQuery(db, "SELECT zipfile, archived, uploaded FROM historical") + expect_identical(unique(v$zipfile), indexUploads$zipfile) + expect_equal(unique(v$archived), a$archived) + expect_equal(unique(v$uploaded), indexUploads$uploaded) +}) + +test_that("an upload missing from the uploads leaves its zip out of the index", { + path <- indexFixture(indexUploads) + db <- DBI::dbConnect(RSQLite::SQLite(), path) + withr::defer(DBI::dbDisconnect(db)) + ## the M, Y and S zips were cut but not uploaded + expect_identical(DBI::dbGetQuery(db, "SELECT DISTINCT msy FROM historical")$msy, "MSY") + expect_identical(nrow(DBI::dbGetQuery(db, "SELECT * FROM archives")), 1L) +}) diff --git a/tests/testthat/test-pipelineLookup.R b/tests/testthat/test-pipelineLookup.R index 07a5699..865e26f 100644 --- a/tests/testthat/test-pipelineLookup.R +++ b/tests/testthat/test-pipelineLookup.R @@ -2,21 +2,82 @@ ## holds. The lookup's value must not change with them, or every upload branch reruns (24,518 ## for release cna-v7.70-3arcmin). The pipeline code is in data-raw/, which R CMD check omits. test_that("the previous-release lookup's value doesn't change when scenarios are added", { - f <- test_path("..", "..", "data-raw", "pipeline", "R", "upload_drive.R") + f <- test_path("..", "..", "data-raw", "pipeline", "R", "upload_s3.R") skip_if_not(file.exists(f), "data-raw/pipeline not available") skip_if_not_installed("withr") e <- new.env() sys.source(f, envir = e) - e$pipeline_previous_archives <- function(index) { - data.frame(zipfile = c("a.zip", "b.zip"), gid = c("ga", "gb"), md5 = c("ma", "mb")) + e$pipeline_previous_archives <- function(index, baseUrl) { + data.frame(zipfile = c("a.zip", "b.zip"), key = c("ka", "kb"), md5 = c("ma", "mb")) } e$pipeline_zip_relpaths <- function(spec) spec$zips out <- withr::local_tempdir() - one <- e$pipeline_previous_lookup("idx", list(list(zips = "a.zip")), out) - two <- e$pipeline_previous_lookup("idx", list(list(zips = "a.zip"), list(zips = "b.zip")), out) + one <- e$pipeline_previous_lookup("idx", list(list(zips = "a.zip")), out, "https://h/p:b") + two <- e$pipeline_previous_lookup( + "idx", + list(list(zips = "a.zip"), list(zips = "b.zip")), + out, + "https://h/p:b" + ) expect_identical(one, two) rows <- e$pipeline_previous_rows(two, list(zips = "b.zip")) - expect_identical(rows$gid, "gb") + expect_identical(rows$key, "kb") +}) + +## Reuse needs the earlier release's objects in the same bucket: a Drive index (no base_url) or +## another bucket's index gives nothing to reuse. +test_that("a previous index from another store or bucket gives no reuse", { + f <- test_path("..", "..", "data-raw", "pipeline", "R", "upload_s3.R") + skip_if_not(file.exists(f), "data-raw/pipeline not available") + skip_if_not_installed("withr") + e <- new.env() + sys.source(f, envir = e) + d <- withr::local_tempdir() + row <- data.frame( + key = "climateData/r0/a.zip", + type = "historical", + zipfile = "a.zip", + md5 = "ma", + n_files = 1L, + size = 1, + verified = 1 + ) + index <- function(name, baseUrl) { + p <- file.path(d, name) + db <- DBI::dbConnect(RSQLite::SQLite(), p) + .archivesCreate(db) + .archivesUpsert(db, row) + .releaseCreate(db) + .releaseWrite( + db, + data.frame( + release_id = "r0", + climatena_version = "7.70", + dem_resolution = "3arcmin", + base_url = baseUrl, + created = 1 + ) + ) + DBI::dbDisconnect(db) + p + } + + same <- e$pipeline_previous_archives(index("same.sqlite", "https://h/p:b"), "https://h/p:b") + expect_identical(same$key, "climateData/r0/a.zip") + other <- e$pipeline_previous_archives(index("other.sqlite", "https://o/x:y"), "https://h/p:b") + expect_identical(nrow(other), 0L) + + ## a Drive index: archives keyed by gid, a release table without base_url + drive <- file.path(d, "drive.sqlite") + db <- DBI::dbConnect(RSQLite::SQLite(), drive) + DBI::dbExecute(db, "CREATE TABLE archives (gid TEXT, type TEXT, zipfile TEXT, md5 TEXT)") + DBI::dbExecute(db, "INSERT INTO archives VALUES ('g', 'historical', 'a.zip', 'ma')") + DBI::dbExecute(db, "CREATE TABLE release (release_id TEXT, created REAL)") + DBI::dbExecute(db, "INSERT INTO release VALUES ('cna-v7.70-3arcmin', 1)") + DBI::dbDisconnect(db) + expect_identical(nrow(e$pipeline_previous_archives(drive, "https://h/p:b")), 0L) + + expect_identical(nrow(e$pipeline_previous_archives(file.path(d, "none.sqlite"), "x")), 0L) }) diff --git a/tests/testthat/test-pipelinePaths.R b/tests/testthat/test-pipelinePaths.R new file mode 100644 index 0000000..be90be6 --- /dev/null +++ b/tests/testthat/test-pipelinePaths.R @@ -0,0 +1,23 @@ +## The pipeline passes paths from _local.R to zip, docker and rclone through the shell (system2()), +## unquoted (data-raw/pipeline/R/paths.R): a path with a space or a quote would break those calls +## part-way through a run, so it stops the run before anything starts. +pathsEnv <- function() { + d <- test_path("..", "..", "data-raw", "pipeline", "R") + skip_if_not(dir.exists(d), "data-raw/pipeline not available") + e <- new.env() + sys.source(file.path(d, "paths.R"), envir = e) + e +} + +test_that("a _local.R path with a space or quote stops the pipeline, naming the setting", { + e <- pathsEnv() + expect_error(e$pipeline_check_paths(list(out_root = "/data/my out", dem_dir = "/d")), "out_root") + expect_error(e$pipeline_check_paths(list(work_dir = "/tmp/it's")), "work_dir") + expect_no_error(e$pipeline_check_paths(list(out_root = "/data/out", climatena_dir = "/c"))) +}) + +test_that("_targets.R checks the paths in _local.R", { + f <- test_path("..", "..", "data-raw", "pipeline", "_targets.R") + skip_if_not(file.exists(f), "data-raw/pipeline not available") + expect_match(paste(readLines(f), collapse = "\n"), "\npipeline_check_paths\\(local\\)\n") +}) diff --git a/tests/testthat/test-pipelineReport.R b/tests/testthat/test-pipelineReport.R new file mode 100644 index 0000000..c0e43f4 --- /dev/null +++ b/tests/testthat/test-pipelineReport.R @@ -0,0 +1,53 @@ +## What report.csv adds beyond errors and missing zips (data-raw/pipeline/R/index.R): release.yml's +## years, periods, GCMs and SSPs against available(), the package's list of what users can request +## (they were the old scripts' only source; 2.2.3 shipped with a mismatch). Errors are reported +## only for targets the pipeline still has. +reportEnv <- function() { + pipe <- test_path("..", "..", "data-raw", "pipeline", "R") + skip_if_not(dir.exists(pipe), "data-raw/pipeline not available") + e <- new.env() + for (f in c("index.R", "zips.R")) { + sys.source(file.path(pipe, f), envir = e) + } + e$pipeline_load <- function() invisible(TRUE) ## the tests already have the package + e +} + +test_that("release settings that differ from available() become settings rows", { + e <- reportEnv() + skip_if_not_installed("yaml") + cfg <- yaml::read_yaml(test_path("..", "..", "data-raw", "pipeline", "release.yml")) + expect_identical(nrow(e$pipeline_settings_vs_available(cfg)), 0L) + + cfg$historical_years[[2]] <- 2024 + cfg$gcms <- list("CanESM5") + out <- e$pipeline_settings_vs_available(cfg) + expect_identical(out$kind, rep("settings", 3)) + expect_match(out$message, "historical years", all = FALSE) + expect_identical(sum(grepl("gcms", out$message)), 2L) ## future and future_normals +}) + +## a branch the pipeline no longer has (e.g. a tile dropped from the release) keeps its last error +## in the store until tar_prune(): the report lists only branches their pattern still has +test_that("the report leaves out branches the pipeline no longer has", { + e <- reportEnv() + meta <- data.frame( + name = c("batch", "batch_a1", "batch_53", "index"), + type = c("pattern", "branch", "branch", "stem"), + error = c(NA, NA, "no DEM tile 53", NA) + ) + meta$children <- list("batch_a1", NULL, NULL, NULL) + expect_identical(e$pipeline_current_meta(meta)$name, c("batch", "batch_a1", "index")) +}) + +## zip_batch() stages only the allowed variables, so a published zip can't hold another file: the +## pipeline has no step that lists each zip again looking for one +test_that("the pipeline has no zip notes step", { + pipe <- test_path("..", "..", "data-raw", "pipeline") + skip_if_not(dir.exists(pipe), "data-raw/pipeline not available") + code <- unlist(lapply( + c(file.path(pipe, "_targets.R"), dir(file.path(pipe, "R"), full.names = TRUE)), + readLines + )) + expect_false(any(grepl("zip_notes|notes_all", code))) +}) diff --git a/tests/testthat/test-pipelineSpecs.R b/tests/testthat/test-pipelineSpecs.R index 6796d7f..6d1ad4d 100644 --- a/tests/testthat/test-pipelineSpecs.R +++ b/tests/testthat/test-pipelineSpecs.R @@ -18,15 +18,42 @@ writeDem <- function(dir, tile, values) { f } +## a DEM tile as ClimateNA needs it: 3 arcmin lon/lat cells, CRLF line ends +writeDem3 <- function(dir, tile) { + r <- terra::rast( + nrows = 2, + ncols = 2, + xmin = 0, + xmax = 0.1, + ymin = 0, + ymax = 0.1, + crs = "EPSG:4326" + ) + terra::values(r) <- 1:4 + f <- file.path(dir, paste0("can_dem_", tile, ".asc")) + terra::writeRaster(r, f, NAflag = -9999, overwrite = TRUE) + rewrite_asc(f) + f +} + test_that("pipeline_dem_files names one file per tile and stops on a missing one", { e <- pipelineEnv() d <- withr::local_tempdir() - writeDem(d, 1, 1:4) - writeDem(d, 2, 1:4) - f <- e$pipeline_dem_files(d, c(1L, 2L)) + writeDem3(d, 1) + writeDem3(d, 2) + f <- e$pipeline_dem_files(d, c(1L, 2L), "3arcmin") expect_named(f, c("1", "2")) expect_true(all(file.exists(f))) - expect_error(e$pipeline_dem_files(d, c(1L, 3L)), "no DEM tile.*3") + expect_error(e$pipeline_dem_files(d, c(1L, 3L), "3arcmin"), "no DEM tile.*3") +}) + +test_that("pipeline_dem_files checks each DEM file against the release's resolution", { + e <- pipelineEnv() + d <- withr::local_tempdir() + writeDem3(d, 1) + expect_error(e$pipeline_dem_files(d, 1L, "1arcmin"), "cell size") + writeDem(d, 2, 1:4) ## LF line ends, as terra writes them on Linux + expect_error(e$pipeline_dem_files(d, 2L, "3arcmin"), "CRLF") }) test_that("pipeline_tile_masks names each tile's mask and land cells by its DEM file", { diff --git a/tests/testthat/test-pipelineTargets.R b/tests/testthat/test-pipelineTargets.R index 4e27819..071e49e 100644 --- a/tests/testthat/test-pipelineTargets.R +++ b/tests/testthat/test-pipelineTargets.R @@ -19,3 +19,32 @@ test_that("tiles re-lists the DEM folder every run, and the DEM-wide targets sto expect_identical(m$error[m$name == n], "stop", label = n) } }) + +## the archives go to the bucket; nothing is uploaded to Drive any more +test_that("the pipeline uploads to the bucket, not to Drive", { + root <- test_path("..", "..") + skip_if_not(file.exists(file.path(root, "data-raw", "pipeline", "_local.R")), "no _local.R") + skip_if_not_installed("targets") + m <- withr::with_dir( + root, + targets::tar_manifest(script = "data-raw/pipeline/_targets.R", fields = c("name", "command")) + ) + expect_contains(m$name, c("bucket", "base_url")) + expect_false(any(c("release_folders", "drive_parent") %in% m$name)) + expect_match(m$command[m$name == "uploads_historical"], "upload_zips\\(.*bucket.*release_id") + expect_match(m$command[m$name == "index"], "base_url") +}) + +## the catalogue is rewritten after the uploads, and its failure lands in that run's report +test_that("the catalogue runs after the uploads and before the report", { + root <- test_path("..", "..") + skip_if_not(file.exists(file.path(root, "data-raw", "pipeline", "_local.R")), "no _local.R") + skip_if_not_installed("targets") + edges <- withr::with_dir( + root, + targets::tar_network(script = "data-raw/pipeline/_targets.R", targets_only = TRUE)$edges + ) + into <- \(to) edges$from[edges$to == to] + expect_contains(into("catalogue"), c("index", "uploads_all", "bucket", "catalogue_settings")) + expect_contains(into("report"), "catalogue") +}) diff --git a/tests/testthat/test-pipelineUpload.R b/tests/testthat/test-pipelineUpload.R index d392a58..fbeccf2 100644 --- a/tests/testthat/test-pipelineUpload.R +++ b/tests/testthat/test-pipelineUpload.R @@ -1,7 +1,7 @@ -## What upload_zips() does with a zip, given the same-named files already in its release folder: -## reuse one with the same MD5; else, when asked (replace_changed in _local.R), replace a -## differing one in place, so its Drive ID (the index's gid) stays the same; else upload a new -## file. +## What upload_zips() does with a zip, given what its key in the bucket already holds: reuse an +## object with the same MD5; else, when asked (replace_changed in _local.R), replace a differing +## one in place; else upload a new object. An object a released index refers to is never +## replaced: installed copies check downloads against its MD5. noFiles <- data.frame(id = character(0), md5 = character(0)) test_that(".uploadAction reuses a same-named file with the same MD5", { @@ -17,7 +17,7 @@ test_that(".uploadAction uploads a new file when none has the name", { test_that(".uploadAction stops on a differing same-named file unless asked to replace it", { expect_error(.uploadAction(data.frame(id = "a", md5 = "x"), "y"), "replace_changed") expect_error( - .uploadAction(data.frame(id = c("a", "b"), md5 = c("x", "z")), "y", gid = "b"), + .uploadAction(data.frame(id = c("a", "b"), md5 = c("x", "z")), "y", key = "b"), "replace_changed" ) }) @@ -34,7 +34,7 @@ test_that(".uploadAction updates the one same-named file in place", { test_that(".uploadAction updates the file the index points to when there are several", { there <- data.frame(id = c("a", "b"), md5 = c("x", "z")) expect_identical( - .uploadAction(there, "y", gid = "b", replace = TRUE), + .uploadAction(there, "y", key = "b", replace = TRUE), list(action = "update", id = "b") ) }) @@ -42,58 +42,222 @@ test_that(".uploadAction updates the file the index points to when there are sev test_that(".uploadAction stops when several same-named files differ and none is the index's", { there <- data.frame(id = c("a", "b"), md5 = c("x", "z")) expect_error(.uploadAction(there, "y"), "a, b") - expect_error(.uploadAction(there, "y", gid = "c"), "a, b") + expect_error(.uploadAction(there, "y", key = "c"), "a, b") }) +test_that(".uploadAction never replaces an object a released index refers to", { + there <- data.frame(id = "k", md5 = "old") + expect_error( + .uploadAction(there, "new", key = "k", replace = TRUE, released = TRUE), + "released index.*new release_id" + ) + ## the same object is still found + expect_identical( + .uploadAction(there, "old", key = "k", released = TRUE), + list(action = "found", id = "k") + ) +}) + +## upload_zips() (data-raw/pipeline/R/upload_s3.R) with its bucket calls replaced: `state` is +## what the zip's key holds (0 or 1 row), `head(url)` what an anonymous HEAD returns, `previous` +## the previous release's rows. Each put and HEAD is recorded in `log`. +s3Bucket <- list(endpoint = "https://h", container = "p:b", prefix = "climateData") +s3Key <- "climateData/r1/historical/MSY/6_MSY_2020.zip" + +s3Env <- function(state = NULL, head = NULL, previous = NULL, log = new.env()) { + f <- test_path("..", "..", "data-raw", "pipeline", "R", "upload_s3.R") + skip_if_not(file.exists(f), "data-raw/pipeline not available") + e <- new.env() + sys.source(f, envir = e) + log$puts <- character(0) + log$heads <- character(0) + e$pipeline_load <- function() invisible(TRUE) + e$pipeline_zip_relpath <- function(spec, subset) "historical/MSY/6_MSY_2020.zip" + e$pipeline_previous_rows <- function(lookup, spec) { + previous %||% data.frame(key = character(0), zipfile = character(0), md5 = character(0)) + } + e$pipeline_s3_state <- function(remote, bucket, key) state %||% noFiles + e$pipeline_s3_put <- function(remote, bucket, key, zip) { + log$puts <- c(log$puts, key) + invisible(key) + } + e$pipeline_s3_head <- function(url) { + log$heads <- c(log$heads, url) + head(url) + } + e +} + +s3Zip <- function(content = "new", env = parent.frame()) { + zip <- file.path(withr::local_tempdir(.local_envir = env), "MSY", "6_MSY_2020.zip") + dir.create(dirname(zip)) + writeLines(content, zip) + zip +} + +md5Of <- function(zip) unname(tools::md5sum(zip)) + +## what a public object holding `zip` answers to an anonymous HEAD +okHead <- function(zip) { + function(url) list(status = 200L, size = file.size(zip), md5 = md5Of(zip), modified = 1.7e9) +} + ## upload_zips() runs on the "uploads" workers, which start without the package, and it calls ## .uploadAction(): it must load the package first, as zip_batch() does. Without it, every ## changed zip's upload failed with "could not find function '.uploadAction'". test_that("upload_zips loads the package on its worker", { - f <- test_path("..", "..", "data-raw", "pipeline", "R", "upload_drive.R") - skip_if_not(file.exists(f), "data-raw/pipeline not available") - e <- new.env() - sys.source(f, envir = e) + e <- s3Env() loaded <- FALSE e$pipeline_load <- function() loaded <<- TRUE - out <- e$upload_zips(character(0), list(), list(), dryRun = FALSE, lookup = NULL) + out <- e$upload_zips(character(0), list(), s3Bucket, "r1", dryRun = FALSE, lookup = NULL) expect_true(loaded) expect_identical(nrow(out), 0L) }) -## a rebuilt zip whose release folder already has a differing file of that name: replaced in -## place (same ID) only with replace_changed; otherwise the upload stops, naming the zip -test_that("upload_zips replaces a changed zip's file only when asked", { - f <- test_path("..", "..", "data-raw", "pipeline", "R", "upload_drive.R") - skip_if_not(file.exists(f), "data-raw/pipeline not available") - e <- new.env() - sys.source(f, envir = e) - rel <- "historical/MSY/6_MSY_2020.zip" - e$pipeline_load <- function() invisible(TRUE) - e$pipeline_zip_relpath <- function(spec, subset) rel - e$pipeline_previous_rows <- function(lookup, spec) { - data.frame(gid = "g1", zipfile = rel, md5 = "old") - } - d <- withr::local_tempdir() - zip <- file.path(d, "MSY", "6_MSY_2020.zip") - dir.create(dirname(zip)) - writeLines("new", zip) - md5 <- unname(tools::md5sum(zip)) - folders <- list(path = file.path(d, "folders.rds")) - saveRDS(c("historical/MSY" = "folder1"), folders$path) - there <- data.frame(name = basename(zip), id = "g1") - there$drive_resource <- list(list(md5Checksum = "old")) - updated <- data.frame(name = basename(zip), id = "g1") - updated$drive_resource <- list(list(md5Checksum = md5, modifiedTime = "2026-11-11T00:00:00Z")) - local_mocked_bindings( - drive_get = function(...) stop("no reusable file"), - drive_ls = function(...) there, - drive_update = function(...) updated, - .package = "googledrive" - ) +test_that("upload_zips uploads a missing object and records its key", { + zip <- s3Zip() + log <- new.env() + e <- s3Env(head = okHead(zip), log = log) + out <- e$upload_zips(zip, list(), s3Bucket, "r1", FALSE, NULL) + expect_identical(out$source, "uploaded") + expect_identical(out$key, s3Key) + expect_identical(out$md5, md5Of(zip)) + expect_identical(out$zipfile, "historical/MSY/6_MSY_2020.zip") + expect_identical(out$uploaded, 1.7e9) + expect_identical(log$puts, s3Key) + expect_identical(log$heads, paste0("https://h/p:b/", s3Key)) +}) - expect_error(e$upload_zips(zip, list(), folders, FALSE, NULL), "6_MSY_2020.zip.*replace_changed") - out <- e$upload_zips(zip, list(), folders, FALSE, NULL, replaceChanged = TRUE) +test_that("upload_zips sends nothing when the object already has the zip's MD5", { + zip <- s3Zip() + log <- new.env() + e <- s3Env(state = data.frame(id = s3Key, md5 = md5Of(zip)), head = okHead(zip), log = log) + out <- e$upload_zips(zip, list(), s3Bucket, "r1", FALSE, NULL) + expect_identical(out$source, "found") + expect_length(log$puts, 0) + ## still checked as a user would see it + expect_identical(log$heads, paste0("https://h/p:b/", s3Key)) +}) + +test_that("upload_zips replaces a changed object only when asked", { + zip <- s3Zip() + log <- new.env() + e <- s3Env(state = data.frame(id = s3Key, md5 = "old"), head = okHead(zip), log = log) + expect_error( + e$upload_zips(zip, list(), s3Bucket, "r1", FALSE, NULL), + "6_MSY_2020.zip.*replace_changed" + ) + expect_length(log$puts, 0) + out <- e$upload_zips(zip, list(), s3Bucket, "r1", FALSE, NULL, replaceChanged = TRUE) expect_identical(out$source, "updated") - expect_identical(out$gid, "g1") - expect_identical(out$md5, md5) + expect_identical(log$puts, s3Key) +}) + +## installed copies of a released index check downloads against its MD5: replacing the object +## would make every one of them fail on that zip +test_that("upload_zips never replaces an object the previous release's index refers to", { + zip <- s3Zip() + log <- new.env() + e <- s3Env( + state = data.frame(id = s3Key, md5 = "old"), + head = okHead(zip), + previous = data.frame(key = s3Key, zipfile = "historical/MSY/6_MSY_2020.zip", md5 = "old"), + log = log + ) + expect_error( + e$upload_zips(zip, list(), s3Bucket, "r1", FALSE, NULL, replaceChanged = TRUE), + "6_MSY_2020.zip.*released index" + ) + expect_length(log$puts, 0) +}) + +test_that("upload_zips reuses an earlier release's identical object", { + zip <- s3Zip() + log <- new.env() + old <- "climateData/r0/historical/MSY/6_MSY_2020.zip" + e <- s3Env( + head = okHead(zip), + previous = data.frame(key = old, zipfile = "historical/MSY/6_MSY_2020.zip", md5 = md5Of(zip)), + log = log + ) + out <- e$upload_zips(zip, list(), s3Bucket, "r1", FALSE, NULL) + expect_identical(out$source, "reused") + expect_identical(out$key, old) + expect_length(log$puts, 0) + expect_identical(log$heads, paste0("https://h/p:b/", old)) +}) + +## an object with the zip's MD5 that isn't public (an upload without the ACL) would otherwise be +## "found" on every rerun and fail the same check: the same bytes go up again, public +test_that("upload_zips uploads a found object again when it isn't public", { + zip <- s3Zip() + log <- new.env() + heads <- 0L + e <- s3Env( + state = data.frame(id = s3Key, md5 = md5Of(zip)), + head = function(url) { + heads <<- heads + 1L + if (heads == 1L) list(status = 403L, size = NA, md5 = NA, modified = NA) else okHead(zip)(url) + }, + log = log + ) + out <- e$upload_zips(zip, list(), s3Bucket, "r1", FALSE, NULL) + expect_identical(log$puts, s3Key) + expect_identical(heads, 2L) + expect_identical(out$source, "uploaded") +}) + +test_that("upload_zips stops when the uploaded object isn't public", { + zip <- s3Zip() + e <- s3Env(head = function(url) list(status = 403L, size = NA, md5 = NA, modified = NA)) + expect_error( + e$upload_zips(zip, list(), s3Bucket, "r1", FALSE, NULL), + "6_MSY_2020.zip.*not public" + ) +}) + +test_that("upload_zips stops when the public object's MD5 or size differs", { + zip <- s3Zip() + e <- s3Env(head = function(url) { + list(status = 200L, size = file.size(zip), md5 = "zzz", modified = 1) + }) + expect_error(e$upload_zips(zip, list(), s3Bucket, "r1", FALSE, NULL), "6_MSY_2020.zip.*MD5") +}) + +test_that("upload_zips in a dry run touches nothing in the bucket", { + zip <- s3Zip() + e <- s3Env() + e$pipeline_s3_state <- function(...) stop("bucket read") + e$pipeline_s3_put <- function(...) stop("bucket write") + e$pipeline_s3_head <- function(...) stop("bucket read") + out <- e$upload_zips(zip, list(), s3Bucket, "r1", TRUE, NULL) + expect_identical(out$source, "dry run") + expect_true(is.na(out$key)) + expect_identical(out$md5, md5Of(zip)) +}) + +test_that("pipeline_s3_key and pipeline_s3_base_url follow the bucket layout", { + e <- s3Env() + b <- list( + endpoint = "https://object-arbutus.alliancecan.ca", + container = "529feda02d404836b0e91b1d360b4df0:predictiveecology", + prefix = "climateData" + ) + expect_identical( + e$pipeline_s3_key(b, "cna-v7.70-3arcmin", "historical/MSY/6_MSY_2020.zip"), + "climateData/cna-v7.70-3arcmin/historical/MSY/6_MSY_2020.zip" + ) + expect_identical( + e$pipeline_s3_base_url(b), + "https://object-arbutus.alliancecan.ca/529feda02d404836b0e91b1d360b4df0:predictiveecology" + ) +}) + +## one DNS timeout failed four upload branches of the 3 arcmin release at once: the anonymous HEAD +## that checks each upload retries network failures, not only HTTP errors +test_that("the anonymous HEAD retries network failures", { + e <- s3Env() + p <- e$pipeline_s3_head_request("https://h/p:b/climateData/r1/x.zip")$policies + expect_true(p$retry_on_failure) + expect_identical(p$retry_max_tries, 3) }) diff --git a/tests/testthat/test-pkgdown.R b/tests/testthat/test-pkgdown.R new file mode 100644 index 0000000..82b0463 --- /dev/null +++ b/tests/testthat/test-pkgdown.R @@ -0,0 +1,15 @@ +## Every topic _pkgdown.yml's reference index lists must exist: pkgdown stops the site build on one +## that matches nothing (a removed export left behind). Runs from a source checkout only. +test_that("the pkgdown reference index lists only documented topics", { + skip_if_not_installed("yaml") + root <- test_path("..", "..") + cfg <- file.path(root, "_pkgdown.yml") + skip_if_not(file.exists(cfg) && dir.exists(file.path(root, "man")), "not a source checkout") + listed <- unlist(lapply(yaml::read_yaml(cfg)$reference, `[[`, "contents")) + listed <- listed[!grepl("(", listed, fixed = TRUE)] ## selectors such as starts_with() + rd <- list.files(file.path(root, "man"), "[.]Rd$", full.names = TRUE) + aliases <- unlist(lapply(rd, function(f) { + sub("^\\\\alias\\{(.*)\\}$", "\\1", grep("^\\\\alias\\{", readLines(f), value = TRUE)) + })) + expect_identical(setdiff(listed, aliases), character(0)) +}) diff --git a/tests/testthat/test-prepClimateLayers.R b/tests/testthat/test-prepClimateLayers.R index d16a5d4..d4566df 100644 --- a/tests/testthat/test-prepClimateLayers.R +++ b/tests/testthat/test-prepClimateLayers.R @@ -1,8 +1,7 @@ test_that("prepClimateLayers works for multiple variable types", { skip_on_cran() - skip_on_ci() ## needs to authorize googledrive package for downloads + skip_on_ci() ## large downloads skip_if_not_installed("archive") - skip_if_not_installed("googledrive") skip_if_not_installed("withr") dPath <- withr::local_tempdir("test_prepClimateLayers_") @@ -179,9 +178,8 @@ test_that("prepClimateLayers works for multiple variable types", { test_that("prepClimateLayers properly handles unordered tileIDs", { skip_on_cran() - skip_on_ci() ## needs to authorize googledrive package for downloads + skip_on_ci() ## large downloads skip_if_not_installed("archive") - skip_if_not_installed("googledrive") skip_if_not_installed("withr") dPath <- withr::local_tempdir("test_prepClimateLayers_") diff --git a/tests/testthat/test-sqliteConcurrency.R b/tests/testthat/test-sqliteConcurrency.R index 81b2935..b467213 100644 --- a/tests/testthat/test-sqliteConcurrency.R +++ b/tests/testthat/test-sqliteConcurrency.R @@ -37,12 +37,12 @@ test_that("a read-only lookup neither writes nor creates tables", { on.exit(unlink(paste0(f, c("", "-wal", "-shm"))), add = TRUE) dbdf <- ClimateNA_sql(f, "historical", readonly = TRUE) - expect_error(DBI::dbExecute(dbdf[["db"]], "DELETE FROM historical"), "readonly") + expect_error(DBI::dbExecute(dbdf[["db"]], "DELETE FROM tiles_historical"), "readonly") DBI::dbDisconnect(dbdf[["db"]]) - ## a table that does not exist is not created on a read path + ## a view that does not exist is not created on a read path con <- DBI::dbConnect(RSQLite::SQLite(), f) - DBI::dbExecute(con, "DROP TABLE IF EXISTS future_normals") + DBI::dbExecute(con, "DROP VIEW IF EXISTS future_normals") DBI::dbDisconnect(con) expect_error(ClimateNA_sql(f, "future_normals", readonly = TRUE)) con <- DBI::dbConnect(RSQLite::SQLite(), f) @@ -54,7 +54,7 @@ test_that("a lookup that fails closes its connection", { f <- dbCopy() on.exit(unlink(paste0(f, c("", "-wal", "-shm"))), add = TRUE) con <- DBI::dbConnect(RSQLite::SQLite(), f) - DBI::dbExecute(con, "DROP TABLE future_normals") + DBI::dbExecute(con, "DROP VIEW future_normals") DBI::dbDisconnect(con) realConnect <- sqlite_connect_db @@ -100,7 +100,7 @@ test_that("writing connections wait for each other's lock; an immutable read doe ## a second writing connection waits for the lock (busy_timeout) instead of failing, then writes t0 <- Sys.time() w <- ClimateNA_sql(f, "historical") - expect_no_error(DBI::dbExecute(w[["db"]], "DELETE FROM historical WHERE rowid = (SELECT max(rowid) FROM historical)")) + expect_no_error(DBI::dbExecute(w[["db"]], "DELETE FROM tiles_historical WHERE id = (SELECT max(id) FROM tiles_historical)")) DBI::dbDisconnect(w[["db"]]) expect_gt(as.numeric(difftime(Sys.time(), t0, units = "secs")), 1) parallel::mccollect(holder) diff --git a/vignettes/climateData.Rmd b/vignettes/climateData.Rmd index b7c3b38..1765198 100644 --- a/vignettes/climateData.Rmd +++ b/vignettes/climateData.Rmd @@ -16,17 +16,16 @@ climateData gives you [ClimateNA](https://climatena.ca/) climate rasters for a s - future years from 2011 to 2100, for several climate models (GCMs) and emissions scenarios (SSPs); - 30-year climate normals, historical and future. -The data are prepared in advance as tiles and stored on Google Drive. climateData downloads only the tiles that cover your study area, then gives you rasters cropped, projected and resampled to match a raster of your own. +The data are prepared in advance as tiles and stored in a public bucket on Arbutus, the Digital Research Alliance of Canada's object storage. climateData downloads only the tiles that cover your study area, checks each download against the checksum in its tile index, then gives you rasters cropped, projected and resampled to match a raster of your own. The `canClimateData` SpaDES module uses the same functions, so what follows also explains the `climateVariables` it takes. ## Before you start -The archives are downloaded with the googledrive package, so you need a Google account: +The archives are public and downloaded over HTTPS, so no account or login is needed: ```{r, eval = FALSE} install.packages("climateData", repos = c("https://predictiveecology.r-universe.dev", getOption("repos"))) -googledrive::drive_auth() # once per session (or cache a token) ``` ## What is available diff --git a/vignettes/maintaining-climate-data.Rmd b/vignettes/maintaining-climate-data.Rmd index e385684..186d5a0 100644 --- a/vignettes/maintaining-climate-data.Rmd +++ b/vignettes/maintaining-climate-data.Rmd @@ -17,8 +17,10 @@ This vignette is for the package's maintainers and developers. It explains how t A *data release* is one full set of ClimateNA outputs, built by one ClimateNA version from DEM tiles at one resolution. It is identified by a `release_id`, such as `cna-v7.70-3arcmin`. A release consists of: -- zip archives on Google Drive: one per tile and decade (historical and future years) or per tile (normals), each in four variable subsets: `MSY` (all), `M` (monthly), `S` (seasonal) and `Y` (annual); -- the tile index, `inst/extdata/ClimateNA_tiles.sqlite`, which maps each tile, year or period and subset to a Drive file ID. +- zip archives in a public bucket on Arbutus, the Digital Research Alliance of Canada's object storage: one per tile and decade (historical and future years) or per tile (normals), each in four variable subsets: `MSY` (all), `M` (monthly), `S` (seasonal) and `Y` (annual); +- the tile index, `inst/extdata/ClimateNA_tiles.sqlite`, which maps each tile, year or period and subset to an object in the bucket (its `key`, and its MD5), and holds the bucket's address (`base_url` in the `release` table). + +Releases before climateData 2.3.0 kept their archives on Google Drive, and their indexes hold Drive file IDs instead. Users get a release through the index shipped in the package. `climateDataRelease()` reports which release that is; modules that cache climate layers (such as canClimateData) should put `climateDataRelease()$release_id` in their cache keys. @@ -26,7 +28,7 @@ A [targets](https://docs.ropensci.org/targets/) pipeline in `data-raw/pipeline/` 1. it runs ClimateNA for every tile and year or period, in a Docker container, and checks each output folder; 2. it cuts the four subset zips for each tile and decade from the `MSY` output, and checks each zip; -3. it uploads the zips to Drive, MD5-verified, reusing the previous release's file for any zip that hasn't changed; +3. it uploads the zips to the bucket, public, and checks each one as a user's download sees it, reusing the previous release's object for any zip that hasn't changed; 4. it writes the tile index for the release and a report of anything that failed. targets records what has been built, so a rerun does only what is missing, failed or changed. @@ -34,11 +36,11 @@ targets records what has been built, so a rerun does only what is missing, faile ## What you need - A Linux compute node with Docker, where your account can run `docker` without `sudo`. -- R with targets, tarchetypes, crew, yaml, devtools, googledrive, digest, DBI and RSQLite, and a checkout of this package. Run the pipeline from the package root: every R process loads the package from there with `devtools::load_all()`. -- The `zip` program, which writes the archives so that a rebuilt zip of unchanged outputs is byte-identical (and so keeps matching the previous release's file). +- R with targets, tarchetypes, crew, yaml, devtools, httr2, jsonlite, digest, DBI, RSQLite and [buckethost](https://github.com/PredictiveEcology/buckethost) (from GitHub), and a checkout of this package. Run the pipeline from the package root: every R process loads the package from there with `devtools::load_all()`. +- The `zip` program, which writes the archives so that a rebuilt zip of unchanged outputs is byte-identical (and so keeps matching the previous release's object). - ClimateNA, unpacked onto a shared directory (see below). -- The DEM tiles, `can_dem_.asc`, with Windows line endings (`makeClimateDEM()`, `rewrite_asc()`). -- Write access to the Drive folder that holds the archives, for real uploads. +- For a release that already has DEM tiles (the 3 and 1 arcmin releases), their folder. A new release can leave it out: the pipeline then builds them (see "Tiles and DEM tiles" below). +- For real uploads: [rclone](https://rclone.org/) on the main node, with a remote for the bucket (see "Access to the bucket" below). ## The ClimateNA image @@ -66,8 +68,8 @@ Download each ClimateNA release from [climatena.ca](https://climatena.ca/) and u The pipeline reads two files: -- `data-raw/pipeline/release.yml` (committed) defines the release: `release_id`, the ClimateNA executable and version, the DEM resolution, the archive types, the years, GCMs, SSPs and normals periods, the minimum ClimateNA version to keep per type (`min_version`), the image, and the Drive folder (`drive_parent`). -- `data-raw/pipeline/_local.R` (gitignored; copy `_local.R.example`) holds what depends on the machine: paths (ClimateNA directory, DEM tiles, output root, and a node-local `work_dir`), the container user, an optional tile subset, `dry_run`, `replace_changed`, `run_timeout`, `previous_index`, the Drive account (`drive_email`), `upload_workers`, and how many ClimateNA runs go at once (`workers`, or `ssh_nodes` across machines). The checkout's own path is in neither file and no target depends on it, so running from a different checkout rebuilds nothing. +- `data-raw/pipeline/release.yml` (committed) defines the release: `release_id`, the ClimateNA executable and version, the DEM resolution, the archive types, the years, GCMs, SSPs and normals periods, the minimum ClimateNA version to keep per type (`min_version`), the image, and the bucket (`bucket`: its endpoint, its container, which is the project id and the bucket name, and the key prefix). +- `data-raw/pipeline/_local.R` (gitignored; copy `_local.R.example`) holds what depends on the machine: paths (ClimateNA directory, DEM tiles, output root, and a node-local `work_dir`), the container user, an optional tile subset, `dry_run`, `replace_changed`, `run_timeout`, `previous_index`, the rclone remote for the bucket (`rclone_remote`), `upload_workers`, and how many ClimateNA runs go at once (`workers`, or `ssh_nodes` across machines). The checkout's own path is in neither file and no target depends on it, so running from a different checkout rebuilds nothing. The paths must not hold spaces or quotes: the pipeline passes them to zip, docker and rclone through the shell, and stops before anything runs if one does. ClimateNA writes each output into `work_dir` (by default each worker's temporary directory) on the node's own disk. The pipeline checks it there and stores it in `out_root` as a single zip per tile and year or period. ClimateNA writes very slowly straight to an NFS share, and copying hundreds of small files per run overloads the file server; one zip per run avoids both. @@ -75,7 +77,21 @@ The DEM tiles have no elevation for some cells (`nan`), and ClimateNA writes val ClimateNA also leaves some land cells (cells with a DEM elevation) empty: its future data miss some coastal cells, and a few cells get no values at all. The pipeline fills each one with ClimateNA's point-mode output at the nearest land cell it covers, run with the empty cell's elevation, if that cell is within `fill_max_km` (`release.yml`, default 50). `fill_points` finds the empty cells and their sources once per release, from one reference period per class (historical: the last historical year; future: the first scenario's first year), and checks each source with a point run; the next nearest is tried when one gives no values. `fills_` runs ClimateNA in point mode for every period of a tile with empty cells and stores the output beside the raw period zip (`.fill-.csv`); `zip_batch()` writes those values into the zips, after the mask. A land cell still empty when a zip is cut is reported as a warning (it appears in `report.csv`). The index lists every filled cell, and any left empty, in `filled_cells`; users read it with `filledCells()`. -`out_root` in `_local.R` holds everything a release writes: raw ClimateNA outputs (`raw/`, one zip and one stamp per tile and year or period), the published zips (`zips/`), the targets store (`_targets/`), logs, the index and the report. **Keep the same `out_root` from one release to the next**: the next release then reuses the raw outputs and zips that haven't changed, and their Drive files. +`out_root` in `_local.R` holds everything a release writes: raw ClimateNA outputs (`raw/`, one zip and one stamp per tile and year or period), the published zips (`zips/`), the targets store (`_targets/`), logs, the index and the report. **Keep the same `out_root` from one release to the next**: the next release then reuses the raw outputs and zips that haven't changed, and their objects in the bucket. + +## Tiles and DEM tiles + +ClimateNA runs one tile at a time, on that tile's DEM file. The tiles are the 86 polygons in `inst/extdata/tiles.gpkg`: a 10 by 10 grid over the bounding box of Canada (GADM 4.1, level 0, holes filled), keeping the cells that intersect Canada, numbered in grid order. Tile ids are in every archive's name and index row, so the grid never changes. + +A release whose `_local.R` names no `dem_dir` builds its own DEM tiles in `/dem/`: + +1. `tile_grid` applies the rule above to the boundary and stops unless the result equals the shipped `tiles.gpkg`. +2. `gtopo30` downloads the GTOPO30 elevation mosaic of Canada (USGS, 30 arc-seconds) from the bucket (`climateData/dem/gtopo30Canada.zip`), checked against its MD5. +3. `dem_built` projects it to lon/lat (ClimateNA needs lon/lat) at the release's `dem_resolution`, crops and masks it to Canada (holes filled), and cuts it by the tile polygons into `can_dem_.asc`. A tile with no DEM cell gets no file, and so no archives (tile 53 at 3 arcmin). + +Before any batch runs, every release's DEM files are checked: Windows (CRLF) line endings, which ClimateNA needs (`rewrite_asc()` writes them on any platform), square cells at `dem_resolution`, and a lon/lat extent. + +The 3 and 1 arcmin releases keep their own DEM folders (`dem_dir`). Each stored ClimateNA period records its DEM file's hash, so changing a single byte of a DEM tile reruns every period of that tile, and a rebuilt tile never matches a used one byte for byte. Rebuilt with the steps above, the 3 arcmin tiles have the same grid for all 81 tiles and the same elevation in every cell both have one; tiles 7, 8, 9 and 68 lack an elevation in 20 cells just outside Canada that the release's tiles have. ClimateNA's outputs on a rebuilt tile with the same elevations (tile 39) are byte-identical to the release's. ## Where it runs @@ -96,11 +112,13 @@ The older `controller` setting is no longer read: the pipeline stops and asks fo With several nodes, the package checkout, ClimateNA, the DEM tiles and `out_root` must be at the same paths on every node (a shared filesystem), and every node needs Docker and the image. -Uploads always run on the main node, where the Drive token is: in parallel on a separate set of local workers (`upload_workers`, 8 by default), after the main process has created the release's Drive folders. The index is built in the main process. +The pipeline writes its SQLite databases (the index, and the previous release's lookup) in `out_root`. SQLite can fail on some network filesystems, as the old build scripts noted; it has worked on the shared filesystem used so far. If a build fails there with "database is locked" or "disk I/O error", give `out_root` a local disk. + +Uploads always run on the main node, where the rclone remote is set up: in parallel on a separate set of local workers (`upload_workers`, 8 by default). The index is built in the main process. ## Running the pipeline -Start with a dry run (`dry_run = TRUE`, the default): it builds everything except the uploads, and writes an index whose Drive IDs are missing (or are the previous release's, for unchanged zips). A dry run on one tile (`tiles = 39L`) is a quick check of a new setup. +Start with a dry run (`dry_run = TRUE`, the default): it builds everything except the uploads, reads nothing from the bucket (except, when `_local.R` names no `dem_dir`, the GTOPO30 mosaic for the DEM tiles), and writes an index whose object keys are missing (or are the previous release's, for unchanged zips). A dry run on one tile (`tiles = 39L`) is a quick check of a new setup. From the package root on the main node, start the run as its own systemd unit, so it survives the end of your session and is easy to stop: @@ -125,8 +143,9 @@ ClimateNA takes about 45 seconds per tile and year at 3 arcmin, so a decade batc When a run ends, read `report.csv` in `out_root`. It is empty when everything was built and uploaded. Otherwise it lists: -- every error and warning that targets recorded, with the target that raised it; -- every zip that is missing from the release, because its batch, zip or upload failed. +- every error and warning that targets recorded, with the target that raised it (only for targets the pipeline still has: a branch it no longer makes, such as one for a tile dropped from the release, keeps its old error in the store until `targets::tar_prune()`, but is left out); +- every zip that is missing from the release, because its batch, zip or upload failed; +- `settings`: years, periods, GCMs or SSPs in `release.yml` that differ from `available()`, the package's list of what users can request (update one or the other, or users will ask for data the release doesn't have). The same errors are in the targets metadata: @@ -139,7 +158,10 @@ Common errors: - `ClimateNA failed or wrote incomplete output for : `: the run crashed, timed out (`run_timeout`), or left files missing. The container log is in `out_root/logs/.log`. That batch's zips are not cut. - `ClimateNA changes outputs`: see "Adding a year" below. -- `MD5 mismatch after uploading ...`: the upload was corrupted; rerunning uploads the zip again. +- `: not public: ...`: the object was stored private (e.g. the upload lost its `public-read` setting); the index won't point at it. A rerun uploads it again with `--s3-acl public-read`; if the error comes back, the remote or the bucket keeps objects private: check them. +- `: the public object's MD5 and size ... differ from the zip's`: the upload was corrupted; with `replace_changed = TRUE` a rerun uploads the zip again. +- `: rclone couldn't upload ...` or `couldn't list ...`: rclone's own message follows (keys, network, quota). +- `: a released index refers to ...`: the zip changed, but a shipped index points at its object; see "Uploading". Fix the cause and run `tar_make()` again. Only what failed reruns. Every run also re-checks each batch's output folders, so a deleted or damaged folder is found and rerun. @@ -154,39 +176,59 @@ Each new year of data comes with a new ClimateNA release. Before any batch runs, `compat_` reruns a sample of the stored outputs with the new ClimateNA (tiles 6, 39 and 77 when present; each tile's first and last year or period) and compares them with the stored ones: -- **compatible** (the same files, at most 1 in 100,000 cells differ, and none by more than 1): the stored outputs are kept, only the new year runs, and only the zips for the decade that gained the year are cut and uploaded. Every other zip reuses the previous release's Drive file. -- **changed**: the pipeline stops with a message naming the type. If the differences are real, regenerate that type: set its `min_version` to the new version in `release.yml` and run again. Every period of that type is then rerun with the new ClimateNA, and all its zips are uploaded as new files. +- **compatible** (the same files, at most 1 in 100,000 cells differ, and none by more than 1): the stored outputs are kept, only the new year runs, and only the zips for the decade that gained the year are cut and uploaded. Every other zip reuses the previous release's object. +- **changed**: the pipeline stops with a message naming the type. If the differences are real, regenerate that type: set its `min_version` to the new version in `release.yml` and run again. Every period of that type is then rerun with the new ClimateNA, and all its zips are uploaded as new objects under the new release's prefix. ## Adding a GCM or SSP Add it to `gcms` or `ssps` in `release.yml`, and to the lists in `available()` (`R/available.R`). Only the new scenario's batches run; existing scenarios are untouched. -## Uploading +## Access to the bucket -Set `dry_run = FALSE` in `_local.R` for the real run. Uploads use your Google account's OAuth token: authenticate once, interactively, on the main node with `googledrive::drive_auth()`, and set `drive_email = "you@example.org"` in `_local.R` so the pipeline finds the cached token. +The archives are in the `predictiveecology` bucket of a project on the Alliance's Arbutus cloud. Anyone can read them over HTTPS; uploading needs membership in that project and S3 keys (EC2 credentials) for rclone. Create the keys once, on the machine that will upload: -Each zip is, in order of preference: +1. In the Arbutus dashboard, with the project selected, create an application credential (*Identity*, *Application Credentials*) with *Unrestricted* ticked: a restricted one can't create EC2 keys. Download its OpenStack RC file. Keep the application credential: EC2 keys made through it may stop working without it. +2. In a new shell, with no other `OS_` variables set: -- **reused**: the previous release's index (`previous_index`; by default the index shipped in the package checkout) has the identical zip (same path and MD5), and its Drive file still exists; -- **found**: the release folder already has the file, from an interrupted run; -- **updated**: the release folder has a file of that name with another MD5, because the zip was rebuilt (as for the mask in #40). Only with `replace_changed = TRUE` in `_local.R`: the file's content is replaced in place and MD5-checked, and its Drive ID stays the same, so the index still points to it. Without it, the upload stops with an error naming the zip; -- **uploaded** as a new file and MD5-checked. + ```sh + pipx install python-openstackclient + source app-cred--openrc.sh + openstack ec2 credentials create + ``` + + Keep the access key and secret in a password manager. (The project's own RC file, which asks for your password, returns HTTP 401 on the current Arbutus cloud.) +3. Set up an rclone remote with them: `rclone config`, a new remote of type `s3`, provider `Other`, the two keys, endpoint `https://object-arbutus.alliancecan.ca`, `acl` `public-read`, and, under the advanced options, `force_path_style = true`. Name it as in `rclone_remote` (`arbutus` by default). `rclone lsd arbutus:` should list `predictiveecology`. + +The keys stay in rclone's configuration on that machine; never put them in the repository. + +## Uploading -The pipeline never deletes a file on Drive, and it replaces one only in the release's own folder and only when you set `replace_changed`, so the indexes of older package versions keep working. Set it for the one run that needs it, then back to `FALSE`. Drive keeps a replaced file's previous content as an older revision for a while. +Set `dry_run = FALSE` in `_local.R` for the real run. Each zip is, in order of preference: -## The release folder on Drive +- **reused**: the previous release's index (`previous_index`; by default the index shipped in the package checkout) has the identical zip (same path and MD5) in this bucket, and that object is still there, public, with that MD5; +- **found**: the zip's key already holds it, from an interrupted run; +- **updated**: the key holds another MD5, because the zip was rebuilt. Only with `replace_changed = TRUE` in `_local.R`, and never for an object the previous release's index refers to: installed copies of that release check each download against the index's MD5, so replacing it would break them. A fix to released data needs a new `release_id`. Otherwise the upload stops with an error naming the zip; +- **uploaded** as a new object. -New files go into a folder for the release inside the archive folder (`drive_parent`): +Every object is uploaded public (`--s3-acl public-read`: new objects are private otherwise) and in a single part, so its ETag is its MD5. After each upload, the pipeline fetches the object's headers anonymously, as a user's download would, and stops naming the zip unless it is public with the zip's MD5 and size. The pipeline never deletes an object. Set `replace_changed` for the one run that needs it, then back to `FALSE`. + +## The release's objects in the bucket + +Each zip is the object ``` -//[/_ssp]// +//[/_ssp]// ``` -for example `cna-v7.70-3arcmin/future/CanESM5_ssp245/MSY/39_CanESM5_245_MSY_2050.zip`. The index's `zipfile` column holds the path below the release folder. A release folder holds only the zips that release uploaded; reused zips stay in the folder of the release that first uploaded them. Don't delete an old release's folder while any shipped index still points into it. +for example `climateData/cna-v7.70-3arcmin/future/CanESM5_ssp245/MSY/39_CanESM5_245_MSY_2050.zip`, at `//` (`base_url` in the index, then the key). The index's `zipfile` column holds the path below the release; `key` holds the whole key. A release's prefix holds only the zips that release uploaded; reused zips stay under the release that first uploaded them. Don't delete an old release's objects while any shipped index still points at them. + +## The bucket's catalogue + +The bucket has a browsable catalogue: an `index.html` in every folder, at `//index.html`. After a run whose uploads changed, the `catalogue` target rewrites it with buckethost's `generateIndexes()`, through the same rclone remote. It lists the bucket and rewrites every page outside the excluded folders, including those of the bucket's other data, so its heading, disclaimer, footer and excluded folders (`catalogue` in `release.yml`) must match the settings the bucket's other users run it with; agree any change with them. It doesn't run in a dry run. Folders listed under `exclude` get no pages; the live catalogue leaves out `wbi/`, whose 2.9 million objects would make a refresh take about 18 hours instead of minutes. If it fails, the error is in `report.csv` and the archives are unaffected; rerun with `targets::tar_invalidate(catalogue)` and `tar_make()`. ## Shipping a release -1. Audit the release (below). +1. Verify the release (below). 2. Copy the index into the package: ```r @@ -201,18 +243,22 @@ for example `cna-v7.70-3arcmin/future/CanESM5_ssp245/MSY/39_CanESM5_245_MSY_2050 The copied index becomes the next release's `previous_index`. -## Auditing a release +## Verifying a release -`data-raw/04-audit_archives.R` checks the published archives independently of the pipeline. For every zip in an index, it checks that the file on Drive holds every year or period folder the index claims, with every variable file present and non-empty, downloading the Drive copy when the local zip differs from it. It writes its findings (`zips.csv`, `report.csv`, `summary.md`) and changes nothing. Audit a release's index before copying it into the package. From the package root, on the main node: +The pipeline checks each zip's contents when it cuts it, and each object's MD5 when it uploads it, so a release whose objects all still carry the index's MD5s holds the archives the pipeline checked. Before copying the index into the package, compare the bucket with it once, on a compute node: ```r -googledrive::drive_auth(email = "you@example.org") -auditIndex <- "/path/to/out_root/ClimateNA_tiles.sqlite" -auditZipRoot <- "/path/to/out_root/zips" -auditDriveFolders <- list(release = "") -auditDir <- file.path("/path/to/out_root/_audit", format(Sys.Date())) -auditTypes <- c("historical", "historical_normals", "future", "future_normals") -source("data-raw/04-audit_archives.R") +idx <- DBI::dbConnect(RSQLite::SQLite(), "/path/to/out_root/ClimateNA_tiles.sqlite") +a <- DBI::dbGetQuery(idx, "SELECT key, md5, size FROM archives") +DBI::dbDisconnect(idx) +ls <- jsonlite::fromJSON(system2( + "rclone", + c("lsjson", "-R", "--hash", "--files-only", "arbutus:predictiveecology/climateData"), + stdout = TRUE +)) +objs <- data.frame(key = paste0("climateData/", ls$Path), md5 = ls$Hashes$md5, size = ls$Size) +m <- merge(a, objs, by = "key", all.x = TRUE, suffixes = c("", "_bucket")) +stopifnot(!anyNA(m$md5_bucket), m$md5 == m$md5_bucket, m$size == m$size_bucket) ``` -Zips that the release reused from an earlier release are outside its folder; the script looks those up by their Drive IDs. Every zip should come out complete; any that doesn't is classed `rerun_pipeline`. +Then check a random sample of the objects anonymously (e.g. `curl -sI ` gives `200` and an ETag equal to the MD5), and run `prepClimateLayers()` once for each archive type on a machine with no credentials.