R/validate.R

Defines functions cli_escape print_workflow_issues bind_issues workflow_flow workflow_issues

# Static checks of a Workflow's graph, used by $validate() and $run().
#
# They follow the rules of $run():
# - a Station that starts a parallel group runs, then the group's Stations
#   run on its output, then the run goes to the group's `to` Station, or
#   stops when it has none. The Station's own Routes are not followed, and
#   neither are the Routes out of the group's Stations;
# - otherwise the conditional Routes are tried first, then the first
#   unconditional one; when no Route is followed, the run stops.

# The issues found, as a data frame with one row per issue: `level`
# ("error" or "warning"), `check`, `stations` (comma separated) and
# `message`.
workflow_issues <- function(stations, routes, groups, entry, prefix = "") {
  issues <- list()
  add <- function(level, check, where, message) {
    issues[[length(issues) + 1L]] <<- data.frame(
      level = level, check = check,
      stations = paste(where, collapse = ", "),
      message = paste0(prefix, message),
      stringsAsFactors = FALSE
    )
  }
  names_all <- names(stations)

  if (length(names_all) == 0L) {
    add("error", "no_stations", character(), "The workflow has no Stations.")
    return(bind_issues(issues))
  }
  flow <- workflow_flow(stations, routes, groups, entry)
  entry <- flow$entry
  group_of <- flow$group_of
  visited <- flow$visited
  in_groups <- flow$in_groups
  runs <- union(visited, in_groups)

  for (group in flow$extra_groups) {
    add("warning", "duplicate_group", group$from, sprintf(
      "Station '%s' starts several parallel groups; only the first one runs.", group$from
    ))
  }

  for (name in names_all) {
    if (!is.null(group_of[[name]])) next
    unconditional <- Filter(
      function(route) identical(route$from, name) && is.null(route$condition), routes
    )
    if (length(unconditional) > 1L) {
      ignored <- vapply(unconditional[-1L], function(route) route$to, character(1))
      add("warning", "ignored_route", name, sprintf(
        "Station '%s' has several unconditional Routes; only the first (to '%s') is followed, never the Route%s to %s.",
        name, unconditional[[1L]]$to, if (length(ignored) > 1L) "s" else "",
        paste0("'", ignored, "'", collapse = ", ")
      ))
    }
  }

  never <- setdiff(names_all, runs)
  if (length(never)) {
    add("warning", "unreachable", never, sprintf(
      "%s never run%s: no Route or parallel group leads to %s from the entry Station '%s'.",
      paste0("'", never, "'", collapse = ", "),
      if (length(never) == 1L) "s" else "",
      if (length(never) == 1L) "it" else "them",
      entry
    ))
  }

  # Routes that are never followed.
  for (name in intersect(names(group_of), visited)) {
    if (any(vapply(routes, function(route) identical(route$from, name), logical(1)))) {
      add("warning", "ignored_route", name, sprintf(
        "Station '%s' starts a parallel group, so its Routes are not followed (the group goes to %s).",
        name, if (is.null(group_of[[name]]$to)) "no Station: the run stops" else paste0("'", group_of[[name]]$to, "'")
      ))
    }
  }
  only_in_groups <- setdiff(in_groups, visited)
  for (name in only_in_groups) {
    if (any(vapply(routes, function(route) identical(route$from, name), logical(1)))) {
      add("warning", "ignored_route", name, sprintf(
        "Station '%s' only runs inside a parallel group, so its Routes are not followed.", name
      ))
    }
  }

  # Loops with no way out: Stations the run can reach, from which it can
  # never reach a Station where it may stop.
  stuck <- flow$stuck
  if (length(stuck)) {
    add("error", "endless_loop", stuck, sprintf(
      "The run can never end once it reaches %s: every Route leads back into the loop. Add a conditional Route out of it, or remove a Route.",
      paste0("'", stuck, "'", collapse = ", ")
    ))
  }

  # Wrapped workflows are checked too.
  for (name in runs) {
    handler <- stations[[name]]$handler
    if (inherits(handler, "WorkflowAgent") && inherits(handler$workflow, "Workflow")) {
      inner <- handler$workflow$.__enclos_env__$private
      nested <- workflow_issues(
        inner$.stations, inner$.routes, inner$.parallel_groups, inner$.entry,
        prefix = paste0(prefix, "In the workflow of Station '", name, "': ")
      )
      if (nrow(nested)) issues[[length(issues) + 1L]] <- nested
    }
  }

  bind_issues(issues)
}

