Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mikehostetler/786adb815ffbe857f6e7bc03106cabd2 to your computer and use it in GitHub Desktop.
Save mikehostetler/786adb815ffbe857f6e7bc03106cabd2 to your computer and use it in GitHub Desktop.
Parallel Jido Actions
defmodule Jido.Actions.ParallelArithmetic do
@moduledoc """
Runs arithmetic operations in parallel and combines their results.
"""
use Jido.Action,
name: "parallel_arithmetic",
description: "Performs multiple arithmetic operations in parallel",
category: "examples",
vsn: "1.0.0",
schema: [
input: [type: :integer, required: true, doc: "Base number"],
add_amount: [type: :integer, required: true, doc: "Addition amount"],
multiply_amount: [type: :integer, required: true, doc: "Multiplication factor"]
]
alias Jido.Exec
alias Jido.Actions.Arithmetic.{Add, Multiply, Square}
@impl true
def run(%{input: input, add_amount: add, multiply_amount: mult}, context) do
# Define operations and expected keys in result
operations = [
{Add, %{value: input, amount: add}, :addition},
{Multiply, %{value: input, amount: mult}, :multiplication},
{Square, %{value: input}, :square}
]
# Run operations and collect results
results =
operations
|> Enum.map(fn {action, params, key} ->
task = Exec.run_async(action, params, context)
{task, key}
end)
|> Enum.map(fn {task, key} ->
case Exec.await(task) do
{:ok, %{result: value}} -> {:ok, {key, value}}
error -> error
end
end)
# Check if all operations succeeded
case Enum.split_with(results, &match?({:ok, _}, &1)) do
{successes, []} ->
# All operations succeeded
result_map =
successes
|> Enum.map(fn {:ok, {key, value}} -> {key, value} end)
|> Map.new()
|> Map.put(:input, input)
{:ok, result_map}
{_, [error | _]} ->
# At least one operation failed
{:error, "Parallel operation failed: #{inspect(error)}"}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment