diff --git a/examples/ecto_integration/test/ecto_integration_test.exs b/examples/ecto_integration/test/ecto_integration_test.exs index 2c6d033..4eadc12 100644 --- a/examples/ecto_integration/test/ecto_integration_test.exs +++ b/examples/ecto_integration/test/ecto_integration_test.exs @@ -5,7 +5,7 @@ defmodule EctoIntegration.Test do alias EctoIntegration.Data.{Post, Post.EventLog} alias EctoIntegration.Repo - setup_all do + setup do uuid = Ecto.UUID.generate() post = Post.create(%{id: uuid, title: "Post 1", body: "Body 1"}) @@ -91,4 +91,28 @@ defmodule EctoIntegration.Test do } ] = post.(uuid).event_log |> Enum.sort() end + + test "loading a persisted struct starts the FSM with correct current state", setup_attrs do + %{uuid: uuid, post: _post} = setup_attrs + post = fn uuid -> Post |> Repo.get(uuid) |> Repo.preload(:event_log) end + state = &Finitomata.state/1 + + # update data in database directly + {:ok, published_post} = + post.(uuid) + |> Ecto.Changeset.cast(%{state: :published}, [:state]) + |> Repo.update() + + assert published_post.state == :published + + # kill the FSM process + pid = Finitomata.fqn(nil, uuid) |> GenServer.whereis() + assert is_pid(pid) + assert Process.exit(pid, :kill) + Process.sleep(100) + + # re-fetch data, which will start the FSM + assert post.(uuid).state == :published + assert state.(uuid).current == :published + end end diff --git a/lib/finitomata.ex b/lib/finitomata.ex index 8b37ad1..2b418dd 100644 --- a/lib/finitomata.ex +++ b/lib/finitomata.ex @@ -803,13 +803,15 @@ defmodule Finitomata do :ignore -> {lifecycle, payload} end - state = %State{ - name: name, - lifecycle: lifecycle, - persistency: Map.get(init_arg, :persistency, nil), - timer: @__config__[:timer], - payload: payload - } + state = + %State{ + name: name, + lifecycle: lifecycle, + persistency: Map.get(init_arg, :persistency, nil), + timer: @__config__[:timer], + payload: payload + } + |> put_current_state_if_loaded(lifecycle, payload) :persistent_term.put({Finitomata, state.name}, state.payload) @@ -822,6 +824,10 @@ defmodule Finitomata do {:ok, state, {:continue, {:transition, event_payload({@__config__[:entry], nil})}}} end + defp put_current_state_if_loaded(state, lifecycle, payload) do + if lifecycle == :loaded, do: Map.put(state, :current, payload.state), else: state + end + @doc false @impl GenServer def handle_call(:state, _from, state), do: {:reply, state, state} diff --git a/stuff/fsm.md b/stuff/fsm.md index 7076650..90ec7f2 100644 --- a/stuff/fsm.md +++ b/stuff/fsm.md @@ -16,7 +16,7 @@ I’m a big fan of [Finite Automata](https://en.wikipedia.org/wiki/Finite-state_ This library leverages the power of _callbacks_ to not only completely cover the _FSM_ implementation, but also provide a compile-time proof the _FSM_ is valid and functional. One of the most important things this library provides is the _FSM_ description itself, that is fault-tolerant, not error-prone, and easy to grasp. The _FSM_ definition, which is currently supported in both [PlantUML](https://plantuml.com/en/state-diagram) and [Mermaid](https://mermaid.live) syntaxes, would be drawn in the generated docs of the project using this library. -The consumer of this library initiates a transition by calling somewhat like `transition(object, event)`, then the `GenServer` does its magic and the callback `on_transition/4` gets called. From inside this callback, the consumer implements the business logic and returns the result (the next state to move the _FSM_ to.) There are also syntactic sugar callbacks `on_enter/2`, `on_exit/2`, `on_failure/2`, and `on_terminate/1` to allow easy state change reactions, handling of errors, and a final cleanup respectively. +The consumer of this library initiates a transition by calling somewhat like `transition(object, event)`, then the `GenServer` does its magic and the callback `on_transition/4` gets called. From inside this callback, the consumer implements the business logic and returns the result (the next state to move the _FSM_ to.) There are also syntactic sugar callbacks `on_enter/2`, `on_exit/2`, `on_failure/3`, and `on_terminate/1` to allow easy state change reactions, handling of errors, and a final cleanup respectively. All the callbacks do have a default implementation, which would perfectly handle transitions having a single to state and not requiring any additional business logic attached. When needed, this might be turned off. @@ -26,7 +26,7 @@ Upon start, _FSM_ moves to its _initial state_ and sits there awaiting for the t This library has a compilation-time guarantee the _FSM_ is valid, e. g. has the only one begin state, has at least one end state, all states can be reached, _and_ all the necessary callbacks are defined. That said, if we an _FSM_ has an event initiating transitions from the same state to two different states, and there is no `on_transition/4` clause covering that case, the compile-time error would be raised. On the other hand, if the transition is predetermined and might lead to the only one state, the callback implementation is not mandatory, because there is no trolley problem between these two states. -The _FSM_ definition allows event names, terminated with bangs and/or question marks. If the event name is terminated with a bang (`init!`,) **and this event is the only one possible from this state,** the event will be called automatically once _FSM_ enters this state. This is handy for moving through initialization or through states which do not require a consumer intervention and might be done immediately after _FSM_ reaches the respective state. If the transition failed in any way (the state has not been left either due to `{:error, any()}` response received from `on_transition/4` _or_ due to other unexpected issue, like if `on_transition/4` raised,) the `on_failure/2` callback would be called and the warning would be printed to the log. To suppress this behaviour and to allow a transition silently fail, the event should have ended with a question mark (`try_call?`.) The event cannot have both a bang and a question mark in its name. +The _FSM_ definition allows event names, terminated with bangs and/or question marks. If the event name is terminated with a bang (`init!`,) **and this event is the only one possible from this state,** the event will be called automatically once _FSM_ enters this state. This is handy for moving through initialization or through states which do not require a consumer intervention and might be done immediately after _FSM_ reaches the respective state. If the transition failed in any way (the state has not been left either due to `{:error, any()}` response received from `on_transition/4` _or_ due to other unexpected issue, like if `on_transition/4` raised,) the `on_failure/3` callback would be called and the warning would be printed to the log. To suppress this behaviour and to allow a transition silently fail, the event should have ended with a question mark (`try_call?`.) The event cannot have both a bang and a question mark in its name. ## Wiki Example