PacketFlow.DSL.Reactor (packetflow v0.1.0)

DSL for defining PacketFlow reactors with state management and message processing

Summary

Functions

Define a reactor with state management and message processing

Define a simple reactor with basic state management

Functions

defreactor(name, list)

(macro)

Define a reactor with state management and message processing

Example

defreactor FileSystemReactor do
  @initial_state %{files: %{}, operations: []}
  @capabilities [FileSystemCap.read, FileSystemCap.write, FileSystemCap.delete]

  def start_link(opts \ []) do
    GenServer.start_link(__MODULE__, opts, name: __MODULE__)
  end

  def init(opts) do
    state = Keyword.get(opts, :initial_state, @initial_state)
    {:ok, state}
  end

  def handle_call({:process_intent, intent}, _from, state) do
    case process_intent(intent, state) do
      {:ok, new_state, effects} ->
        {:reply, {:ok, effects}, new_state}
      {:error, reason} ->
        {:reply, {:error, reason}, state}
    end
  end

  def process_intent(intent, state) do
    case intent do
      %FileReadIntent{} ->
        handle_file_read(intent, state)
      %FileWriteIntent{} ->
        handle_file_write(intent, state)
      _ ->
        {:error, :unsupported_intent}
    end
  end

  defp handle_file_read(intent, state) do
    case Map.get(state.files, intent.path) do
      nil ->
        {:error, :file_not_found}
      content ->
        new_state = update_in(state, [:operations], &[intent | &1])
        {:ok, new_state, []}
    end
  end

  defp handle_file_write(intent, state) do
    new_state = state
    |> update_in([:files], &Map.put(&1, intent.path, intent.content))
    |> update_in([:operations], &[intent | &1])
    {:ok, new_state, []}
  end
end

defsimple_reactor(name, state_fields, list)

(macro)

Define a simple reactor with basic state management

Example

defsimple_reactor CounterReactor, [:count] do
  @capabilities [CounterCap.increment, CounterCap.decrement]

  def process_intent(intent, state) do
    case intent do
      %IncrementIntent{} ->
        new_state = update_in(state, [:count], &(&1 + 1))
        {:ok, new_state, []}
      %DecrementIntent{} ->
        new_state = update_in(state, [:count], &(&1 - 1))
        {:ok, new_state, []}
      _ ->
        {:error, :unsupported_intent}
      end
    end
  end
end