Package {cloudosR}


Type: Package
Title: 'Lifebit' Platform 'API' Client
Version: 0.2.4
Description: Interacts with the 'Lifebit' Platform Cohort Browser 'API' https://cloudos.lifebit.ai. Enables schema discovery, table exploration, and read-only 'SQL' query execution with policy-aware behavior and team-based access control for cohort data analysis. Requires bastion-enabled workspaces for 'API' access.
License: MIT + file LICENSE
Encoding: UTF-8
Language: en-US
Depends: R (≥ 4.1.0)
Imports: httr2 (≥ 1.1.0), jsonlite
Suggests: testthat (≥ 3.1.7), withr, knitr, rmarkdown
VignetteBuilder: knitr
RoxygenNote: 7.3.3
NeedsCompilation: no
Packaged: 2026-08-28 08:29:05 UTC; leilamansouri
Author: Leila Mansouri [aut, cre]
Maintainer: Leila Mansouri <leila.mansouri@lifebit.ai>
Repository: CRAN
Date/Publication: 2026-08-28 09:00:02 UTC

List Cohort Tables

Description

Retrieves the list of available database schemas and tables for a cohort.

Usage

cloudos.cohort_tables(profilename = "", cohort_id = "")

Arguments

profilename

Character. Name of the configured profile to use. If empty or NULL, uses the default profile.

cohort_id

Character. ID of the cohort to query schemas for.

Value

List with schema information including databases, tables, and columns.

Examples

## Not run: 
  # Get available schemas for a cohort
  schemas <- cloudos.cohort_tables(
    profilename = "production",
    cohort_id = "your-cohort-id"
  )
  
  # Display databases
  cat("Available databases:\n")
  for (db in schemas) {
    cat("  -", db$database, "\n")
  }

## End(Not run)

Configure Lifebit Platform Profile

Description

Stores API credentials and workspace context for a named profile. This is the required first step before any API wrapper call.

Usage

cloudos.configure(
  profilename = "",
  apikey = "",
  workspace_id = "",
  base_url = "https://cloudos.lifebit.ai",
  set_default = FALSE
)

Arguments

profilename

Character. Name of the profile to create or update.

apikey

Character. API key for authentication.

workspace_id

Character. Workspace/team ID for API requests.

base_url

Character. Base URL for Lifebit Platform API (default: "https://cloudos.lifebit.ai").

set_default

Logical. If TRUE, sets this profile as the default (default: FALSE).

Value

Invisible NULL. Prints a success message.

Examples

## Not run: 
  cloudos.configure(
    profilename = "production",
    apikey = "your-api-key",
    workspace_id = "5c6d3e9bd954e800b23f8c62",
    set_default = TRUE
  )

## End(Not run)

List Lifebit Platform Profiles

Description

Lists configured profiles so users can confirm available environments.

Usage

cloudos.profile_list()

Value

Data frame with profile names and metadata (workspace_id, default, created_at, updated_at). Returns empty data frame if no profiles are configured.

Examples

## Not run: 
  profiles <- cloudos.profile_list()
  print(profiles)

## End(Not run)

Execute SQL Query (Orchestrator)

Description

High-level function that orchestrates the full query lifecycle: submit -> poll status -> fetch results as dataframe.

Usage

cloudos.query(
  profilename = "",
  cohort_id = "",
  sql = "",
  poll_interval = 2,
  max_wait = 600,
  page_size = 1000,
  all_pages = TRUE,
  max_parallel = NULL
)

Arguments

profilename

Character. Name of the configured profile to use. If empty or NULL, uses the default profile.

cohort_id

Character. ID of the cohort to query.

sql

Character. SQL query to execute.

poll_interval

Integer. Seconds between status checks (default: 2).

max_wait

Integer. Maximum seconds to wait for completion (default: 600).

page_size

Integer. Number of rows per page (default: 1000).

all_pages

Logical. Fetch all result pages automatically (default: TRUE).

max_parallel

Numeric. Maximum number of HTTP requests issued concurrently when polling task status and fetching page results. Defaults to the cloudosR.max_parallel option, or 10 when that is unset. Lower it to be gentler on the API; set it to 1 for fully sequential behaviour. When TRUE, submits multiple async tasks (one per page) to fetch complete results.

Details

IMPORTANT: Pagination works by submitting separate tasks for each page. When all_pages=TRUE, this function submits multiple async tasks (one per page), waits for all to complete, and combines the results. This may take longer for large result sets.

Status polling and page-result fetching are performed concurrently, with at most max_parallel requests in flight at any moment.

Value

Data frame with query results.

Examples