# How the run moves through a Workflow, following the rules of $run():
# - `entry`: where the run starts;
# - `group_of`: the parallel group each Station starts (only the first one
#   from a Station runs), and `extra_groups`, the groups that never run;
# - `next_of`: the Stations the run can go to from each Station, and
#   `can_stop`: whether it can stop there;
# - `visited`: the Stations the run can reach as the current Station, and
#   `in_groups`: the Stations it runs inside a parallel group;
# - `stuck`: reachable Stations from which the run can never end.
workflow_flow <- function(stations, routes, groups, entry) {
  names_all <- names(stations)
  if (is.null(entry)) entry <- names_all[[1L]]

  group_of <- list()
  extra_groups <- list()
  for (group in groups) {
    if (is.null(group_of[[group$from]])) {
      group_of[[group$from]] <- group
    } else {
      extra_groups[[length(extra_groups) + 1L]] <- group
    }
  }

  next_of <- list()
  can_stop <- logical()
  for (name in names_all) {
    group <- group_of[[name]]
    if (!is.null(group)) {
      next_of[[name]] <- if (is.null(group$to)) character() else group$to
      can_stop[[name]] <- is.null(group$to)
      next
    }
    out <- Filter(function(route) identical(route$from, name), routes)
    conditional <- Filter(function(route) !is.null(route$condition), out)
    unconditional <- Filter(function(route) is.null(route$condition), out)
    targets <- vapply(conditional, function(route) route$to, character(1))
    if (length(unconditional)) targets <- c(targets, unconditional[[1L]]$to)
    next_of[[name]] <- unique(targets)
    can_stop[[name]] <- length(unconditional) == 0L
  }

  visited <- character()
  queue <- entry
  while (length(queue)) {
    name <- queue[[1L]]
    queue <- queue[-1L]
    if (name %in% visited) next
    visited <- c(visited, name)
    queue <- c(queue, setdiff(next_of[[name]], visited))
  }
  in_groups <- unique(unlist(lapply(visited, function(name) group_of[[name]]$stations)))
  if (is.null(in_groups)) in_groups <- character()

  can_end <- names(can_stop)[can_stop]
  repeat {
    more <- setdiff(
      names_all[vapply(names_all, function(name) any(next_of[[name]] %in% can_end), logical(1))],
      can_end
    )
    if (!length(more)) break
    can_end <- c(can_end, more)
  }

  list(
    entry = entry, group_of = group_of, extra_groups = extra_groups,
    next_of = next_of, can_stop = can_stop, visited = visited,
    in_groups = in_groups, stuck = setdiff(visited, can_end)
  )
}

bind_issues <- function(issues) {
  if (!length(issues)) {
    return(data.frame(
      level = character(), check = character(), stations = character(),
      message = character(), stringsAsFactors = FALSE
    ))
  }
  out <- do.call(rbind, issues)
  out <- out[order(out$level != "error"), , drop = FALSE]
  rownames(out) <- NULL
  out
}

# Prints the issues $validate() found. Printed to stdout, like a print()
# method, so that it also shows in rendered documents.
print_workflow_issues <- function(issues, name) {
  if (!nrow(issues)) {
    cat(cli::col_green(cli::symbol$tick), " Workflow \"", name, "\": no issues found.\n", sep = "")
    return(invisible(issues))
  }
  n_errors <- sum(issues$level == "error")
  n_warnings <- sum(issues$level == "warning")
  cat(sprintf(
    "Workflow \"%s\": %d error%s and %d warning%s.\n", name,
    n_errors, if (n_errors == 1L) "" else "s",
    n_warnings, if (n_warnings == 1L) "" else "s"
  ))
  width <- max(40L, cli::console_width() - 2L)
  for (i in seq_len(nrow(issues))) {
    mark <- if (issues$level[[i]] == "error") cli::col_red(cli::symbol$cross) else cli::col_yellow("!")
    lines <- strwrap(issues$message[[i]], width = width)
    cat(mark, " ", lines[[1L]], "\n", sep = "")
    if (length(lines) > 1L) cat(paste0("  ", lines[-1L], "\n"), sep = "")
  }
  invisible(issues)
}

# Text that cli prints as is, braces included.
cli_escape <- function(x) gsub("}", "}}", gsub("{", "{{", x, fixed = TRUE), fixed = TRUE)

Try the mini007 package in your browser

Any scripts or data that you put into this service are public.

mini007 documentation built on Dec. 3, 2026, 5:10 p.m.