# Imperial

A minimalistic, fully functional Raft implementation for Elixir. 

It supports:

- leader election, with pre-vote
- log replication, with the log stored on disk by [Goblin](https://hex.pm/packages/goblin)
- snapshots, to shorten the log
- adding and removing members while the cluster runs
- state machines that store their own state durably
- local reads, answered by one server without replication

## Installation

Imperial is not on Hex. Add it as a Git dependency in `mix.exs`:

```elixir
def deps do
  [
    {:imperial, "~> 0.1.0"}
  ]
end
```

## Usage

Define a state machine:

```elixir
defmodule KV do
  use Imperial

  def start_link(opts), do: Imperial.start_link(__MODULE__, opts)

  @impl Imperial
  def handle_init(_opts), do: {:ok, %{}}

  @impl Imperial
  def handle_command({:put, key, value}, _meta, state),
    do: {:reply, :ok, Map.put(state, key, value)}

  def handle_command({:get, key}, _meta, state),
    do: {:reply, Map.get(state, key), state}
end
```

Start it on every node, under a supervisor, with the other nodes of the
cluster as `:nodes`. The nodes must be connected.

```elixir
children = [
  {KV, data_dir: "/var/lib/kv", nodes: [:"kv@host2", :"kv@host3"]}
]
```

Send commands to any server. They are redirected to the leader:

```elixir
{:ok, :ok, leader} = Imperial.command(KV, {:put, :a, 1})
{:ok, 1, _leader} = Imperial.command(leader, {:get, :a})

# answered by the local server, may be out of date
{:ok, 1, _server} = Imperial.command(KV, {:get, :a}, local?: true)
```

Change the members of a running cluster:

```elixir
{:ok, :ok, _leader} = Imperial.add_member(KV, :"kv@host4")
{:ok, :ok, _leader} = Imperial.remove_member(KV, :"kv@host2")
```