## Not run: 
  # Fetch all results
  results <- cloudos.query(
    profilename = "production",
    cohort_id = "699edb4380a6867895f0c9e1",
    sql = "SELECT person_id, gender_concept_id FROM person LIMIT 500"
  )
  
  # Fetch only first page
  results_page1 <- cloudos.query(
    profilename = "production",
    cohort_id = "699edb4380a6867895f0c9e1",
    sql = "SELECT person_id FROM person",
    all_pages = FALSE,
    page_size = 100
  )

  # Limit concurrency to 4 in-flight requests
  results_gentle <- cloudos.query(
    profilename = "production",
    cohort_id = "699edb4380a6867895f0c9e1",
    sql = "SELECT person_id FROM person",
    max_parallel = 4
  )

## End(Not run)

Get Total Row Count for a Query

Description

High-level function that orchestrates the full count lifecycle: submit a count task, poll until complete, and return the total row count. The count endpoint is separate from the data endpoint.

Usage

cloudos.query_count(
  profilename = "",
  cohort_id = "",
  sql = "",
  poll_interval = 2,
  max_wait = 600
)

Arguments

profilename

Character. Name of the configured profile to use. If empty or NULL, uses the default profile.

cohort_id

Character. ID of the cohort to query.

sql

Character. SQL query whose total row count is requested.

poll_interval

Integer. Seconds between status checks (default: 2).

max_wait

Integer. Maximum seconds to wait for completion (default: 600).

Value

Integer. Total number of rows matching the query.

Examples

## Not run: 
  count <- cloudos.query_count(
    profilename = "production",
    cohort_id = "699edb4380a6867895f0c9e1",
    sql = "SELECT person_id FROM person"
  )
  cat("Total rows:", count, "\n")

## End(Not run)

Fetch Count Results from Async Count Task

Description

Fetches the total row count from a completed count async task. Use with a task submitted via cloudos.query_submit_count_async().

Usage

cloudos.query_count_results(profilename = "", task_id = "")

Arguments

profilename

Character. Name of the configured profile to use. If empty or NULL, uses the default profile.

task_id

Character. Task ID returned from cloudos.query_submit_count_async().

Value

Integer. Total number of rows matching the query.

Examples

## Not run: 
  task <- cloudos.query_submit_count_async(
    profilename = "production",
    cohort_id = "699edb4380a6867895f0c9e1",
    sql = "SELECT person_id FROM person"
  )
  # ... poll until completed ...
  count <- cloudos.query_count_results(profilename = "production", task_id = task$task_id)

## End(Not run)

Fetch Async Query Results

Description

Fetches results from a completed async SQL task and returns as a dataframe.

Usage

cloudos.query_results(profilename = "", task_id = "", total_rows = NULL)

Arguments

profilename

Character. Name of the configured profile to use. If empty or NULL, uses the default profile.

task_id

Character. Task ID returned from cloudos.query_submit_async().

total_rows

Integer or NULL. Non-negative total row count for the query, used to populate the total_rows/total_pages metadata. Obtain from cloudos.query_count(). Omit to leave them unpopulated (NULL).

Details

Note: Pagination is controlled when submitting the query via cloudos.query_submit_async(), not when fetching results. This function returns whatever page the task was configured for.

The data endpoint does not return a total row count, so total_rows and total_pages attributes are NULL by default. Pass total_rows (from cloudos.query_count() or cloudos.query_count_results()) to populate both. When the response itself carries a total field (legacy combined endpoint), it is used as a fallback.

Value

Data frame with query results. Carries attributes: total_rows, page, page_size, total_pages, cursor.

Examples

## Not run: 
  results <- cloudos.query_results(
    profilename = "production",
    task_id = "69a5c58d626fe626da0025ce"
  )

## End(Not run)

Check Async Query Status

Description

Returns the current status and metadata for a submitted async SQL task.

Usage

cloudos.query_status(profilename = "", task_id = "")

Arguments

profilename

Character. Name of the configured profile to use. If empty or NULL, uses the default profile.

task_id

Character. Task ID returned from cloudos.query_submit_async().

Value

List with task status, count of results, and other metadata.

Examples

## Not run: 
  status <- cloudos.query_status(
    profilename = "production",
    task_id = "69a5c58d626fe626da0025ce"
  )
  print(status$status)
  print(status$count_of_results)

## End(Not run)

Submit Async SQL Query

Description

Starts async SQL execution for a cohort and returns a task ID for tracking. Targets the query-results/data/async endpoint, which returns rows only (no total row count). Use cloudos.query_submit_count_async() or cloudos.query_count() to get the total row count separately.

Usage

cloudos.query_submit_async(
  profilename = "",
  cohort_id = "",
  sql = "",
  pagination = NULL,
  cursor = NULL
)

Arguments

profilename

Character. Name of the configured profile to use. If empty or NULL, uses the default profile.

cohort_id

Character. ID of the cohort to query.

sql

Character. SQL query to execute.

pagination

