diff --git a/CHANGELOG.md b/CHANGELOG.md index 2cba59a9..c6bd8d0d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- **Several initial steps.** More than one step can set `initial true`. `AshWorkflow.Transformers.AddStateMachine` passes every initial step to the state machine's `initial_states`, and a create action starts a record in one with `change transition_state(:step)`. A create that sets no state starts in the first initial step by declaration order. The reachability check in `AshWorkflow.Verifiers.ValidateWorkflow` starts from every initial step. A step reached only from a second initial step is no longer reported as unreachable. `AshWorkflow.Info.initial_steps/1` and `AshWorkflow.Entities.Step.find_initials/1` list the initial steps, and `AshWorkflow.Info.workflow_graph/1`, the charts and the Clarity overview mark each of them. + +### Changed + +- The unreachable-step error names the initial step it searched from ("not reachable from the initial step :review") rather than "the first step". +- `AshWorkflow.Verifiers.ValidateWorkflow` no longer raises "Only one step can have initial: true". +- `AshWorkflow.Verifiers.ValidateWorkflow` rejects a create action whose `transition_state` names a step that is not initial. Before, the create failed at runtime. +- `AshWorkflow.Verifiers.ValidateWorkflow` rejects an upserting create action that calls `transition_state`. ash_state_machine only lets an upsert move to a state that a transition declares for that action, and a workflow declares none for creates. +- The unreachable-step error suggests `initial true` for an unreachable step that no other step leads into. + ## [0.12.0] - 2026-11-06 ### Added diff --git a/README.md b/README.md index deca7832..18d02de1 100644 --- a/README.md +++ b/README.md @@ -337,7 +337,7 @@ From the workflow DSL, the extension generates: | **Calculations** | `:steps`, `:current_step`, `:available_actions`, `:transition_targets`, `:pending_deadlines`, `:workflow_terminated_at` | Workflow introspection | | **Attributes** | `state_entered_at`, plus one last-fired column per `every` | Added if not already defined | -The initial state is the step with `initial true`, or the first non-terminal step by declaration order if none is marked. Declaration order is easy to trip over, so mark the step when the reading order is not the running order: +The initial state is the step with `initial true`, or the first non-terminal step by declaration order if none is marked. Several steps can be marked initial when records start in different places. See [Initial state](documentation/topics/automatic-vs-manual-steps.md#initial-state). Declaration order is easy to trip over, so mark the step when the reading order is not the running order: ```elixir workflow do diff --git a/documentation/dsls/DSL-AshWorkflow.md b/documentation/dsls/DSL-AshWorkflow.md index 370ba969..abe9bbad 100644 --- a/documentation/dsls/DSL-AshWorkflow.md +++ b/documentation/dsls/DSL-AshWorkflow.md @@ -89,7 +89,7 @@ Declares a step in the workflow. Each step becomes a state in the generated stat | Name | Type | Default | Docs | |------|------|---------|------| | [`action`](#workflow-step-action){: #workflow-step-action } | `atom` | | The action to run for automatic steps. Must reference a user-defined update action on the resource. | -| [`initial`](#workflow-step-initial){: #workflow-step-initial } | `boolean` | `false` | If true, this step is the initial state. At most one step can be marked initial. If none are, the first non-terminal step by declaration order is used. | +| [`initial`](#workflow-step-initial){: #workflow-step-initial } | `boolean` | `false` | If true, a create action can start a record in this step. Several steps can be marked initial, and the first by declaration order is the state a create starts in when it sets none. If no step is marked, the first non-terminal step by declaration order is the only initial step. | | [`terminal`](#workflow-step-terminal){: #workflow-step-terminal } | `boolean` | `false` | Asserts that this is an end state. A step that declares no action, no transitions, no timeouts, no on_success and no on_error is terminal whether or not this is set, so it is only needed to state the intent — the verifier then rejects the step if it grows an outgoing declaration. | | [`on_error`](#workflow-step-on_error){: #workflow-step-on_error } | `atom` | | The step to transition to on failure. Optional, for automatic steps. | | [`policy`](#workflow-step-policy){: #workflow-step-policy } | `any` | | An Ash policy check to apply to all transitions in this step. Accepts any {module, opts} tuple implementing Ash.Policy.Check. | diff --git a/documentation/topics/automatic-vs-manual-steps.md b/documentation/topics/automatic-vs-manual-steps.md index 4f1bc48c..8d6ca521 100644 --- a/documentation/topics/automatic-vs-manual-steps.md +++ b/documentation/topics/automatic-vs-manual-steps.md @@ -281,6 +281,53 @@ workflow do end ``` -At most one step can have `initial true`. If none do, the first non-terminal step is used. +If no step has `initial true`, the first non-terminal step is used. -The extension sets `default_initial_state` and `initial_states` on the generated state machine. +### Several initial steps + +A workflow whose records start in different places marks each starting step with `initial true`. A create action that sets no state starts in the first of them by declaration order. Any other create action names its starting step with `transition_state`: + +```elixir +workflow do + step :self_service_intake do + initial true + transition :submit, to: :review + end + + step :staff_intake do + initial true + transition :submit, to: :review + end + + step :review do + transition :approve, to: :done + end + + step :done, terminal: true +end + +actions do + # Starts in :self_service_intake, the first initial step. + create :open do + accept [:title] + end + + create :open_by_staff do + accept [:title] + change transition_state(:staff_intake) + end +end +``` + +Every step must be reachable from at least one initial step. The compiler also reports: + +- A create whose `transition_state` names a step that is not marked initial is a compile error. +- An unreachable step that no other step leads into gets a hint to mark it `initial true`. + +Once any step sets `initial true`, the first non-terminal step is no longer initial unless it sets `initial true` too. + +#### Upserting creates + +An upserting create cannot name its starting step. ash_state_machine only lets an upsert move to a state that a transition declares for that action, and the workflow declares none for creates. A create with `upsert? true` and `transition_state` is a compile error, even for a step marked initial. An upserting create starts a new record in the first initial step. An upsert onto an existing record leaves it in the step it was in, as long as `upsert_fields` does not include the state attribute. + +The extension sets `initial_states` to every initial step, and `default_initial_state` to the first, on the generated state machine. diff --git a/documentation/topics/diagrams.md b/documentation/topics/diagrams.md index 021b83a7..a8627b9a 100644 --- a/documentation/topics/diagrams.md +++ b/documentation/topics/diagrams.md @@ -90,7 +90,7 @@ stateDiagram-v2 | Automatic step | `⚙️ automatic` under the step name | | Manual step | `✋ manual` under the step name | | Wait state, where a timeout is the only exit | `⏳ wait state` under the step name | -| Initial step | An edge from the start marker | +| Initial step | An edge from the start marker, one per initial step | | Terminal step | An edge to the end marker | | `on_success` | `⚙` and the step's action | | `on_error` | `✖ on_error` | @@ -526,7 +526,7 @@ colours". #### Layout -`dot` puts the steps in ranks, from the initial step down to the end steps. +`dot` puts the steps in ranks, from the initial steps down to the end steps. An undo edge points back up to the earlier step, next to the edge that it undoes. The file writes it from the earlier step, with `dir="back"`, so the steps keep their forward order. The arrowhead is at the tail, so the `undo` diff --git a/documentation/tutorials/getting-started-with-ash-workflow.md b/documentation/tutorials/getting-started-with-ash-workflow.md index 35315e09..2ad57b0c 100644 --- a/documentation/tutorials/getting-started-with-ash-workflow.md +++ b/documentation/tutorials/getting-started-with-ash-workflow.md @@ -108,7 +108,7 @@ From that DSL, AshWorkflow generates: > > AshWorkflow does not generate one. A workflow record's creation inputs are specific to your application, so the extension leaves `create` to you and only adds the changes that set the initial state and `state_entered_at`. A resource with a `workflow` block and no create action compiles, and then nothing can start a workflow. -`:auto_check` becomes the initial state because it is the first step by declaration order that is not terminal. `AshWorkflow.Entities.Step.find_initial/1` picks it. To name the initial step instead of relying on declaration order, mark it: +`:auto_check` becomes the initial state because it is the first step by declaration order that is not terminal. `AshWorkflow.Entities.Step.find_initials/1` picks it. To name the initial step instead of relying on declaration order, mark it: ```elixir workflow do @@ -127,6 +127,8 @@ end Without `initial true` that workflow would start in `:review`, because `:review` is declared first. A step that declares transitions has to set `initial` inside its block: `step :intake, initial: true do ... end` does not compile, because the DSL macro takes either options or a block. +Several steps can set `initial true` when records start in different places. See [Several initial steps](../topics/automatic-vs-manual-steps.md#several-initial-steps). + ## Use the workflow ```elixir diff --git a/lib/ash_workflow/charts/dot.ex b/lib/ash_workflow/charts/dot.ex index d6040dfd..b95bfa36 100644 --- a/lib/ash_workflow/charts/dot.ex +++ b/lib/ash_workflow/charts/dot.ex @@ -19,7 +19,7 @@ defmodule AshWorkflow.Charts.Dot do | Manual step | Amber box, `✋ manual` under the name | | Wait state | Lavender box with a dashed border, `⏳ wait state` under the name | | Terminal step | Double border. Green, red, amber or grey: see "Terminal steps" | - | Initial step | An edge from a small filled circle | + | Initial step | An edge from a small filled circle, one per initial step | | `on_success` | Thick blue edge, `⚙` and the action | | `on_error` | Red edge, `✖ on_error` | | Timeout | Dashed amber edge, `⏱`, the timeout's name and its deadline | @@ -48,7 +48,7 @@ defmodule AshWorkflow.Charts.Dot do ## Layout - `dot` puts the steps in ranks, from the initial step to the end steps. An + `dot` puts the steps in ranks, from the initial steps to the end steps. An edge that closes a loop, such as a transition back to an earlier step, goes back up the ranks. diff --git a/lib/ash_workflow/charts/graph/node.ex b/lib/ash_workflow/charts/graph/node.ex index 45eb487f..5891dac7 100644 --- a/lib/ash_workflow/charts/graph/node.ex +++ b/lib/ash_workflow/charts/graph/node.ex @@ -11,7 +11,7 @@ defmodule AshWorkflow.Charts.Graph.Node do A timeout is the only way out. * `:terminal` — an end state. - `initial?` is `true` for the step the workflow starts in. `notes` holds what + `initial?` is `true` for each step a record can be created in. `notes` holds what the step does without leaving it, so it has no edge: its policy, its retry policy, the timeouts that run an action, and its `every` entries. """ diff --git a/lib/ash_workflow/charts/mermaid.ex b/lib/ash_workflow/charts/mermaid.ex index 8c1fbd57..e22110aa 100644 --- a/lib/ash_workflow/charts/mermaid.ex +++ b/lib/ash_workflow/charts/mermaid.ex @@ -13,8 +13,8 @@ defmodule AshWorkflow.Charts.Mermaid do * Each step that is not terminal has a description line with its kind: `⚙\u{FE0F} automatic`, `✋ manual` or `⏳ wait state`. The gear carries U+FE0F, so it draws as a colour emoji, the same as the other two. - * The initial step has an edge from `[*]`, and every terminal step has an - edge to `[*]`. + * Every initial step has an edge from `[*]`, and every terminal step has + an edge to `[*]`. * An edge label starts with a symbol for its kind: `⚙` for `on_success`, `✖` for `on_error`, `📨` for an `on_signal`, `⏱` for a timeout and `↶` for undo. A transition has no symbol. A timeout edge gives the timeout's diff --git a/lib/ash_workflow/clarity/content/workflow_overview.ex b/lib/ash_workflow/clarity/content/workflow_overview.ex index 5b2b42e1..4269c6eb 100644 --- a/lib/ash_workflow/clarity/content/workflow_overview.ex +++ b/lib/ash_workflow/clarity/content/workflow_overview.ex @@ -50,9 +50,17 @@ with {:module, _} <- Code.ensure_loaded(Clarity.Content), ] end + defp initial_label([_]), do: "Initial step" + defp initial_label(_), do: "Initial steps" + + defp initial_links(_resource, []), do: "—" + + defp initial_links(resource, nodes), + do: nodes |> Enum.map(&step_link(resource, &1.id)) |> Enum.intersperse(", ") + defp summary(resource, graph) do counts = Enum.frequencies_by(graph.nodes, & &1.kind) - initial = Enum.find(graph.nodes, & &1.initial?) + initial_nodes = Enum.filter(graph.nodes, & &1.initial?) kinds = for kind <- [:automatic, :manual, :wait_state, :terminal], count = counts[kind] do @@ -63,7 +71,7 @@ with {:module, _} <- Code.ensure_loaded(Clarity.Content), ["Property", "Value"], [ ["State attribute", code(Info.state_attribute(resource))], - ["Initial step", if(initial, do: step_link(resource, initial.id), else: "—")], + [initial_label(initial_nodes), initial_links(resource, initial_nodes)], ["Steps", "#{length(graph.nodes)} (#{Enum.join(kinds, ", ")})"], ["Moves", Integer.to_string(Enum.count(graph.edges, &(&1.kind != :undo)))], ["Undo", undo(resource)], diff --git a/lib/ash_workflow/entities/step.ex b/lib/ash_workflow/entities/step.ex index 08b27161..d21b3394 100644 --- a/lib/ash_workflow/entities/step.ex +++ b/lib/ash_workflow/entities/step.ex @@ -49,7 +49,7 @@ defmodule AshWorkflow.Entities.Step do type: :boolean, default: false, doc: - "If true, this step is the initial state. At most one step can be marked initial. If none are, the first non-terminal step by declaration order is used." + "If true, a create action can start a record in this step. Several steps can be marked initial, and the first by declaration order is the state a create starts in when it sets none. If no step is marked, the first non-terminal step by declaration order is the only initial step." ], terminal: [ type: :boolean, @@ -167,12 +167,25 @@ defmodule AshWorkflow.Entities.Step do do: is_nil(List.last(routes).when) @doc """ - Finds the initial step from a list of steps. + Finds the steps a record can be created in. - Returns the step with `initial: true`, or falls back to the first - non-terminal step by declaration order. + Returns every step with `initial: true` in declaration order, or the first + non-terminal step when none is marked. """ - def find_initial(steps) do - Enum.find(steps, & &1.initial) || steps |> Enum.reject(&terminal?/1) |> List.first() + @spec find_initials([t()]) :: [t()] + def find_initials(steps) do + case Enum.filter(steps, & &1.initial) do + [] -> steps |> Enum.reject(&terminal?/1) |> Enum.take(1) + initial_steps -> initial_steps + end end + + @doc """ + Finds the step a record starts in when its create action sets no state. + + Returns the first of `find_initials/1`, or `nil` when the workflow has no + non-terminal step. + """ + @spec find_initial([t()]) :: t() | nil + def find_initial(steps), do: steps |> find_initials() |> List.first() end diff --git a/lib/ash_workflow/info.ex b/lib/ash_workflow/info.ex index 4cb79970..63115694 100644 --- a/lib/ash_workflow/info.ex +++ b/lib/ash_workflow/info.ex @@ -270,13 +270,21 @@ defmodule AshWorkflow.Info do end @doc """ - Returns the initial step for the workflow. + Returns the step a record starts in when its create action sets no state. """ @spec initial_step(Ash.Resource.t()) :: Step.t() | nil def initial_step(resource) do Step.find_initial(steps(resource)) end + @doc """ + Returns every step a record can be created in, in declaration order. + """ + @spec initial_steps(Ash.Resource.t()) :: [Step.t()] + def initial_steps(resource) do + Step.find_initials(steps(resource)) + end + @doc """ Returns the workflow's `transition_log` configuration, or `nil` if no transition log is configured. @@ -482,8 +490,8 @@ defmodule AshWorkflow.Info do * `:action` — the action an automatic step runs, `nil` for every other step * `:policy` — the step's `policy` check, or `nil` * `:retry` — the step's `AshWorkflow.Entities.Retry`, or `nil` - * `:initial` — `true` for the step the workflow starts in, as - `AshWorkflow.Entities.Step.find_initial/1` picks it + * `:initial` — `true` for each step a record can be created in, as + `AshWorkflow.Entities.Step.find_initials/1` picks them * `:terminal` — `true` for an end state * `:manual` — `true` when nothing runs on entry * `:wait_state` — `true` when a timeout is the step's only exit @@ -547,20 +555,20 @@ defmodule AshWorkflow.Info do @spec workflow_graph(Ash.Resource.t()) :: %{atom() => map()} def workflow_graph(resource) do steps = steps(resource) - initial = Step.find_initial(steps) + initial_steps = Step.find_initials(steps) undo_enabled? = undo(resource) != nil - Map.new(steps, &step_to_graph_entry(&1, initial, undo_enabled?)) + Map.new(steps, &step_to_graph_entry(&1, initial_steps, undo_enabled?)) end - defp step_to_graph_entry(step, initial, undo_enabled?) do + defp step_to_graph_entry(step, initial_steps, undo_enabled?) do {step.name, %{ name: step.name, action: step.action, policy: step.policy, retry: step.retry, - initial: step == initial, + initial: step in initial_steps, terminal: Step.terminal?(step), manual: Step.manual?(step), wait_state: Step.wait_state?(step), diff --git a/lib/ash_workflow/transformers/add_state_machine.ex b/lib/ash_workflow/transformers/add_state_machine.ex index 522fc2f1..a4854b18 100644 --- a/lib/ash_workflow/transformers/add_state_machine.ex +++ b/lib/ash_workflow/transformers/add_state_machine.ex @@ -5,9 +5,9 @@ defmodule AshWorkflow.Transformers.AddStateMachine do Injects the following into the resource's `state_machine` DSL: - **`state_attribute`** — the workflow's `state_attribute`, when it declares one. - - **`initial_states`** — set to the step with `initial: true`, or the first + - **`initial_states`** — every step with `initial: true`, or the first non-terminal step by declaration order if none is marked. - - **`default_initial_state`** — same as above + - **`default_initial_state`** — the first of `initial_states` - **Transitions** for each step type: - *Automatic steps* — `transition :step_action, from: [:step_name], to: [...]`, where `to` is every target across the step's `on_success` entries. @@ -43,9 +43,9 @@ defmodule AshWorkflow.Transformers.AddStateMachine do |> Transformer.get_entities([:workflow]) |> Enum.filter(&match?(%Step{}, &1)) - case Step.find_initial(steps) do - nil -> raise no_steps_error() - first_step -> add_state_machine(dsl, steps, first_step) + case Step.find_initials(steps) do + [] -> raise no_steps_error() + initial_steps -> add_state_machine(dsl, steps, initial_steps) end end @@ -63,12 +63,16 @@ defmodule AshWorkflow.Transformers.AddStateMachine do ) end - defp add_state_machine(dsl, steps, first_step) do + defp add_state_machine(dsl, steps, [default_step | _] = initial_steps) do dsl = dsl |> put_state_attribute() - |> Transformer.set_option([:state_machine], :initial_states, [first_step.name]) - |> Transformer.set_option([:state_machine], :default_initial_state, first_step.name) + |> Transformer.set_option( + [:state_machine], + :initial_states, + Enum.map(initial_steps, & &1.name) + ) + |> Transformer.set_option([:state_machine], :default_initial_state, default_step.name) transitions = build_transitions(steps) ++ undo_transitions(dsl) diff --git a/lib/ash_workflow/verifiers/validate_workflow.ex b/lib/ash_workflow/verifiers/validate_workflow.ex index 77001a68..33c4a7e9 100644 --- a/lib/ash_workflow/verifiers/validate_workflow.ex +++ b/lib/ash_workflow/verifiers/validate_workflow.ex @@ -16,12 +16,13 @@ defmodule AshWorkflow.Verifiers.ValidateWorkflow do |> Enum.filter(&match?(%Step{}, &1)) with :ok <- validate_has_steps(steps), - :ok <- validate_single_initial(steps), + :ok <- validate_initial_steps(steps), :ok <- validate_step_configs(steps), :ok <- validate_references(steps), :ok <- validate_timeout_actions(dsl, steps), :ok <- validate_every_actions(dsl, steps), - :ok <- validate_shared_transition_policies(steps) do + :ok <- validate_shared_transition_policies(steps), + :ok <- validate_create_starting_steps(dsl, steps) do validate_reachability(steps) end end @@ -46,35 +47,76 @@ defmodule AshWorkflow.Verifiers.ValidateWorkflow do end end - defp validate_single_initial(steps) do - initial_steps = Enum.filter(steps, & &1.initial) - - case initial_steps do - [_, _ | _] -> - names = Enum.map(initial_steps, & &1.name) + defp validate_initial_steps(steps) do + case Enum.find(steps, &(&1.initial and Step.terminal?(&1))) do + nil -> + :ok + step -> {:error, DslError.exception( - path: [:workflow], - message: "Only one step can have initial: true, but found: #{inspect(names)}" + path: [:workflow, :step, step.name], + message: "Terminal step :#{step.name} cannot have initial: true." )} + end + end - [step] -> - if Step.terminal?(step) do - {:error, - DslError.exception( - path: [:workflow, :step, step.name], - message: "Terminal step :#{step.name} cannot have initial: true." - )} - else - :ok - end + # Checks a literal `transition_state` target at compile time rather than on the first create. + defp validate_create_starting_steps(dsl, steps) do + initial_names = steps |> Step.find_initials() |> Enum.map(& &1.name) + validate_start_targets(create_starting_steps(dsl), initial_names) + end - _ -> + defp validate_start_targets(starts, initial_names) do + case Enum.find(starts, &invalid_start?(&1, initial_names)) do + nil -> :ok + + %{action: action, upsert?: true, target: target} -> + {:error, + DslError.exception( + path: [:actions, :create, action], + message: + "Create action :#{action} upserts and calls transition_state(#{inspect(target)}). ash_state_machine only lets an upsert move to a state that a transition declares for that action, and a workflow declares none for creates. An upserting create starts records in the first initial step. Remove `upsert? true` or the transition_state change." + )} + + %{action: action, target: target} -> + {:error, + DslError.exception( + path: [:actions, :create, action], + message: + "Create action :#{action} starts records in #{inspect(target)}, which is not an initial step. Mark step #{inspect(target)} with `initial true`, or start in one of #{inspect(initial_names)}." + )} end end + defp invalid_start?(%{upsert?: true}, _initial_names), do: true + defp invalid_start?(%{target: target}, _initial_names) when not is_atom(target), do: false + defp invalid_start?(%{target: target}, initial_names), do: target not in initial_names + + defp create_starting_steps(dsl) do + global_changes = + dsl + |> Verifier.get_entities([:changes]) + |> Enum.filter(&(:create in List.wrap(Map.get(&1, :on)))) + + dsl + |> Verifier.get_entities([:actions]) + |> Enum.filter(&match?(%Ash.Resource.Actions.Create{}, &1)) + |> Enum.flat_map(fn action -> + (Map.get(action, :changes, []) ++ global_changes) + |> Enum.flat_map(&transition_state_target/1) + |> Enum.map(&%{action: action.name, upsert?: action.upsert?, target: &1}) + end) + end + + defp transition_state_target(%Ash.Resource.Change{ + change: {AshStateMachine.BuiltinChanges.TransitionState, opts} + }), + do: [Keyword.get(opts, :target)] + + defp transition_state_target(_change), do: [] + defp validate_step_configs(steps) do Enum.reduce_while(steps, :ok, fn step, :ok -> case validate_step(step) do @@ -510,15 +552,16 @@ defmodule AshWorkflow.Verifiers.ValidateWorkflow do end defp validate_reachability(steps) do - case Step.find_initial(steps) do - nil -> :ok - initial -> do_validate_reachability(initial, steps) + case Step.find_initials(steps) do + [] -> :ok + initial_steps -> do_validate_reachability(initial_steps, steps) end end - defp do_validate_reachability(first_step, steps) do + defp do_validate_reachability(initial_steps, steps) do step_map = Map.new(steps, &{&1.name, &1}) - reachable = MapSet.new(bfs([first_step.name], step_map, [])) + initial_names = Enum.map(initial_steps, & &1.name) + reachable = MapSet.new(bfs(initial_names, step_map, [])) all_names = MapSet.new(steps, & &1.name) unreachable = MapSet.difference(all_names, reachable) @@ -531,11 +574,15 @@ defmodule AshWorkflow.Verifiers.ValidateWorkflow do DslError.exception( path: [:workflow], message: - "The following steps are not reachable from the first step :#{first_step.name}: #{inspect(unreachable_list)}" + "The following steps are not reachable from #{describe_initial(initial_names)}: #{inspect(unreachable_list)}" <> + entry_hint(unreachable_list, steps) )} end end + defp describe_initial([name]), do: "the initial step #{inspect(name)}" + defp describe_initial(names), do: "any initial step #{inspect(names)}" + # `visited` is a plain list rather than a MapSet: workflows have a handful of # steps, so the linear membership check costs nothing at compile time. @spec bfs([atom()], %{optional(atom()) => Step.t()}, [atom()]) :: [atom()] @@ -549,26 +596,36 @@ defmodule AshWorkflow.Verifiers.ValidateWorkflow do neighbors = case Map.get(step_map, name) do - nil -> - [] + nil -> [] + step -> successors(step) + end - step -> - successors = - Step.on_success_targets(step) ++ ([step.on_error] |> Enum.reject(&is_nil/1)) + bfs(rest ++ neighbors, step_map, visited) + end + end - transition_targets = - Enum.flat_map(step.transitions, &Transition.all_targets/1) + defp successors(step) do + Step.on_success_targets(step) ++ + Enum.reject([step.on_error], &is_nil/1) ++ + Enum.flat_map(step.transitions, &Transition.all_targets/1) ++ + (step.timeouts |> Enum.map(& &1.transition_to) |> Enum.reject(&is_nil/1)) ++ + (step.on_signals |> Enum.map(& &1.transition_to) |> Enum.reject(&is_nil/1)) + end - timeout_targets = - step.timeouts |> Enum.map(& &1.transition_to) |> Enum.reject(&is_nil/1) + # A step nothing leads into can only be a starting step, so the likely fix is + # `initial true` rather than a missing transition. + defp entry_hint(unreachable_names, steps) do + entered = MapSet.new(Enum.flat_map(steps, &successors/1)) - on_signal_targets = - step.on_signals |> Enum.map(& &1.transition_to) |> Enum.reject(&is_nil/1) + case Enum.reject(unreachable_names, &MapSet.member?(entered, &1)) do + [] -> + "" - successors ++ transition_targets ++ timeout_targets ++ on_signal_targets - end + [name] -> + ". No step leads into #{inspect(name)}. Mark it `initial true` if records start there." - bfs(rest ++ neighbors, step_map, visited) + names -> + ". No step leads into #{inspect(names)}. Mark each one that records start in with `initial true`." end end diff --git a/mix.lock b/mix.lock index 9b3aa4ba..6b763cc9 100644 --- a/mix.lock +++ b/mix.lock @@ -47,7 +47,7 @@ "phoenix_live_view": {:hex, :phoenix_live_view, "1.2.12", "35848150bbab579e9d0aff79525269d7c0801a4f61232b84f635c11222cee88f", [:mix], [{:igniter, ">= 0.6.16 and < 1.0.0-0", [hex: :igniter, repo: "hexpm", optional: true]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:lazy_html, "~> 0.1.0", [hex: :lazy_html, repo: "hexpm", optional: true]}, {:phoenix, "~> 1.6.15 or ~> 1.7.0 or ~> 1.8.0", [hex: :phoenix, repo: "hexpm", optional: false]}, {:phoenix_html, "~> 3.3 or ~> 4.0", [hex: :phoenix_html, repo: "hexpm", optional: false]}, {:phoenix_template, "~> 1.0", [hex: :phoenix_template, repo: "hexpm", optional: false]}, {:phoenix_view, "~> 2.0", [hex: :phoenix_view, repo: "hexpm", optional: true]}, {:plug, "~> 1.15", [hex: :plug, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.2 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "656810d716e3369545dd63981196a5d68b77fdb253afe02ef0c6fa14cfd8dc2b"}, "phoenix_pubsub": {:hex, :phoenix_pubsub, "2.4.1", "2ff3e7ba8b432120989870997b9adaefb76e1f63805554ab0b9e948987981f4b", [:mix], [], "hexpm", "352fba7a87bf61395b6e97da66944ad9b1bfe5459e5981039f60d68270bd9700"}, "phoenix_template": {:hex, :phoenix_template, "1.1.0", "b329582281b1e00e4dc664afd60ef5b489cbb356923caa3b1e00abe8651b9a18", [:mix], [{:phoenix_html, "~> 2.14.2 or ~> 3.0 or ~> 4.0", [hex: :phoenix_html, repo: "hexpm", optional: true]}], "hexpm", "eba70070de79b2c3501ef205a74a69f98ab352f3785aa15da9ed161f9fe0fd5d"}, - "plug": {:hex, :plug, "1.20.3", "56c480c633ec2ce10140e236e15233bf576e1d323887d7c96711bd02ab5160db", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_crypto, "~> 1.1.1 or ~> 1.2 or ~> 2.0", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.3 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "be266aee1b8536ef6409d58cf39a3121319f0ec47cfa1b24024485aa0e76ad76"}, + "plug": {:hex, :plug, "1.20.4", "8fca521b31eb586dbb91968dd9fa95be6b60fb40f9ca77b005361e06836aed75", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_crypto, "~> 1.1.1 or ~> 1.2 or ~> 2.0", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.3 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "96ee42c0b8b35bcb14e3e65afb85abe9bb7745a8576e8c602802bbb01e5acf72"}, "plug_crypto": {:hex, :plug_crypto, "2.2.1", "bd1d0358a2e2f5ffb818217e64c394f9d24ed191d862b7fa1bcce264ace2b8ea", [:mix], [], "hexpm", "4417ccbd8f85e627321cd07d2ab9c4b621f1fd883b9905af241f9b4b780b94b6"}, "postgrex": {:hex, :postgrex, "0.22.4", "d271f595dfd25230b6398354e19d17bb5e2d20130fd2d9bdca7e15f125d43552", [:mix], [{:db_connection, "~> 2.9", [hex: :db_connection, repo: "hexpm", optional: false]}, {:decimal, "~> 1.5 or ~> 2.0 or ~> 3.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:table, "~> 0.1.0", [hex: :table, repo: "hexpm", optional: true]}], "hexpm", "4aae45a2d60e35b04eea2602440be152fae332901f1fc7a60fc7cb7f0f9a9c5a"}, "reactor": {:hex, :reactor, "1.0.7", "804bd237609df9162d7c61f68c6243722ef3ea2f9c48e693a04b7f09cf99e4d6", [:mix], [{:igniter, "~> 0.4", [hex: :igniter, repo: "hexpm", optional: true]}, {:iterex, "~> 0.1", [hex: :iterex, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:multigraph, "~> 0.16.1-mg.2", [hex: :multigraph, repo: "hexpm", optional: false]}, {:spark, ">= 2.3.3 and < 3.0.0-0", [hex: :spark, repo: "hexpm", optional: false]}, {:splode, "~> 0.2", [hex: :splode, repo: "hexpm", optional: false]}, {:telemetry, "~> 1.2", [hex: :telemetry, repo: "hexpm", optional: false]}, {:yaml_elixir, "~> 2.11", [hex: :yaml_elixir, repo: "hexpm", optional: false]}, {:ymlr, "~> 5.0", [hex: :ymlr, repo: "hexpm", optional: false]}], "hexpm", "d5eddbdcdf1016d76d713c927741f6db21421271cea015b0d355d6b1097206a4"}, @@ -60,7 +60,7 @@ "spitfire": {:hex, :spitfire, "0.4.3", "83aa224f713966769644772a814a67b26df518d25059b3855c23a2f7b531937a", [:mix], [], "hexpm", "4f771bbdf00fe6eda6e2a7e488c42ead48142fea697349510a41fabb41376632"}, "splode": {:hex, :splode, "0.3.3", "420917ee2373c5db8462417ea6faa8cbeb8deec7b18ae5dd2fa07c67f883f25a", [:mix], [], "hexpm", "3f98c7799ec8960f816b4ccc5cc6a5d2b72a20ad3f8fff9199fb530194ad9f50"}, "stream_data": {:hex, :stream_data, "1.4.0", "026f929db613aabea6208012ae9b8970d3fd5f88b3bdf26831bc536f98c42036", [:mix], [], "hexpm", "2b0ee3a340dcce1c8cf6302a763ee757d1e01c54d6e16d9069062509d68b1dc9"}, - "telemetry": {:hex, :telemetry, "1.4.2", "a0cb522801dffb1c49fe6e30561badffc7b6d0e180db1300df759faa22062855", [:rebar3], [], "hexpm", "928f6495066506077862c0d1646609eed891a4326bee3126ba54b60af61febb1"}, + "telemetry": {:hex, :telemetry, "1.4.3", "d0333fa869361e6833d6ff8e806ff4d8553fe1332fcce0af86c7381951a1dc2f", [:rebar3], [], "hexpm", "17a63581cf2e832a238287f5fe6811e8ca1f333249f1376ad653164a3c4770d4"}, "telemetry_registry": {:hex, :telemetry_registry, "0.3.2", "701576890320be6428189bff963e865e8f23e0ff3615eade8f78662be0fc003c", [:mix, :rebar3], [{:telemetry, "~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "e7ed191eb1d115a3034af8e1e35e4e63d5348851d556646d46ca3d1b4e16bab9"}, "text_diff": {:hex, :text_diff, "0.1.0", "1caf3175e11a53a9a139bc9339bd607c47b9e376b073d4571c031913317fecaa", [:mix], [], "hexpm", "d1ffaaecab338e49357b6daa82e435f877e0649041ace7755583a0ea3362dbd7"}, "tz": {:hex, :tz, "0.28.4", "f5433914dcf8619d593979ec65bbe878158cad818bc2b53b44d9e4bda509753f", [:mix], [{:castore, "~> 0.1 or ~> 1.0", [hex: :castore, repo: "hexpm", optional: true]}, {:mint, "~> 1.6", [hex: :mint, repo: "hexpm", optional: true]}], "hexpm", "72fe8d526cf30fcc4e07cec4ceb583ba5f2d69c6334c9533419c836a6acd1c56"}, diff --git a/test/ash_workflow/initial_step_test.exs b/test/ash_workflow/initial_step_test.exs index 8a064371..cf298a6a 100644 --- a/test/ash_workflow/initial_step_test.exs +++ b/test/ash_workflow/initial_step_test.exs @@ -4,6 +4,9 @@ defmodule AshWorkflow.InitialStepTest do import AshWorkflowTest.DslAssertions alias AshStateMachine.Info, as: SMInfo + alias AshWorkflow.Charts.Graph + alias AshWorkflow.Charts.Mermaid + alias AshWorkflow.Info describe "initial: true flag" do test "step with initial: true becomes the initial state, overriding declaration order" do @@ -18,11 +21,62 @@ defmodule AshWorkflow.InitialStepTest do end end + describe "several initial steps" do + alias AshWorkflowTest.MultipleInitialWorkflow + + test "every marked step is an initial state, and the first is the default" do + assert {:ok, [:start_one, :start_two]} = + SMInfo.state_machine_initial_states(MultipleInitialWorkflow) + + assert {:ok, :start_one} = + SMInfo.state_machine_default_initial_state(MultipleInitialWorkflow) + end + + test "a create that sets no state starts in the default initial step" do + {:ok, record} = MultipleInitialWorkflow.create(%{title: "test"}) + assert record.state == :start_one + end + + test "a create can start in another initial step with transition_state" do + {:ok, record} = MultipleInitialWorkflow.create_at_start_two(%{title: "test"}) + assert record.state == :start_two + + {:ok, finished} = Ash.update(record, %{}, action: :finish) + assert finished.state == :done + end + + test "Info lists every initial step and keeps the first as the default" do + assert Enum.map(Info.initial_steps(MultipleInitialWorkflow), & &1.name) == + [:start_one, :start_two] + + assert Info.initial_step(MultipleInitialWorkflow).name == :start_one + end + + test "workflow_graph marks every initial step" do + graph = Info.workflow_graph(MultipleInitialWorkflow) + + assert graph[:start_one].initial + assert graph[:start_two].initial + refute graph[:done].initial + end + + test "the Mermaid chart draws a start edge to every initial step" do + output = + MultipleInitialWorkflow + |> Graph.build() + |> Mermaid.render([]) + |> IO.iodata_to_binary() + + assert output =~ "[*] --> step_start_one" + assert output =~ "[*] --> step_start_two" + end + end + describe "verifier" do - test "rejects a workflow where multiple steps have initial: true" do + test "rejects a step no initial step reaches" do assert_dsl_error( """ - defmodule MultipleInitialWorkflow do + defmodule StrandedFromInitialsWorkflow do use Ash.Resource, domain: AshWorkflowTest.Domain, data_layer: Ash.DataLayer.Ets, @@ -31,7 +85,7 @@ defmodule AshWorkflow.InitialStepTest do workflow do step :step_a do initial true - transition :go, to: :step_b + transition :finish, to: :done end step :step_b do @@ -39,19 +93,148 @@ defmodule AshWorkflow.InitialStepTest do transition :finish, to: :done end + step :stranded do + transition :finish, to: :done + end + step :done, terminal: true end + actions do + create :create_at_b do + change transition_state(:step_b) + end + end + attributes do uuid_v7_primary_key :id attribute :title, :string, allow_nil?: false end end """, - ~r/Only one step can have initial: true/ + ~r/not reachable from any initial step \[:step_a, :step_b\]: \[:stranded\]\. No step leads into :stranded\. Mark it `initial true`/ + ) + end + + test "rejects a create that starts records in a step that is not initial" do + assert_dsl_error( + """ + defmodule CreateIntoNonInitialWorkflow do + use Ash.Resource, + domain: AshWorkflowTest.Domain, + data_layer: Ash.DataLayer.Ets, + extensions: [AshWorkflow, AshOban] + + workflow do + step :draft do + transition :submit, to: :review + end + + step :review do + transition :approve, to: :done + end + + step :done, terminal: true + end + + actions do + create :create_in_review do + change transition_state(:review) + end + end + + attributes do + uuid_v7_primary_key :id + end + end + """, + ~r/Create action :create_in_review starts records in :review, which is not an initial step/ + ) + end + + test "rejects an upserting create that names its starting step" do + assert_dsl_error( + """ + defmodule UpsertIntoInitialWorkflow do + use Ash.Resource, + domain: AshWorkflowTest.Domain, + data_layer: Ash.DataLayer.Ets, + extensions: [AshWorkflow, AshOban] + + workflow do + step :start_one do + initial true + transition :finish, to: :done + end + + step :start_two do + initial true + transition :finish, to: :done + end + + step :done, terminal: true + end + + identities do + identity :unique_key, [:key], pre_check_with: AshWorkflowTest.Domain + end + + actions do + create :upsert_at_two do + accept [:key] + upsert? true + upsert_identity :unique_key + change transition_state(:start_two) + end + end + + attributes do + uuid_v7_primary_key :id + attribute :key, :string, allow_nil?: false, public?: true + end + end + """, + ~r/Create action :upsert_at_two upserts and calls transition_state\(:start_two\)/ ) end + test "accepts a later initial step that no create names with transition_state" do + defmodule SetAttributeStartWorkflow do + use Ash.Resource, + domain: AshWorkflowTest.Domain, + data_layer: Ash.DataLayer.Ets, + extensions: [AshWorkflow, AshOban], + validate_domain_inclusion?: false + + workflow do + step :start_one do + initial true + transition :finish, to: :done + end + + step :start_two do + initial true + transition :finish, to: :done + end + + step :done, terminal: true + end + + actions do + create :create_at_two do + change set_attribute(:state, :start_two) + end + end + + attributes do + uuid_v7_primary_key :id + end + end + + assert {:ok, [:start_one, :start_two]} = + SMInfo.state_machine_initial_states(SetAttributeStartWorkflow) + end + test "rejects a terminal step marked initial: true" do assert_dsl_error( """ diff --git a/test/ash_workflow/multiple_initial_runtime_test.exs b/test/ash_workflow/multiple_initial_runtime_test.exs new file mode 100644 index 00000000..25718f22 --- /dev/null +++ b/test/ash_workflow/multiple_initial_runtime_test.exs @@ -0,0 +1,158 @@ +defmodule AshWorkflow.MultipleInitialRuntimeTest do + @moduledoc """ + A create that names a later initial step with `transition_state/1` starts + there exactly as a create into the default initial step would. + """ + use AshWorkflowTest.EtsCase, async: true + use Oban.Testing, repo: AshWorkflowTest.Repo, prefix: "public" + + import Ash.Signals.Test + + alias AshWorkflow.Charts.Dot + alias AshWorkflow.Charts.Graph + alias AshWorkflow.Charts.Json + alias AshWorkflow.Clarity.Content.WorkflowOverview + alias AshWorkflowTest.MultipleInitialRuntimeWorkflow, as: Workflow + alias AshWorkflowTest.MultipleInitialSignals, as: Signals + alias Clarity.Vertex.Ash.Resource, as: ResourceVertex + + defp reload(record), do: Ash.get!(Workflow, record.id, authorize?: false) + + defp trigger(name) do + Workflow + |> AshOban.Info.oban_triggers() + |> Enum.find(&(&1.name == name)) + end + + defp intake_worker, + do: Enum.find(AshOban.Info.oban_triggers(Workflow), &(&1.action == :process_intake)).worker + + defp matching_ids(trigger) do + Workflow + |> Ash.Query.do_filter(trigger.where) + |> Ash.read!() + |> Enum.map(& &1.id) + end + + defp backdate!(record, days_ago) do + record + |> Ash.Changeset.for_update(:touch, %{}) + |> Ash.Changeset.force_change_attribute( + :state_entered_at, + DateTime.add(DateTime.utc_now(), -days_ago, :day) + ) + |> Ash.update!() + end + + describe "the transition log" do + test "a create into a later initial step writes an :initial row to that step with no from_state" do + record = Workflow.create_at_parked!(%{title: "test"}) + + assert [row] = Workflow.history(record) + assert row.from_state == nil + assert row.to_state == :parked + assert row.transition_name == :create_at_parked + assert row.triggered_by == :initial + end + end + + describe "step emits" do + setup :capture_signals + + test "a create into a later initial step emits that step's signal and not the first step's" do + %{id: id} = Workflow.create_at_intake!(%{title: "test"}) + + assert_signal_emitted(Signals, :intake_started, %{id: ^id, to_state: :intake}) + refute_signal_emitted(Signals, :drafting_started) + end + end + + describe "an automatic later initial step" do + test "a create into it queues its action" do + record = Workflow.create_at_intake!(%{title: "test"}) + + assert_enqueued(worker: intake_worker(), args: %{"primary_key" => %{"id" => record.id}}) + end + + test "running the queued job moves the record on" do + record = Workflow.create_at_intake!(%{title: "test"}) + + assert %{success: 1} = Oban.drain_queue(queue: :workflow) + assert reload(record).state == :review + end + end + + describe "a wait-state later initial step" do + test "its timeout matches only once state_entered_at is older than fire_after" do + record = Workflow.create_at_parked!(%{title: "test"}) + release = trigger(:__timeout_trigger_parked_release) + + refute record.id in matching_ids(release) + + backdate!(record, 4) + assert record.id in matching_ids(release) + end + + test "the timeout moves the record to its target" do + record = Workflow.create_at_parked!(%{title: "test"}) + + record = Ash.update!(record, action: :__timeout_parked_release) + assert record.state == :drafting + end + end + + describe "an initial step another step leads into" do + test "a record can start there and return there" do + record = Workflow.create_at_intake!(%{title: "test"}) + record = Ash.update!(record, action: :process_intake) + record = Ash.update!(record, action: :reopen) + + assert record.state == :intake + + assert Enum.map(Workflow.history(record), &{&1.from_state, &1.to_state, &1.triggered_by}) == + [ + {nil, :intake, :initial}, + {:intake, :review, :automatic}, + {:review, :intake, :manual} + ] + end + end + + describe "charts" do + test "the JSON graph marks every initial step" do + initial = + for node <- Json.to_map(Graph.build(Workflow))["nodes"], node["initial"], do: node["id"] + + assert initial == ["drafting", "intake", "parked"] + end + + test "the DOT graph draws a start edge to every initial step" do + dot = Workflow |> Graph.build() |> Dot.render([]) |> IO.iodata_to_binary() + + assert dot =~ ~s("start" -> "step_drafting";) + assert dot =~ ~s("start" -> "step_intake";) + assert dot =~ ~s("start" -> "step_parked";) + end + end + + describe "the Clarity workflow overview" do + test "lists every initial step under the plural label" do + {:markdown, render} = + WorkflowOverview.render_static( + %ResourceVertex{resource: Workflow}, + nil + ) + + row = + render.(%{}) + |> IO.iodata_to_binary() + |> String.split("\n") + |> Enum.find(&String.contains?(&1, "Initial step")) + + assert row =~ "Initial steps" + assert row =~ "`drafting`" + assert row =~ "`intake`" + assert row =~ "`parked`" + end + end +end diff --git a/test/ash_workflow/verifiers/validate_workflow_test.exs b/test/ash_workflow/verifiers/validate_workflow_test.exs index 95f06f77..55fbc0dc 100644 --- a/test/ash_workflow/verifiers/validate_workflow_test.exs +++ b/test/ash_workflow/verifiers/validate_workflow_test.exs @@ -579,7 +579,7 @@ defmodule AshWorkflow.Verifiers.ValidateWorkflowTest do ]) assert {:error, %Spark.Error.DslError{message: message}} = ValidateWorkflow.verify(dsl) - assert message =~ "not reachable from the first step" + assert message =~ "not reachable from the initial step :start" assert message =~ ":orphan" end diff --git a/test/ash_workflow/wait_state_test.exs b/test/ash_workflow/wait_state_test.exs index 2f2f8716..2f43167b 100644 --- a/test/ash_workflow/wait_state_test.exs +++ b/test/ash_workflow/wait_state_test.exs @@ -278,7 +278,7 @@ defmodule AshWorkflow.WaitStateTest do end end """, - ~r/not reachable from the first step :review: \[:stranded\]/ + ~r/not reachable from the initial step :review: \[:stranded\]/ ) end diff --git a/test/support/domain.ex b/test/support/domain.ex index 1fab1d73..d5aebf40 100644 --- a/test/support/domain.ex +++ b/test/support/domain.ex @@ -21,6 +21,7 @@ defmodule AshWorkflowTest.Domain do resource AshWorkflowTest.AcceptWorkflow resource AshWorkflowTest.AcceptedRouteWorkflow resource AshWorkflowTest.InitialFlagWorkflow + resource AshWorkflowTest.MultipleInitialWorkflow resource AshWorkflowTest.DerivedTerminalWorkflow resource AshWorkflowTest.RepeatingTimeoutWorkflow resource AshWorkflowTest.EveryUntilWorkflow @@ -90,5 +91,7 @@ defmodule AshWorkflowTest.Domain do resource AshWorkflowTest.OrderWorkflow resource AshWorkflowTest.AuthorizedOrderWorkflow resource AshWorkflowTest.Payment + resource AshWorkflowTest.MultipleInitialRuntimeWorkflow + resource AshWorkflowTest.MultipleInitialRuntimeLog end end diff --git a/test/support/workflows/multiple_initial_runtime_log.ex b/test/support/workflows/multiple_initial_runtime_log.ex new file mode 100644 index 00000000..d8d32b6d --- /dev/null +++ b/test/support/workflows/multiple_initial_runtime_log.ex @@ -0,0 +1,34 @@ +defmodule AshWorkflowTest.MultipleInitialRuntimeLog do + @moduledoc """ + The transition log for `AshWorkflowTest.MultipleInitialRuntimeWorkflow`. + """ + + use Ash.Resource, + domain: AshWorkflowTest.Domain, + data_layer: Ash.DataLayer.Ets + + actions do + defaults [:read] + + create :create do + accept [:workflow_id, :from_state, :to_state, :transition_name, :occurred_at, :triggered_by] + end + end + + attributes do + uuid_v7_primary_key :id + attribute :from_state, :atom, public?: true + attribute :to_state, :atom, allow_nil?: false, public?: true + attribute :transition_name, :atom, allow_nil?: false, public?: true + attribute :occurred_at, :utc_datetime_usec, allow_nil?: false, public?: true + attribute :triggered_by, :atom, allow_nil?: false, public?: true + end + + relationships do + belongs_to :workflow, AshWorkflowTest.MultipleInitialRuntimeWorkflow, + allow_nil?: false, + public?: true, + attribute_public?: true, + attribute_writable?: true + end +end diff --git a/test/support/workflows/multiple_initial_runtime_workflow.ex b/test/support/workflows/multiple_initial_runtime_workflow.ex new file mode 100644 index 00000000..24d70800 --- /dev/null +++ b/test/support/workflows/multiple_initial_runtime_workflow.ex @@ -0,0 +1,86 @@ +defmodule AshWorkflowTest.MultipleInitialRuntimeWorkflow do + @moduledoc """ + Workflow with three initial steps, used to show a create can start in any of + them: a manual step, an automatic step and a wait state. `:intake` is also + reached from `:review` by `reopen`. + + start → drafting ──(submit)──→ intake + start → intake ──(process_intake)──→ review ──(approve)──→ done + └─(reopen)───→ intake + start → parked ── after 3 days ──→ drafting + """ + + use Ash.Resource, + domain: AshWorkflowTest.Domain, + data_layer: Ash.DataLayer.Ets, + extensions: [AshWorkflow, AshOban] + + workflow do + signals AshWorkflowTest.MultipleInitialSignals + + transition_log AshWorkflowTest.MultipleInitialRuntimeLog + + step :drafting do + initial true + emit :drafting_started + transition :submit, to: :intake + end + + step :intake do + initial true + emit :intake_started + action :process_intake + on_success :review + end + + step :parked do + initial true + timeout :release, fire_after: {3, :days}, transition_to: :drafting + end + + step :review do + transition :approve, to: :done + transition :reopen, to: :intake + end + + step :done, terminal: true + end + + code_interface do + define :create + define :create_at_intake + define :create_at_parked + end + + actions do + defaults [:read] + + create :create do + primary? true + accept [:title] + end + + create :create_at_intake do + accept [:title] + change transition_state(:intake) + end + + create :create_at_parked do + accept [:title] + change transition_state(:parked) + end + + update :process_intake do + accept [] + end + + update :touch do + accept [] + end + end + + attributes do + uuid_v7_primary_key :id + attribute :title, :string, allow_nil?: false, public?: true + end +end diff --git a/test/support/workflows/multiple_initial_signals.ex b/test/support/workflows/multiple_initial_signals.ex new file mode 100644 index 00000000..1fb85497 --- /dev/null +++ b/test/support/workflows/multiple_initial_signals.ex @@ -0,0 +1,19 @@ +defmodule AshWorkflowTest.MultipleInitialSignals do + @moduledoc """ + Signals emitted by `AshWorkflowTest.MultipleInitialRuntimeWorkflow` on entering + its initial steps. + """ + use Ash.Signals + + signals do + signal :drafting_started do + argument :id, :uuid, allow_nil?: false + argument :to_state, :atom, allow_nil?: false + end + + signal :intake_started do + argument :id, :uuid, allow_nil?: false + argument :to_state, :atom, allow_nil?: false + end + end +end diff --git a/test/support/workflows/multiple_initial_workflow.ex b/test/support/workflows/multiple_initial_workflow.ex new file mode 100644 index 00000000..e83240a8 --- /dev/null +++ b/test/support/workflows/multiple_initial_workflow.ex @@ -0,0 +1,51 @@ +defmodule AshWorkflowTest.MultipleInitialWorkflow do + @moduledoc """ + Workflow with two initial steps, neither reachable from the other. + + start → start_one ──(finish)──→ done + start → start_two ──(finish)──→ done + + `:create` starts in `:start_one`, the first initial step by declaration + order. `:create_at_start_two` names the other one. + """ + + use Ash.Resource, + domain: AshWorkflowTest.Domain, + data_layer: Ash.DataLayer.Ets, + extensions: [AshWorkflow, AshOban] + + workflow do + step :start_one do + initial true + transition :finish, to: :done + end + + step :start_two do + initial true + transition :finish, to: :done + end + + step :done, terminal: true + end + + code_interface do + define :create + define :create_at_start_two + end + + actions do + create :create do + accept [:title] + end + + create :create_at_start_two do + accept [:title] + change transition_state(:start_two) + end + end + + attributes do + uuid_v7_primary_key :id + attribute :title, :string, allow_nil?: false + end +end diff --git a/usage-rules.md b/usage-rules.md index a80edf93..1045e5d5 100644 --- a/usage-rules.md +++ b/usage-rules.md @@ -89,7 +89,7 @@ Call `AshWorkflow.Scheduler.execute/3` when the moment arrives. It runs the acti ## Defining a Workflow -All workflow configuration goes inside a single `workflow do ... end` block. Steps are declared in order — the first non-terminal step becomes the initial state. +All workflow configuration goes inside a single `workflow do ... end` block. Steps are declared in order. The first non-terminal step becomes the initial state unless one or more steps set `initial true`. A step that declares no action, no transitions, no timeouts, no `on_success` and no `on_error` is terminal, whether or not it sets `terminal: true`. Setting it states the intent, and the verifier then rejects the step if it grows an outgoing declaration. @@ -712,12 +712,14 @@ AshWorkflow validates your workflow at compile time and raises clear errors for: - An automatic step declaring no `on_success` - More than one unconditional `on_success` on a step, or an unconditional `on_success` declared before a conditional one (it would shadow it) - An automatic step whose `on_success` is entirely conditional (no trailing unconditional fallback) and declares neither `on_error` nor a timeout with `transition_to` -- Unreachable steps (not connected to the first step via any path) +- Unreachable steps (not connected to any initial step via any path) +- A create action whose `transition_state` names a step that is not initial +- An upserting create action that calls `transition_state` ## Important Caveats - **Do not add `AshStateMachine` or `AshOban` to your extensions list** — AshWorkflow injects their DSL automatically. Adding them manually will cause conflicts. - **Shared transition names merge** — same-named transitions across steps become one action that routes based on current state. -- **The first non-terminal step is the initial state** — order matters for the first step. +- **The first non-terminal step is the initial state unless a step sets `initial true`.** Several steps can set it. A create that sets no state starts in the first of them, and `change transition_state(:step)` starts a record in another. An upserting create cannot call `transition_state`, and the compiler rejects one that does. - **Automatic steps use Oban** — ensure your application has Oban configured and running. - **`state_entered_at` is managed automatically** — do not set it manually in your actions.