| Title: | A Framework for Real-Time Analysis and Disease Surveillance |
|---|---|
| Description: | A comprehensive framework for building real-time disease surveillance systems. Provides R6-based infrastructure for database-driven surveillance tasks, with support for parallel processing, data validation, and automated pipeline execution. Designed for epidemiological analysis and public health monitoring applications. |
| Authors: | Richard Aubrey White [aut, cre] (ORCID: <https://orcid.org/0000-0002-6747-1726>), Folkehelseinstituttet [cph] |
| Maintainer: | Richard Aubrey White <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 26.11.18 |
| Built: | 2026-11-27 13:00:59 UTC |
| Source: | https://github.com/niphr/cs9 |
Diagnostic function that checks the CS9 environment configuration. This function checks the required environment variables and the database connectivity. It reports detailed feedback that helps you troubleshoot configuration problems.
check_environment_setup(verbose = TRUE, use_startup_message = FALSE)check_environment_setup(verbose = TRUE, use_startup_message = FALSE)
verbose |
Logical. If TRUE (default), prints detailed diagnostic output. If FALSE, runs the check silently and only returns the result object. |
use_startup_message |
Logical. If TRUE, uses packageStartupMessage() for output (suppressible). If FALSE (default), uses cat() for console output. |
CS9 needs specific environment variables for database connectivity and configuration. This function checks for:
Required environment variables (CS9_DBCONFIG_ACCESS, CS9_DBCONFIG_DRIVER, etc.).
Database configuration availability.
Database table initialization status.
When you install CS9 from CRAN without a database configuration, the package loads with limited functionality. Use this function to identify what you must configure for full database-driven surveillance functionality.
A list containing environment setup status and recommendations:
status: "ok", "warning", or "error".
issues: Character vector of identified problems.
recommendations: Character vector of suggested fixes.
The installation vignette: vignette("installation", package = "cs9").
# Check environment setup with verbose output check_environment_setup() # Check silently and examine results result <- check_environment_setup(verbose = FALSE) if(result$status != "ok") { cat("Issues found:", result$issues, "\n") cat("Recommendations:", result$recommendations, "\n") }# Check environment setup with verbose output check_environment_setup() # Check silently and examine results result <- check_environment_setup(verbose = FALSE) if(result$status != "ok") { cat("Issues found:", result$issues, "\n") cat("Recommendations:", result$recommendations, "\n") }
check_staged_against_live() checks each key of a comparison from
compare_staged_to_live() against the rules in rules. It stops with an
error that names every failing key, and otherwise returns the comparison.
check_staged_against_live( comparison, rules = c("partitions_agree", "no_missing", "no_decrease") )check_staged_against_live( comparison, rules = c("partitions_agree", "no_missing", "no_decrease") )
comparison |
A data.table from |
rules |
A character vector with one or more of |
A key is live when a live row of any partition holds it. These are the rules:
partitions_agree: the partitions that hold the key have one value in
the live rows, and one value in the staged rows. "One value" means that
unique() of the values has length 1.
no_missing: a live key has a staged value.
no_decrease: no staged value of a live key is below a live value of
it. A staged value equal to the live value passes.
no_missing and no_decrease pass a key that is not live.
partitions_agree checks every key, also a key that is not live.
A key fails at most once, with the first problem in this order:
the live partitions disagree on the stored total (<values>)
the partitions disagree on the staged total (<values>)
staged none, stored <values>
staged <values>, stored <values>
<values> are the distinct values, sorted, without scientific notation,
and separated by ", ". These texts and this order are those of
consultations_check() in norsyss.cs9.
comparison, invisibly, when every key passes. Otherwise the
function stops with an error of class cs9_staged_check_error. Its
message names each failing key and its problem. Its element failures
is a data.table with the key columns and problem, with one row per
failing key.
## Not run: # In the action of a task that has the table `results` in its tables. comparison <- compare_staged_to_live(tables$results, "isoyearweek", "n") check_staged_against_live(comparison, rules = "no_decrease") ## End(Not run)## Not run: # In the action of a task that has the table `results` in its tables. comparison <- compare_staged_to_live(tables$results, "isoyearweek", "n") check_staged_against_live(comparison, rules = "no_decrease") ## End(Not run)
compare_staged_to_live() reads the rows that the task run in progress
staged in table, and the live rows of table. It returns the values of
one column of both, side by side, for each key and partition.
compare_staged_to_live(table, key, value, filter = NULL)compare_staged_to_live(table, key, value, filter = NULL)
table |
A |
key |
A character vector of column names. The values of these
columns identify a key. The vector MUST NOT contain |
value |
The name of one column. Its values MUST be numeric. |
filter |
|
The function reads the staged rows with table$staged_tbl(). It reads the
live rows with tbl() of table, or of each partition table of a
partitioned table. It skips a live table that does not exist. It collects
each side with csdb::collect_and_sort_by_pk().
The function works only during a task run of a task that has table in
its tables. Outside a run it stops with the error of staged_tbl().
A row of the result holds at most one staged value and one live value.
Several rows of one side can share a key in one partition, for example
when key is not the whole primary key. The function then keeps each
distinct value. The result then has one row for each combination of a
distinct staged value and a distinct live value of that key and partition.
check_staged_against_live() then sees the disagreement.
The function reads a value of NA as no value.
A data.table with the key columns and these columns:
partition: character. The name of the partition, as in
names(table$tables). NA for a table without partitions.
staged: numeric. The staged value, or NA where no staged row holds
the key in that partition.
live: numeric. The live value, or NA where no live row holds the key
in that partition.
The rows are sorted by the key columns, partition, staged and
live, with NA first.
## Not run: # In the action of a task that has the table `results` in its tables. weeks <- c("2026-45", "2026-46") comparison <- compare_staged_to_live( tables$results, key = "isoyearweek", value = "n", filter = function(x) dplyr::filter(x, isoyearweek %in% !!weeks) ) check_staged_against_live(comparison) ## End(Not run)## Not run: # In the action of a task that has the table `results` in its tables. weeks <- c("2026-45", "2026-46") comparison <- compare_staged_to_live( tables$results, key = "isoyearweek", value = "n", filter = function(x) dplyr::filter(x, isoyearweek %in% !!weeks) ) check_staged_against_live(comparison) ## End(Not run)
Flags/values to be used in the 'dashboards' scene
configconfig
Creates a directory and all necessary parent directories if they don't already exist.
create_folder_if_doesnt_exist(path)create_folder_if_doesnt_exist(path)
path |
Character string specifying the directory path to create. |
Character string containing the created directory path.
## Not run: # Create a new directory create_folder_if_doesnt_exist("/tmp/my_analysis/results") ## End(Not run)## Not run: # Create a new directory create_folder_if_doesnt_exist("/tmp/my_analysis/results") ## End(Not run)
Copies results from a dated folder to a "latest" folder. The "latest" folder gives easy access to the most recent analysis results.
create_latest_folder(results_folder_name, date)create_latest_folder(results_folder_name, date)
results_folder_name |
Character string specifying the name of the results folder (subdirectory under "output"). |
date |
Character string specifying the date of extraction (used to identify the source folder). |
This function copies all contents from output/results_folder_name/date
to output/results_folder_name/latest. It overwrites existing files.
No return value. This function is called for its side effect of copying files from the dated folder to the latest folder.
## Not run: # Copy today's results to latest folder create_latest_folder("covid_reports", "2024-01-15") ## End(Not run)## Not run: # Copy today's results to latest folder create_latest_folder("covid_reports", "2024-01-15") ## End(Not run)
Retrieves data hash configuration entries from the database table. These entries track data changes across surveillance task plans and elements.
get_config_data_hash_for_each_plan( task = NULL, index_plan = NULL, element_tag = NULL )get_config_data_hash_for_each_plan( task = NULL, index_plan = NULL, element_tag = NULL )
task |
Character string specifying the task name to filter by. If NULL, returns data for all tasks. |
index_plan |
Integer specifying the plan index to filter by. If NULL, returns data for all plans. |
element_tag |
Character string specifying the element tag to filter by. If NULL, returns data for all elements. |
A data.table containing the filtered hash configuration entries with columns: task, index_plan, element_tag, date, datetime, element_hash, all_hash.
## Not run: # Get all hash data for a specific task get_config_data_hash_for_each_plan(task = "covid_analysis") # Get hash data for specific task and plan get_config_data_hash_for_each_plan(task = "covid_analysis", index_plan = 1) ## End(Not run)## Not run: # Get all hash data for a specific task get_config_data_hash_for_each_plan(task = "covid_analysis") # Get hash data for specific task and plan get_config_data_hash_for_each_plan(task = "covid_analysis", index_plan = 1) ## End(Not run)
Retrieves configuration log entries from the config_log table with optional filtering
by surveillance system identifier, task name, and date range.
get_config_log(ss = NULL, task = NULL, start_date = NULL, end_date = NULL)get_config_log(ss = NULL, task = NULL, start_date = NULL, end_date = NULL)
ss |
Character. Surveillance system identifier to filter by. Defaults to |
task |
Character. Task name to filter by. Defaults to |
start_date |
Character. Start date ( |
end_date |
Character. End date ( |
The function retrieves entries from the config_log table in the current configuration.
The function applies start_date and end_date to the date column of the log entries. Both bounds are inclusive.
A data.table containing the filtered log entries.
## Not run: # Get all log entries get_config_log() # Get logs for a specific surveillance system get_config_log(ss = "weather") # Get logs for a specific task and date range get_config_log(task = "data_import", start_date = "2024-01-01", end_date = "2024-12-31") ## End(Not run)## Not run: # Get all log entries get_config_log() # Get logs for a specific surveillance system get_config_log(ss = "weather") # Get logs for a specific task and date range get_config_log(task = "data_import", start_date = "2024-01-01", end_date = "2024-12-31") ## End(Not run)
Retrieves the last updated timestamps for database tables from the configuration tracking system.
get_config_tables_last_updated(table_name = NULL)get_config_tables_last_updated(table_name = NULL)
table_name |
Character string specifying the table name to filter by. If NULL, returns data for all tables. |
A data.table containing last updated information with columns: table_name, last_updated_datetime, and other tracking metadata.
## Not run: # Get last updated info for all tables get_config_tables_last_updated() # Get info for a specific table get_config_tables_last_updated(table_name = "anon_covid_cases") ## End(Not run)## Not run: # Get last updated info for all tables get_config_tables_last_updated() # Get info for a specific table get_config_tables_last_updated(table_name = "anon_covid_cases") ## End(Not run)
Retrieves runtime statistics and performance metrics for surveillance tasks from the configuration database.
get_config_tasks_stats(task = NULL, last_run = FALSE)get_config_tasks_stats(task = NULL, last_run = FALSE)
task |
Character string specifying the task name to filter by. If NULL, returns statistics for all tasks. |
last_run |
Logical value indicating whether to return only the most recent run statistics. If FALSE, returns all historical data. |
A data.table containing task statistics with columns including: task, datetime, runtime_seconds, memory_usage, status, and other metrics.
## Not run: # Get all task statistics get_config_tasks_stats() # Get statistics for a specific task get_config_tasks_stats(task = "covid_analysis") # Get only the last run for a task get_config_tasks_stats(task = "covid_analysis", last_run = TRUE) ## End(Not run)## Not run: # Get all task statistics get_config_tasks_stats() # Get statistics for a specific task get_config_tasks_stats(task = "covid_analysis") # Get only the last run for a task get_config_tasks_stats(task = "covid_analysis", last_run = TRUE) ## End(Not run)
Applies standard include/exclude filters to a database table or data frame.
The filters use the conventional surveillance field names. Each NULL
argument is a no-op, so callers only need to supply the dimensions they
actually want to restrict.
mandatory_db_filter( .data, granularity_time = NULL, granularity_time_not = NULL, granularity_geo = NULL, granularity_geo_not = NULL, country_iso3 = NULL, location_code = NULL, age = NULL, age_not = NULL, sex = NULL, sex_not = NULL )mandatory_db_filter( .data, granularity_time = NULL, granularity_time_not = NULL, granularity_geo = NULL, granularity_geo_not = NULL, country_iso3 = NULL, location_code = NULL, age = NULL, age_not = NULL, sex = NULL, sex_not = NULL )
.data |
A data frame, |
granularity_time |
Character vector. Values of |
granularity_time_not |
Character vector. Values of
|
granularity_geo |
Character vector. Values of |
granularity_geo_not |
Character vector. Values of
|
country_iso3 |
Character vector. Values of |
location_code |
Character vector. Values of |
age |
Character vector. Values of |
age_not |
Character vector. Values of |
sex |
Character vector. Values of |
sex_not |
Character vector. Values of |
The filtered object in the same class as .data.
## Not run: # Inside a data_selector function, filter a remote table before collecting: d <- schema$anon_covid_cases$tbl() |> mandatory_db_filter( granularity_time = "isoweek", granularity_geo = "county", age_not = "total" ) |> dplyr::collect() ## End(Not run)## Not run: # Inside a data_selector function, filter a remote table before collecting: d <- schema$anon_covid_cases$tbl() |> mandatory_db_filter( granularity_time = "isoweek", granularity_geo = "county", age_not = "total" ) |> dplyr::collect() ## End(Not run)
Constructs the appropriate folder path for surveillance system results, with automatic switching between production and interactive modes.
path( ..., create_dir = FALSE, trailing_slash = FALSE, auto = cs9::config$is_auto )path( ..., create_dir = FALSE, trailing_slash = FALSE, auto = cs9::config$is_auto )
... |
Character strings specifying the second level directory and beyond. |
create_dir |
Logical value indicating whether to create the directory if it doesn't exist. Defaults to FALSE. |
trailing_slash |
Logical value indicating whether to add a trailing slash to the returned path. Defaults to FALSE. |
auto |
Logical value indicating whether this is running in automatic mode (uses base directory) or interactive mode (adds "_interactive" subdirectory). Defaults to the current cs9::config$is_auto setting. |
Character string containing the constructed file path.
## Not run: # Get basic output path path("reports", "daily") # Create directory if it doesn't exist path("reports", "daily", create_dir = TRUE) # Get path with trailing slash path("reports", "daily", trailing_slash = TRUE) ## End(Not run)## Not run: # Get basic output path path("reports", "daily") # Create directory if it doesn't exist path("reports", "daily", create_dir = TRUE) # Get path with trailing slash path("reports", "daily", trailing_slash = TRUE) ## End(Not run)
path_get() takes the arguments of path() and downloads that path from
the SMB share in cs9::config$share, a file or a folder with all its
subfolders. It returns the local path when each remote file exists locally
with the remote size.
path_get( ..., create_dir = FALSE, trailing_slash = FALSE, auto = cs9::config$is_auto )path_get( ..., create_dir = FALSE, trailing_slash = FALSE, auto = cs9::config$is_auto )
... |
Character strings specifying the second level directory and beyond. |
create_dir |
Logical value indicating whether to create the directory if it doesn't exist. Defaults to FALSE. |
trailing_slash |
Logical value indicating whether to add a trailing slash to the returned path. Defaults to FALSE. |
auto |
Logical value indicating whether this is running in automatic mode (uses base directory) or interactive mode (adds "_interactive" subdirectory). Defaults to the current cs9::config$is_auto setting. |
path_get() first lists the path on the share. A folder is listed again,
folder by folder, to find every file below it. path_get() creates the
local folders, also the empty ones, and sends one get per file. It then
compares the size of each local file with the size in that listing.
path_get() stops, with an error that contains the local path, in these
cases:
The remote path does not exist.
A local file is missing, or its size is not the remote size.
Any smbclient call reports an NT_STATUS code or a non-zero exit
status.
The checks of the path and of the names in path_put() apply here too,
before any smbclient call. When cs9::config$share is empty, only the
checks of the path apply. path_get() then downloads nothing, does not check
the local path, and returns the path.
The local path from path().
## Not run: folder <- cs9::path_get("input", "weather") ## End(Not run)## Not run: folder <- cs9::path_get("input", "weather") ## End(Not run)
path_ls() takes the arguments of path() and lists the entries directly
in that folder on the SMB share in cs9::config$share. When
cs9::config$share is empty, it lists the local folder with
fs::dir_info().
path_ls( ..., create_dir = FALSE, trailing_slash = FALSE, auto = cs9::config$is_auto )path_ls( ..., create_dir = FALSE, trailing_slash = FALSE, auto = cs9::config$is_auto )
... |
Character strings specifying the second level directory and beyond. |
create_dir |
Logical value indicating whether to create the directory if it doesn't exist. Defaults to FALSE. |
trailing_slash |
Logical value indicating whether to add a trailing slash to the returned path. Defaults to FALSE. |
auto |
Logical value indicating whether this is running in automatic mode (uses base directory) or interactive mode (adds "_interactive" subdirectory). Defaults to the current cs9::config$is_auto setting. |
The entries keep the order of smbclient ls, and . and .. are not
entries. The checks of the path and of the names in path_put() apply here
too, before any smbclient call. Without a share, only the checks of the
path apply. A folder that does not exist on the share is an error that
contains the local path.
A data.table with one row per entry and four columns:
path: the local path of the entry, under cs9::config$path.
type: "file" or "directory". Without a share, the type from
fs::dir_info(), as text.
size: the size in bytes, as a number.
modification_time: a POSIXct in the time zone UTC.
## Not run: cs9::path_ls("input", "weather") ## End(Not run)## Not run: cs9::path_ls("input", "weather") ## End(Not run)
path_put() takes the arguments of path() and uploads the file at that
path to the same relative path on the SMB share in cs9::config$share. It
returns the local path invisibly.
path_put( ..., create_dir = FALSE, trailing_slash = FALSE, auto = cs9::config$is_auto )path_put( ..., create_dir = FALSE, trailing_slash = FALSE, auto = cs9::config$is_auto )
... |
Character strings specifying the second level directory and beyond. |
create_dir |
Logical value indicating whether to create the directory if it doesn't exist. Defaults to FALSE. |
trailing_slash |
Logical value indicating whether to add a trailing slash to the returned path. Defaults to FALSE. |
auto |
Logical value indicating whether this is running in automatic mode (uses base directory) or interactive mode (adds "_interactive" subdirectory). Defaults to the current cs9::config$is_auto setting. |
The share comes from the environment variable CS9_SHARE, for example
//server/share. Each call runs smbclient with
--use-kerberos=required -N, so the session needs a Kerberos ticket.
The upload has four steps:
mkdir for each remote folder above the file, one by one. A folder that
exists already is no error.
put to the temporary name <name>.partial-<pid>-<hex> in the same
remote folder.
ls of the temporary name. The size on the share MUST be the local size.
rename ... -f, which replaces the final name.
When step 2 or step 3 fails, path_put() sends no rename and deletes
nothing under the final name. It tries to delete the temporary name, and it
stops with an error that contains the local path.
path_put() always stops in these two cases, also without a share:
The path is not under cs9::config$path, or cs9::config$path is empty.
A path component is . or ...
When cs9::config$share is empty, path_put() then returns the path. It
uploads nothing and does not check the local file. With a share, it also
stops before it runs smbclient in these cases:
A name contains ", \, *, ?, ; or a control character.
The local file does not exist.
The local path from path(), invisibly.
## Not run: saveRDS(mtcars, cs9::path("output", "weather", "results.rds")) cs9::path_put("output", "weather", "results.rds") ## End(Not run)## Not run: saveRDS(mtcars, cs9::path("output", "weather", "results.rds")) cs9::path_put("output", "weather", "results.rds") ## End(Not run)
Re-reads every CS9_DBCONFIG_* environment variable and rebuilds the four
configuration tables.
reload_db_config()reload_db_config()
cs9 reads the environment once, in its own .onLoad(). A package that sets
its own CS9_DBCONFIG_* values inside .onLoad() therefore sets them too
late. cs9 is a dependency, so cs9 loads first. cs9 reads the
environment before the dependent package runs. Call this function
immediately after the Sys.setenv() block. cs9 then picks the new values
up.
It re-runs set_env_vars(), which rebuilds config$dbconfigs, and then
setup_database_tables(), which rebuilds config$tables. Neither opens a
database connection: csdb::DBTable_v9 creates its table lazily, on first
use.
invisible(NULL), called for its effect on config.
The reload is safe against both a failed reload and a repeated one.
It disconnects every table it is about to discard, so a second reload does not leak the connections held by the R6 objects it replaces.
It then empties config$tables before it touches config$dbconfigs. A
failure anywhere after that point therefore leaves config$tables empty
rather than holding tables built from the previous configuration. An empty
table list is an honest "not configured"; a stale one describes a database
that config$dbconfigs no longer points at.
check_environment_setup(), which reports whether the environment
is complete.
The installation vignette, vignette("installation", package = "cs9").
## Not run: # In a dependent package's .onLoad(), before its own setup runs Sys.setenv(CS9_DBCONFIG_ACCESS = "config/anon") Sys.setenv(CS9_DBCONFIG_DRIVER = "SQLite") Sys.setenv(CS9_DBCONFIG_DB_CONFIG = "/tmp/config.sqlite") Sys.setenv(CS9_DBCONFIG_DB_ANON = "/tmp/anon.sqlite") cs9::reload_db_config() ## End(Not run)## Not run: # In a dependent package's .onLoad(), before its own setup runs Sys.setenv(CS9_DBCONFIG_ACCESS = "config/anon") Sys.setenv(CS9_DBCONFIG_DRIVER = "SQLite") Sys.setenv(CS9_DBCONFIG_DB_CONFIG = "/tmp/config.sqlite") Sys.setenv(CS9_DBCONFIG_DB_ANON = "/tmp/anon.sqlite") cs9::reload_db_config() ## End(Not run)
Starts one task in a process that outlives the R session which started it, and returns at once. The task's exit code is written to a status file when it ends.
run_task_detached( task_name, package_dir = ".", ss_prefix = "global$ss", run_dir = NULL, run_key = NULL, synthetic = FALSE )run_task_detached( task_name, package_dir = ".", ss_prefix = "global$ss", run_dir = NULL, run_key = NULL, synthetic = FALSE )
task_name |
Character string. Name of the task to run. |
package_dir |
Character string. Directory of the implementation package,
which must hold a ‘DESCRIPTION’. Defaults to |
ss_prefix |
Character string. R expression that resolves to the
surveillance system object in the child process. Defaults to
|
run_dir |
Character string or |
run_key |
A string that names the run, or |
synthetic |
|
This is the non-interactive counterpart to
run_task_sequentially_as_callr_bg_using_load_all(). Use that one
in Positron, where a person watches a live console. Use this one when nobody
is watching: a script, a cron entry, or an agent driving a machine over SSH.
The difference is not style. TaskJob passes
supervise = TRUE, so callr kills the task when the parent R
process exits, and it streams output through later::later(), which
needs an event loop that Rscript does not drive.
Invisibly, a list with elements task, log,
status, errors and pid, all character strings. The
status and errors files do not exist until the task ends.
Wait on the status file, never on the log. A log cannot separate "finished cleanly" from "died at line 4", so a caller reading the tail of a log is guessing. The status file appears only when the task ends, and holds the exit code. No file means still running, never done.
Exit code 0 does not mean the work succeeded. Measured on 2026-08-17: a
NorSySS import exited 0 with 212 rejected COPY statements in its
log. The csdb of that date did not read the exit status of its load client,
so a rejected COPY never reached R. Since csdb 2026.10.3 a refused
load stops with an R error. A task that catches an error and continues still
exits 0, so a status of 0 beside a non-zero error count means: read the log.
The count comes from a grep over the log, so it is a heuristic. A count above zero is worth reading. A count of zero does NOT prove the task did what it should: only checking the data can tell you that.
The log opens with the task name, the implementation package and its version, the git branch and commit of the package directory when it is a repository, and whether that tree was clean. A log that reports only a duration cannot answer "which code ran" afterwards.
## Not run: run <- run_task_detached("my_task", package_dir = ".") # later, from anywhere: readLines(run$status) ## End(Not run)## Not run: run <- run_task_detached("my_task", package_dir = ".") # later, from anywhere: readLines(run$status) ## End(Not run)
Positron-friendly counterpart to
run_task_sequentially_as_rstudio_job_using_load_all().
run_task_sequentially_as_callr_bg_using_load_all( task_name, ss_prefix = "global$ss", run_key = NULL )run_task_sequentially_as_callr_bg_using_load_all( task_name, ss_prefix = "global$ss", run_key = NULL )
task_name |
Character string. Name of the task to run. |
ss_prefix |
Character string. R expression that resolves to the
surveillance system object in the child process. Defaults to
|
run_key |
A string that names the run, or |
Invisibly returns the TaskJob R6 object (already started).
## Not run: job <- run_task_sequentially_as_callr_bg_using_load_all("my_task") job$wait() ## End(Not run)## Not run: job <- run_task_sequentially_as_callr_bg_using_load_all("my_task") job$wait() ## End(Not run)
Executes a surveillance task as an RStudio job using devtools::load_all() for package development. This function creates a temporary R script that loads the package and runs the specified task sequentially (cores = 1).
run_task_sequentially_as_rstudio_job_using_load_all( task_name, ss_prefix = "global$ss", run_key = NULL )run_task_sequentially_as_rstudio_job_using_load_all( task_name, ss_prefix = "global$ss", run_key = NULL )
task_name |
Character string specifying the name of the task to run. |
ss_prefix |
Character string specifying the prefix used to access the surveillance system object. Defaults to "global$ss". |
run_key |
A string that names the run, or |
Use this function mainly during package development, to test tasks interactively. It creates a temporary R script that:
Loads the package using devtools::load_all().
Sets the task to run with single core (cores = 1).
Executes the task via the surveillance system.
No return value. This function is called for its side effect of launching an RStudio job that executes the surveillance task.
## Not run: # Run a task as RStudio job during development run_task_sequentially_as_rstudio_job_using_load_all("covid_analysis") # Use custom surveillance system prefix run_task_sequentially_as_rstudio_job_using_load_all( "covid_analysis", ss_prefix = "my_ss" ) ## End(Not run)## Not run: # Run a task as RStudio job during development run_task_sequentially_as_rstudio_job_using_load_all("covid_analysis") # Use custom surveillance system prefix run_task_sequentially_as_rstudio_job_using_load_all( "covid_analysis", ss_prefix = "my_ss" ) ## End(Not run)
Returns the date of the run with a run_key in progress: the date of its
first attempt, also on a retry after midnight. Outside such a run it returns
today's date, as Sys.Date() does.
run_today()run_today()
cs9 sets argset$today to this date. Use run_today() in a planner instead
of Sys.Date(), so that every attempt of a run builds the same plans.
A Date.
run_today()run_today()
Core R6 class for creating and managing disease surveillance systems. This class orchestrates database tables, tasks, and analyses for real-time epidemiological monitoring and public health surveillance.
SurveillanceSystem_v9 provides infrastructure for:
Database table management with automated logging.
Task scheduling and parallel execution.
Data validation and schema enforcement.
Configuration and performance monitoring.
The surveillance system follows a structured approach:
Define database tables with add_table().
Configure surveillance tasks with add_task().
Execute tasks with run_task() or external schedulers.
Every table that add_table() or add_partitionedtable() adds gets a
csdb::SyntheticTable in synthetic_tables. The argument synthetic takes
one of these:
NULL: the schema-only default. It is the spec list().
a spec: a named list with the elements generator, dir, invariants
and profile. Each element is optional.
a csdb::SyntheticTable, which cs9 stores as given.
cs9 builds the SyntheticTable of a spec from the contract of the table.
The contract is the field types of the table without
auto_last_updated_datetime, the keys, and validator_field_contents.
With dir, cs9 calls csdb::synthetic_table_from_dir(), which reads
profile.yaml from dir. A spec MUST NOT have both dir and profile.
The keys of the contract of a partitioned table also hold the partition
column. Each partition is its own database table, so two partitions can
hold the same series. The spec of a partitioned table also gets the
invariant partition_known, which refuses a partition value outside
name_partitions. Without generator, row i gets the partition
name_partitions[(i - 1) %% length(name_partitions) + 1].
set_synthetic(TRUE) stops unless every database is a SQLite file under
tempdir(). It checks each entry of config$dbconfigs and the database of
each table in tables and partitionedtables. The check compares
normalised paths with fs::path_has_parent().
populate_synthetic() stops unless synthetic_mode is TRUE. It stops
when it gets neither task, a task name or a Task, nor tables. It
fills these tables:
task alone: every table in the tables of the task.
tables alone: the tables named in tables.
task and tables: only the tables named in tables. Each of them
MUST be in the tables of the task. Otherwise the call stops, and the
error names the tables that are not.
cs9 cannot tell the input tables of a task from its output tables. When
the tables of a task hold output tables, name the input tables in
tables.
It then works in this order:
It checks the database of every table, and of every partition. One
database that is not SQLite under tempdir() stops the whole call.
It gets the data of each table. With dataset, a table whose catalogue
holds a dataset of that name gets that dataset. Every other table gets
$random(n, seed), and a message names those tables. With a number n, a
partitioned table gets max(n, length(name_partitions)) rows. Every
table gets n = NULL unchanged, which means the generator's own size.
With n = NULL, the default generator of a partitioned table draws the
size of csdb::simulate_from_profile(), and at least
length(name_partitions) rows. The default generator therefore fills
every partition. A custom generator decides which partitions get rows.
It validates the data against the contract of the table that receives
it. A SyntheticTable from the caller can be looser than the table.
With derive, it replaces the data of each table that derive names,
in list order. Then it validates the data of every table again. The
paragraphs on derive below describe this step.
With task, it checks the join groups of the task. The next paragraphs
describe this join check.
For each table, it checks the database of the table again, then calls
drop_all_rows(), then insert_data(). drop_all_rows() empties every
partition, so a partition that the data does not name is left empty.
A failure in steps 1 to 5 therefore writes nothing. The check in step 6 refuses a database that changed after step 1.
derive is NULL or a list of functions, each named by a table that the
call fills. A name of another table stops the call before the first draw.
Element x = f replaces the data of table x with
data.table::as.data.table(f(data, world, seed)). data is the named list
of the data of every table, after the draws and the earlier elements of
derive. world is the world of set_synthetic_world(). seed is the
seed of table x. A function can therefore compute a table from the
tables that the call drew. Every table is validated after the last
function, so a function that breaks another table by reference also stops
the call. Without derive, the call works as it
did before cs9 26.11.12.
add_task(synthetic_joins = ) declares the join groups of a task, and
cs9 stores them in the field synthetic_joins by task name. A join
group is a character vector of at least 2 table names of the tables of
the task. add_task() stops when a group names another table. Two tables
of a group that share key columns MUST have a non-empty inner join on the
shared key columns, the partition column included. Otherwise
populate_synthetic() stops, and the error names the two tables and the
shared columns. A pair with no shared key column is not checked.
The join check is off by default. A task with no join groups gets no join
check, and tables alone gets none. With task and tables, each group
keeps only the tables that the call fills. A group with fewer than 2 of
these tables is skipped.
Each table gets its own seed, so two tables do not share a stream of
random values. The seed of a table is seed plus the first 7 hexadecimal
digits of the md5 of the table name, modulo .Machine$integer.max.
synthetic(table_name, seed = s) uses s as given.
A detached run has its own tempdir(). With run-task.sh --synthetic, the
implementation package MUST point its CS9_DBCONFIG_DB_* variables under
tempdir() in its .onLoad(). It MUST then call reload_db_config().
source(name) returns the simulator of add_source() when
synthetic_mode is TRUE, and the reader otherwise. add_source()
stops unless the reader and the simulator have the same names of
formal arguments, in the same order. The error names both lists.
tablesList of database tables managed by the surveillance system.
partitionedtablesList of partitioned database tables.
tasksList of surveillance tasks configured for execution.
nameCharacter string identifying the surveillance system instance.
implementation_versionCharacter string tracking the analytics code version.
synthetic_tablesNamed list of csdb::SyntheticTable, by table name.
synthetic_modeTRUE when synthetic mode is on. Change it with set_synthetic().
synthetic_worldNULL, or the named list that every generator gets as world.
synthetic_joinsNamed list of the join groups of add_task(synthetic_joins = ), by task name.
sourcesNamed list of sources from add_source(). Each holds a reader and a simulator.
SurveillanceSystem_v9$new()SurveillanceSystem_v9$new( name = "unspecified", implementation_version = "unspecified" )
nameA string that you may use to track performance metrics (runtime and RAM usage).
implementation_versionA string that you may use to track performance metrics (runtime and RAM usage).
SurveillanceSystem_v9$add_table()Add a table.
SurveillanceSystem_v9$add_table( name_access, name_grouping = NULL, name_variant = NULL, field_types, keys, indexes = NULL, validator_field_types = csdb::validator_field_types_blank, validator_field_contents = csdb::validator_field_contents_blank, synthetic = NULL )
name_accessFirst part of table name, corresponding to the database where it will be stored.
name_groupingSecond part of table name, corresponding to some sort of grouping.
name_variantFinal part of table name, corresponding to a distinguishing variant.
field_typesNamed character vector, where the names are the column names, and the values are the column types. Valid types are BOOLEAN, CHARACTER, INTEGER, DOUBLE, DATE, DATETIME.
keysCharacter vector, containing the column names that uniquely identify a row of data.
indexesNamed list, containing indexes.
validator_field_typesFunction corresponding to a validator for the field types.
validator_field_contentsFunction corresponding to a validator for the field contents.
syntheticNULL for the schema-only default, a spec list(generator = , dir = , invariants = , profile = ), or a csdb::SyntheticTable. See the section "Synthetic mode".
No return value. This method is called for its side effect of adding a table to the surveillance system.
global$ss$add_table(
name_access = c("anon"),
name_grouping = "example_weather",
name_variant = "data",
field_types = c(
"granularity_time" = "TEXT",
"granularity_geo" = "TEXT",
"country_iso3" = "TEXT",
"location_code" = "TEXT",
"border" = "INTEGER",
"age" = "TEXT",
"sex" = "TEXT",
"isoyear" = "INTEGER",
"isoweek" = "INTEGER",
"isoyearweek" = "TEXT",
"season" = "TEXT",
"seasonweek" = "DOUBLE",
"calyear" = "INTEGER",
"calmonth" = "INTEGER",
"calyearmonth" = "TEXT",
"date" = "DATE",
"temp_max" = "DOUBLE",
"temp_min" = "DOUBLE",
"precip" = "DOUBLE"
),
keys = c(
"granularity_time",
"location_code",
"date",
"age",
"sex"
),
validator_field_types = csdb::validator_field_types_csfmt_rts_data_v1,
validator_field_contents = csdb::validator_field_contents_csfmt_rts_data_v1
)
SurveillanceSystem_v9$add_partitionedtable()Add a partitioned table to the surveillance system.
SurveillanceSystem_v9$add_partitionedtable( name_access, name_grouping = NULL, name_variant = NULL, name_partitions = "default", column_name_partition = "partition", value_generator_partition = NULL, field_types, keys, indexes = NULL, validator_field_types = csdb::validator_field_types_blank, validator_field_contents = csdb::validator_field_contents_blank, synthetic = NULL )
name_accessFirst part of table name, corresponding to the database where it will be stored.
name_groupingSecond part of table name, corresponding to some sort of grouping.
name_variantFinal part of table name, corresponding to a distinguishing variant.
name_partitionsCharacter string specifying partition naming scheme.
column_name_partitionColumn name used for partitioning.
value_generator_partitionFunction to generate partition values.
field_typesNamed character vector of column names and types.
keysCharacter vector of column names that uniquely identify rows.
indexesNamed list containing index definitions.
validator_field_typesFunction to validate field types.
validator_field_contentsFunction to validate field contents.
syntheticNULL for the schema-only default, a spec list(generator = , dir = , invariants = , profile = ), or a csdb::SyntheticTable. See the section "Synthetic mode".
No return value. This method is called for its side effect of adding a partitioned table to the surveillance system.
SurveillanceSystem_v9$add_task()Add a surveillance task to the system.
run_task() builds the plans again on every call, so argset$today and argset$yesterday hold the date of the run.
SurveillanceSystem_v9$add_task( name_grouping = NULL, name_action = NULL, name_variant = NULL, cores = 1, permission = NULL, plan_analysis_fn_name = NULL, for_each_plan = NULL, for_each_analysis = NULL, universal_argset = NULL, upsert_at_end_of_each_plan = FALSE, insert_at_end_of_each_plan = FALSE, action_fn_name, data_selector_fn_name = NULL, tables = NULL, synthetic_joins = NULL )
name_groupingName of the task (grouping).
name_actionName of the task (action).
name_variantName of the task (variant).
coresThe number of CPU cores, or a function with no arguments that returns it.
The task calls the function each time it runs, so the function MAY read an environment variable that changes after add_task().
A runner that sets cores to 1, such as TaskJob, replaces the function.
permissionA permission R6 instance.
plan_analysis_fn_nameThe name of a function that returns a named list list(for_each_plan = list(), for_each_analysis = NULL).
for_each_planA list, where each unit corresponds to one data extraction. You SHOULD use plnr::expand_list.
for_each_analysisA list, where each unit corresponds to one analysis within a plan (data extraction). You SHOULD use plnr::expand_list.
universal_argsetA list, where these argsets are applied to all analyses universally.
upsert_at_end_of_each_planWhether to upsert your results automatically at the end of each plan.
insert_at_end_of_each_planWhether to insert your results automatically at the end of each plan.
action_fn_nameThe name of the function called for each analysis with arguments data, argset, schema.
data_selector_fn_nameThe name of a function called to obtain the data for each analysis. The function MUST have the arguments argset, schema and MUST return a named list.
tablesA named list that maps cs9::config$schemas for use in action_fn_name and data_selector_fn_name.
synthetic_joinsNULL, or a list of join groups for populate_synthetic(). A join group is a character vector of at least 2 table names of tables. See the section "Synthetic mode".
No return value. This method is called for its side effect of adding a task to the surveillance system.
SurveillanceSystem_v9$get_task()Get a surveillance task by name.
The task builds its plans only when it has none, so it shows the plans of the last build.
Call task$run() on the result to run plans that you edit by hand, because run_task() builds the plans again.
SurveillanceSystem_v9$get_task(task_name)
task_nameCharacter string specifying the task name.
A Task R6 object representing the surveillance task.
SurveillanceSystem_v9$run_task()Execute a surveillance task by name.
The task builds its plans once on every call, before any plan runs and before a worker forks.
The plans do not change during the run, and argset$today is the date of the run.
A run started with a run_key, which a scheduler can pass, stages its writes and changes the task's tables only after every plan succeeds.
An interactive run writes directly, as before. See vignette("rebuilding-a-table-safely").
SurveillanceSystem_v9$run_task(task_name, run_key = NULL)
task_nameCharacter string specifying the task name to run.
run_keyA string that names the run, or NULL. With NULL the run writes the task's tables directly.
A second call with the same run_key resumes a failed run. It skips each plan that the failed run finished, except plan 1.
No return value. This method is called for its side effect of executing the task.
SurveillanceSystem_v9$shortcut_get_tables()Get database tables associated with a task.
SurveillanceSystem_v9$shortcut_get_tables(task_name)
task_nameCharacter string specifying the task name.
A named list of database table objects used by the task.
SurveillanceSystem_v9$shortcut_get_argset()Get argument set for a specific plan and analysis.
SurveillanceSystem_v9$shortcut_get_argset( task_name, index_plan = 1, index_analysis = 1 )
task_nameCharacter string specifying the task name.
index_planInteger specifying which plan to access.
index_analysisInteger specifying which analysis to access.
A named list containing the argument set for the specified plan and analysis.
SurveillanceSystem_v9$shortcut_get_data()Get data for a specific plan.
SurveillanceSystem_v9$shortcut_get_data(task_name, index_plan = 1)
task_nameCharacter string specifying the task name.
index_planInteger specifying which plan to access.
A named list containing the data extracted for the specified plan.
SurveillanceSystem_v9$shortcut_get_plans_argsets_as_dt()Get plans and argsets as a data.table.
SurveillanceSystem_v9$shortcut_get_plans_argsets_as_dt(task_name)
task_nameCharacter string specifying the task name.
A data.table containing plan and analysis information with columns including index_plan and index_analysis.
SurveillanceSystem_v9$shortcut_get_num_analyses()Get the total number of analyses for a task.
SurveillanceSystem_v9$shortcut_get_num_analyses(task_name)
task_nameCharacter string specifying the task name.
Integer value representing the total number of analyses across all plans for the task.
SurveillanceSystem_v9$set_synthetic()Turn synthetic mode on or off. See the section "Synthetic mode".
SurveillanceSystem_v9$set_synthetic(on = TRUE)
onTRUE or FALSE. TRUE stops unless every database is a SQLite file under tempdir().
SurveillanceSystem_v9$set_synthetic_world()Set the world that every generator gets.
SurveillanceSystem_v9$set_synthetic_world(world)
worldNULL, or a named list.
SurveillanceSystem_v9$synthetic()Get validated synthetic data for one table.
SurveillanceSystem_v9$synthetic( table_name, dataset = NULL, n = 1000L, seed = 1L )
table_nameThe name of the table.
datasetNULL for $random(n, seed), or the name of a fixed dataset for $dataset(dataset).
n, seedThe number of rows and the seed of random data.
A validated data.table.
SurveillanceSystem_v9$populate_synthetic()Replace the rows of tables with synthetic data. See the section "Synthetic mode".
SurveillanceSystem_v9$populate_synthetic( task = NULL, tables = NULL, dataset = NULL, n = 1000L, seed = 1L, derive = NULL )
taskNULL, a task name or a Task. The method fills every table in its tables.
tablesNULL, or a character vector of table names to fill.
dataset, n, seedA table whose catalogue holds the dataset dataset gets that dataset. Every other table gets $random(n, seed), with its own seed from seed and the table name.
deriveNULL, or a list of functions named by tables that the call fills. Element x = f replaces the data of table x with f(data, world, seed), after every draw and before the validation of every table.
Invisibly, the number of rows inserted, named by table.
SurveillanceSystem_v9$add_source()Add a source that synthetic mode can switch.
SurveillanceSystem_v9$add_source(name, reader, simulator)
nameThe name of the source.
reader, simulatorThe functions that source() returns with synthetic mode off and on. They MUST have the same names of formal arguments.
SurveillanceSystem_v9$source()Get a source: the simulator with synthetic mode on, else the reader.
SurveillanceSystem_v9$source(name)
nameThe name of the source.
A function.
SurveillanceSystem_v9$clone()The objects of this class are cloneable with this method.
SurveillanceSystem_v9$clone(deep = FALSE)
deepWhether to make a deep clone.
## Not run: # Create surveillance system ss <- SurveillanceSystem_v9$new( name = "covid_surveillance", implementation_version = "1.0" ) # Add database table ss$add_table( name_access = "anon", name_grouping = "covid", name_variant = "cases", field_types = c("date" = "DATE", "cases" = "INTEGER"), keys = c("date") ) # Add surveillance task ss$add_task( name_grouping = "covid", name_action = "import", name_variant = "daily_data", action_fn_name = "import_covid_data", data_selector_fn_name = "select_covid_sources" ) # Run task ss$run_task("covid_import_daily_data") ## End(Not run) ## ------------------------------------------------ ## Method `SurveillanceSystem_v9$add_table()` ## ------------------------------------------------ ## Not run: global$ss$add_table( name_access = c("anon"), name_grouping = "example_weather", name_variant = "data", field_types = c( "granularity_time" = "TEXT", "granularity_geo" = "TEXT", "country_iso3" = "TEXT", "location_code" = "TEXT", "border" = "INTEGER", "age" = "TEXT", "sex" = "TEXT", "isoyear" = "INTEGER", "isoweek" = "INTEGER", "isoyearweek" = "TEXT", "season" = "TEXT", "seasonweek" = "DOUBLE", "calyear" = "INTEGER", "calmonth" = "INTEGER", "calyearmonth" = "TEXT", "date" = "DATE", "temp_max" = "DOUBLE", "temp_min" = "DOUBLE", "precip" = "DOUBLE" ), keys = c( "granularity_time", "location_code", "date", "age", "sex" ), validator_field_types = csdb::validator_field_types_csfmt_rts_data_v1, validator_field_contents = csdb::validator_field_contents_csfmt_rts_data_v1 ) ## End(Not run)## Not run: # Create surveillance system ss <- SurveillanceSystem_v9$new( name = "covid_surveillance", implementation_version = "1.0" ) # Add database table ss$add_table( name_access = "anon", name_grouping = "covid", name_variant = "cases", field_types = c("date" = "DATE", "cases" = "INTEGER"), keys = c("date") ) # Add surveillance task ss$add_task( name_grouping = "covid", name_action = "import", name_variant = "daily_data", action_fn_name = "import_covid_data", data_selector_fn_name = "select_covid_sources" ) # Run task ss$run_task("covid_import_daily_data") ## End(Not run) ## ------------------------------------------------ ## Method `SurveillanceSystem_v9$add_table()` ## ------------------------------------------------ ## Not run: global$ss$add_table( name_access = c("anon"), name_grouping = "example_weather", name_variant = "data", field_types = c( "granularity_time" = "TEXT", "granularity_geo" = "TEXT", "country_iso3" = "TEXT", "location_code" = "TEXT", "border" = "INTEGER", "age" = "TEXT", "sex" = "TEXT", "isoyear" = "INTEGER", "isoweek" = "INTEGER", "isoyearweek" = "TEXT", "season" = "TEXT", "seasonweek" = "DOUBLE", "calyear" = "INTEGER", "calmonth" = "INTEGER", "calyearmonth" = "TEXT", "date" = "DATE", "temp_max" = "DOUBLE", "temp_min" = "DOUBLE", "precip" = "DOUBLE" ), keys = c( "granularity_time", "location_code", "date", "age", "sex" ), validator_field_types = csdb::validator_field_types_csfmt_rts_data_v1, validator_field_contents = csdb::validator_field_contents_csfmt_rts_data_v1 ) ## End(Not run)
Returns a function(profile, n, seed, world) for the generator of a
synthetic spec. The function gives one row for each combination of the
world elements in grid, and draws the other columns with
csdb::simulate_from_profile().
synthetic_grid_generator(grid, finish = NULL)synthetic_grid_generator(grid, finish = NULL)
grid |
A character vector of names of world elements. |
finish |
|
The generator works in this order:
It stops when world is NULL or does not hold every element of
grid.
It takes one unit from each element of grid. A vector is one column
of unique values. A data.frame gives its columns that are in
names(profile$field_types), as unique rows, so the values in one row
stay together. An element with no column in the table is skipped.
It crosses the units. data.table::CJ() crosses the vectors, in the
order of grid, and each data.frame is then crossed with every row so
far. The grid is the result.
It calls csdb::simulate_from_profile() for nrow(grid) rows, with
seed. It removes profile$keys, because the grid makes the rows
unique. It removes every data.frame element from the world. csdb
draws wrong values for a data.frame element named like a TEXT column,
and stops for one named like an INTEGER column.
It replaces each grid column of the draw with the grid.
It calls finish(d, seed, world) when finish is not NULL. world
is the world as the generator got it, with its data.frame elements.
It orders the columns as names(profile$field_types), and returns the
data.table.
The generator ignores n: the grid sets the number of rows. For a
partitioned table, put the partition column in the world and in grid,
so that every partition gets every combination.
The generator stops when the elements of grid give no column of the
table, or give one column twice. It installs the grid values with their R
types, so a world element MUST have the R type of its column.
synthetic_weeks() and synthetic_years() give the time columns with
those types.
A function(profile, n, seed, world) that returns a data.table.
generator <- synthetic_grid_generator(c("location", "age", "weeks")) world <- list( location = data.frame( location_code = c("nation_nor", "county_nor03"), granularity_geo = c("nation", "county") ), age = c("total", "000_004"), weeks = synthetic_weeks("2024-01", "2024-03") ) profile <- csdb::profile_schema( c(location_code = "TEXT", granularity_geo = "TEXT", age = "TEXT", isoyearweek = "TEXT", n = "INTEGER"), keys = c("location_code", "age", "isoyearweek") ) generator(profile, n = NULL, seed = 1L, world = world)generator <- synthetic_grid_generator(c("location", "age", "weeks")) world <- list( location = data.frame( location_code = c("nation_nor", "county_nor03"), granularity_geo = c("nation", "county") ), age = c("total", "000_004"), weeks = synthetic_weeks("2024-01", "2024-03") ) profile <- csdb::profile_schema( c(location_code = "TEXT", granularity_geo = "TEXT", age = "TEXT", isoyearweek = "TEXT", n = "INTEGER"), keys = c("location_code", "age", "isoyearweek") ) generator(profile, n = NULL, seed = 1L, world = world)
synthetic_weeks() returns one row for each isoyearweek from from to
to. synthetic_years() returns one row for each isoyear of those weeks.
synthetic_weeks(from, to) synthetic_years(from, to)synthetic_weeks(from, to) synthetic_years(from, to)
from, to
|
The first and the last isoyearweek, as text, for example
|
Each function returns the 12 time columns of csfmt_rts_data_v2:
granularity_time, isoyearweek, isoyear, isoweek, isoquarter,
isoyearquarter, season, seasonweek, date, calyear, calmonth and
calyearmonth. cstime derives each column except granularity_time from
isoyearweek. date is the last date of the week, and calyear,
calmonth and calyearmonth come from date. The integer columns are integer, seasonweek is
numeric, and date is a Date.
synthetic_weeks() sets granularity_time to "isoyearweek".
synthetic_years() sets it to "isoyear". A row of synthetic_years()
takes the last isoyearweek of its isoyear, from
cstime::isoyear_to_last_isoyearweek_c(). That week can be after to.
Put the result in the world as a data.frame element. Then
synthetic_grid_generator() gives each table the time columns that it
holds.
A data.table with the 12 time columns.
synthetic_weeks("2021-30", "2021-32") synthetic_years("2021-30", "2022-10")synthetic_weeks("2021-30", "2021-32") synthetic_years("2021-30", "2022-10")
Run a cs9 task in a background R process with live output streaming back to
the current R console via later::later() polling. Equivalent in spirit to
run_task_sequentially_as_rstudio_job_using_load_all() but does not
depend on RStudio's job API (which Positron does not implement).
Methods:
$start() spawns the background process and starts to poll its output.
$wait(t) blocks this session until the task finishes. It drains the
event loop while it waits.
$is_alive() returns TRUE while the background process runs.
$status() prints a brief status summary.
$tail(n) prints the last n lines of the log file (a snapshot, not live).
$kill() terminates the background process.
task_nameCharacter string. Name of the task being run.
ss_prefixCharacter string. R expression used to access the surveillance system in the child process.
script_pathCharacter string. Path to the temporary R script that is sourced in the background process.
log_pathCharacter string. Path to the log file where background process output is written.
started_atPOSIXct. Time at which $start() was called.
finished_atPOSIXct. Time at which the background process exited.
run_keyCharacter string or NULL. The run_key that the script
passes to run_task().
TaskJob$new()Create a new TaskJob.
TaskJob$new( task_name, ss_prefix = "global$ss", log_dir = tempdir(check = TRUE), run_key = NULL )
task_nameCharacter string. Name of the task to run, as registered
in the surveillance system (e.g. ss$tasks[["my_task"]]).
ss_prefixCharacter string. R expression that evaluates to the
surveillance system object in the child process. Defaults to
"global$ss".
log_dirCharacter string. Directory where the temporary script and
log file are written. Defaults to tempdir().
run_keyA string that names the run, or NULL. The script
passes it to run_task() in the child process. Pass a key to stage
the run, as a scheduler does. With NULL the task writes its
tables directly.
A new TaskJob object. Call $start() to launch the
background process.
TaskJob$start()Spawn the background process and start to poll its output.
TaskJob$start()
Invisibly returns the TaskJob object.
TaskJob$is_alive()Check whether the background process is still running.
TaskJob$is_alive()
Logical. TRUE while the background process is alive.
TaskJob$status()Print a brief status summary (task name, start time, alive status, log path).
TaskJob$status()
Invisibly returns the TaskJob object.
TaskJob$wait()Block the current session until the background task finishes or the timeout expires. This method drains the later event loop while it waits.
TaskJob$wait(timeout_s = 600)
timeout_sNumeric. Maximum number of seconds to wait. Defaults to
600 (10 minutes).
Invisibly returns the TaskJob object.
TaskJob$kill()Terminate the background process.
TaskJob$kill()
Invisibly returns the TaskJob object.
TaskJob$tail()Print the last n lines of the task log file (snapshot, not live).
TaskJob$tail(n = 20)
nInteger. Number of trailing lines to show. Defaults to 20.
Invisibly returns the TaskJob object.
TaskJob$clone()The objects of this class are cloneable with this method.
TaskJob$clone(deep = FALSE)
deepWhether to make a deep clone.
## Not run: job <- TaskJob$new("my_task") job$start() job$status() job$wait(timeout_s = 120) job$tail(n = 30) ## End(Not run)## Not run: job <- TaskJob$new("my_task") job$start() job$status() job$wait(timeout_s = 120) job$tail(n = 30) ## End(Not run)
Logs configuration updates with relevant metadata such as timestamp,
session state, task name, and a custom message. The function inserts
the log entry into the config_log table in the current configuration.
update_config_log(ss = "unspecified", task = "unspecified", ...)update_config_log(ss = "unspecified", task = "unspecified", ...)
ss |
Character. Surveillance system identifier. Defaults to |
task |
Character. Name of the task being logged. Defaults to |
... |
Character. Custom message describing the log entry. Must not be |
The function records the type of interaction (automatic or interactive),
session state, task description, and a user-provided message in the configuration log.
It throws an error if the message argument is NULL.
The datetime column holds milliseconds. Each call in one R process
writes a datetime at least 4 milliseconds after the previous call.
This keeps two calls for the same task apart in the key of config_log.
No return value; this function is called for its side effect of inserting
a log entry into the config_log table.
## Not run: update_config_log(ss = "weather", task = "data_import", message = "Imported dataset successfully.") ## End(Not run)## Not run: update_config_log(ss = "weather", task = "data_import", message = "Imported dataset successfully.") ## End(Not run)
Points every access in access at a SQLite file in dir and rebuilds the
four configuration tables. It reads and sets no environment variable.
use_sqlite_default(dir, access = c("config", "anon"))use_sqlite_default(dir, access = c("config", "anon"))
dir |
The directory that holds the SQLite files. |
access |
The access names, one SQLite file for each. |
Access a uses the file fs::path(dir, paste0(a, ".sqlite")). The function
creates dir if it does not exist. Each entry of config$dbconfigs has the
fields and the id rule that CS9_DBCONFIG_DRIVER=SQLite gives through
reload_db_config(). The fields that SQLite does not read are empty
strings, and port is NA_integer_.
The function sets config$path to dir and config$is_auto to FALSE.
It does not change config$share.
A child R process does not inherit this configuration, because no
environment variable carries it. Call it in a package's .onLoad(). Each
child R process that loads that package then calls it again, with the
child's own arguments.
invisible(NULL), called for its effect on config.
The function disconnects every table in config$tables and empties the
list before it changes config$dbconfigs. A failure after that point leaves
config$tables empty. access MUST contain "config", because the four
configuration tables use the config access.
reload_db_config(), which reads the configuration from the
CS9_DBCONFIG_* environment variables.
## Not run: # In a dependent package's .onLoad() cs9::use_sqlite_default(file.path(tempdir(), "cs9")) ## End(Not run)## Not run: # In a dependent package's .onLoad() cs9::use_sqlite_default(file.path(tempdir(), "cs9")) ## End(Not run)