List (optional). Pagination settings with pageNumber and pageSize. Example: list(pageNumber = 0, pageSize = 100). If NULL, API returns default page.

cursor

Character (optional). Opaque cursor for cursor-based pagination, as returned in a previous page's attr(result, "cursor").

Value

List with task metadata including task_id, status, and full response.

Examples

## Not run: 
  # Submit query without pagination
  task <- cloudos.query_submit_async(
    profilename = "production",
    cohort_id = "699edb4380a6867895f0c9e1",
    sql = "SELECT person_id FROM person LIMIT 100"
  )

  # Submit query with pagination for page 2 with 50 rows per page
  task <- cloudos.query_submit_async(
    profilename = "production",
    cohort_id = "699edb4380a6867895f0c9e1",
    sql = "SELECT person_id FROM person",
    pagination = list(pageNumber = 2, pageSize = 50)
  )
  print(task$task_id)

## End(Not run)

Submit Async Count Query

Description

Starts an async SQL execution that returns only the total row count for a cohort query. Targets the query-results/count/async endpoint. Fetch the count with cloudos.query_count_results() or use the high-level cloudos.query_count().

Usage

cloudos.query_submit_count_async(profilename = "", cohort_id = "", sql = "")

Arguments

profilename

Character. Name of the configured profile to use. If empty or NULL, uses the default profile.

cohort_id

Character. ID of the cohort to query.

sql

Character. SQL query whose total row count is requested.

Value

List with task metadata including task_id, status, and full response.

Examples

## Not run: 
  task <- cloudos.query_submit_count_async(
    profilename = "production",
    cohort_id = "699edb4380a6867895f0c9e1",
    sql = "SELECT person_id FROM person"
  )
  print(task$task_id)

## End(Not run)

Validate SQL Query

Description

Validates SQL syntax and references before execution.

Usage

cloudos.sql_validate(profilename = "", sql = "")

Arguments

profilename

Character. Name of the configured profile to use. If empty or NULL, uses the default profile.

sql

Character. SQL query to validate.

Value

List with validation results including isValid, tableReferences, and columnReferences.

Examples

## Not run: 
  # Validate a SQL query
  validation <- cloudos.sql_validate(
    profilename = "production",
    sql = "SELECT person_id FROM person WHERE year_of_birth >= 1960"
  )
  
  if (validation$isValid) {
    cat("SQL is valid\n")
    cat("Tables:", paste(validation$tableReferences, collapse = ", "), "\n")
  } else {
    cat("SQL is invalid:", validation$message, "\n")
  }

## End(Not run)

Convert Query Results to Dataframe

Description

Internal function to convert API response data to a dataframe.

Usage

convert_results_to_dataframe(data, column_names)

Arguments

data

List. Data rows from API response.

column_names

Character vector. Column names.

Value

Data frame with query results.


Read an Error Response Body as Text

Description

Internal helper returning a trimmed, truncated string body, or a fallback message when the body is unreadable or empty.

Usage

error_body_text(response)

Arguments

response

HTTP response object from httr2.

Value

Character. Body text or fallback message.


Extract Error Message from a Response Body

Description

Internal function to pull the most informative message out of an error response. JSON bodies contribute their message or error field; text/* bodies (plain text or the HTML pages emitted by gateways and reverse proxies sitting in front of the API) are returned verbatim, truncated to keep the condition message readable.

Usage

extract_error_message(response)

Arguments

response

HTTP response object from httr2.

Value

Character. Error detail, or a fallback string when nothing is readable.


Format Error Message with Generic Access Denial

Description

Returns a generic error message that doesn't leak information about resource existence. Used for schema/table access errors in accordance with security policy.

Usage

format_generic_access_error(resource_type, resource_name = NULL)

Arguments

resource_type

Character. Type of resource (e.g., "schema", "table").

resource_name

Character. Name of the resource (optional).

Value

Character. Generic error message.


Get Config Directory Path

Description

Internal function to get the Lifebit Platform config directory path. Uses tools::R_user_dir() for CRAN-compliant persistent storage. Can be overridden with CLOUDOS_CONFIG_DIR environment variable.

Usage

get_config_dir()

Value

Character. Path to config directory.


Get Config File Path

Description

Internal function to get the Lifebit Platform config file path. Config file is stored in the user's R config directory as .cloudos_config.json using tools::R_user_dir() for CRAN compliance.

Usage

get_config_file()

Value

Character. Path to config file.


Handle API Error Response

Description

Internal function to handle API error responses and generate user-friendly error messages.

Usage

handle_api_error(response, endpoint)

Arguments

response

HTTP response object from httr2.

endpoint

Character. Endpoint that was called (for error context).

Value

NULL (throws error with formatted message).


Make HTTP GET Request

Description

Internal function to make authenticated GET requests to Lifebit Platform API.

Usage

http_get(profile, endpoint, query_params = list())

Arguments

profile

List. Profile configuration from load_profile().

endpoint

Character. API endpoint path (without base URL).

query_params

List. Query parameters to include in request.

Value

Parsed JSON response.


Make Concurrent HTTP GET Requests

Description

Internal function to issue several authenticated GET requests at once via httr2::req_perform_parallel(). At most max_parallel requests are in flight simultaneously; the remainder queue until a slot frees up.

Usage

http_get_parallel(
  profile,
  endpoints,
  query_params = list(),
  max_parallel = NULL
)

Arguments

profile

List. Profile configuration from load_profile().

endpoints

Character vector or list. API endpoint paths (without base URL).

query_params

List. Query parameters applied to every request.

max_parallel

Numeric or NULL. Maximum number of concurrent requests. NULL uses the cloudosR.max_parallel option (default 10).

Details

Results are returned in the same order as endpoints. A single endpoint is dispatched through http_get() so that trivial batches do not pay the cost of setting up a connection pool.

Value

List of parsed JSON responses, in the order of endpoints.


Make HTTP POST Request

Description

Internal function to make authenticated POST requests to Lifebit Platform API.

Usage

http_post(profile, endpoint, body = list(), query_params = list())

Arguments

profile

List. Profile configuration from load_profile().

endpoint

Character. API endpoint path (without base URL).

body

List. Request body to send as JSON.

query_params

List. Query parameters to include in request.

Value

Parsed JSON response.


Check if Response Indicates Access Denial

Description

Internal function to check if API response indicates access denial (could be either non-existent or unauthorized).

Usage

is_access_denied(response)

Arguments

response

HTTP response object from httr2.

Value

Logical. TRUE if access is denied.


Load Profile Configuration

Description

Internal function to load a specific profile's configuration. If profilename is empty or NULL, loads the default profile.

Usage

load_profile(profilename = "")

Arguments

profilename

Character. Name of the profile to load. If empty, loads default profile.

Value

List with profile configuration (apikey, workspace_id, base_url).


Null-coalescing Operator

Description

Returns the left-hand side if it's not NULL, otherwise returns the right-hand side.

Usage

x %||% y

Arguments

x

First value to check.

y

Default value if x is NULL.

Value

x if not NULL, otherwise y.


Parse JSON Response

Description

Internal function to safely parse JSON response from API.

Usage

parse_json_response(response, endpoint = NULL)

Arguments

response

HTTP response object from httr2.

endpoint

Character or NULL. Endpoint that was called, included in the error message when parsing fails.

Value

Parsed JSON object.


Print method for cloudos_tables

Description

Print method for cloudos_tables

Usage

## S3 method for class 'cloudos_tables'
print(x, ...)

Arguments

x

A cloudos_tables object

...

Additional arguments (unused)

Value

The cloudos_tables object x, returned invisibly. Called primarily for its side effect of printing a formatted list of schemas and tables to the console.


Validate and Parse an API Response

Description

Internal function shared by the sequential and parallel HTTP helpers. Raises a formatted error for non-success statuses and for success statuses returned with no body, otherwise parses the JSON payload.

Usage

process_response(response, endpoint)

Arguments

response

HTTP response object from httr2.

endpoint

Character. Endpoint that was called (for error context).

Value

Parsed JSON response.


Resolve Maximum Parallel Requests

Description

Internal function to resolve and validate the concurrency cap used by the parallel HTTP helpers. Falls back to the cloudosR.max_parallel option and then to CLOUDOS_DEFAULT_MAX_PARALLEL.

Usage

resolve_max_parallel(max_parallel = NULL)

Arguments

max_parallel

Numeric or NULL. Requested cap. If NULL, the option is used.

Value

Integer. Positive concurrency cap.


Convert a Results Response into an Annotated Data Frame

Description

Internal function holding the shared parsing and pagination-metadata logic for a completed data task's results payload. Used by cloudos.query_results() and by the concurrent page fetcher so both produce identical data frames.

Usage

results_response_to_df(response, total_rows = NULL)

Arguments

response

List. Parsed results payload from the API.

total_rows

Numeric or NULL. Total row count from a count task.

Value

Data frame with total_rows, page, page_size, total_pages and cursor attributes.


Truncate Error Detail

Description

Internal helper capping error detail length so an HTML error page cannot flood the console.

Usage

truncate_error_text(text, max_chars = 1000L)

Arguments

text

Character. Error detail.

max_chars

Integer. Maximum number of characters to keep.

Value

Character. Possibly truncated text.


Validate Required String Parameter

Description

Internal function to validate that a string parameter is not empty or NULL.

Usage

validate_required_string(value, param_name)

Arguments

value

Character. Value to validate.

param_name

Character. Name of the parameter (for error messages).

Value

NULL (throws error if validation fails).