Packages
eventstore
0.6.1
1.4.8
1.4.7
1.4.6
1.4.4
1.4.3
1.4.2
1.4.1
1.4.0
1.3.2
1.3.1
1.3.0
1.2.3
1.2.2
1.2.1
1.2.0
1.1.0
1.0.3
1.0.2
1.0.1
1.0.0
1.0.0-rc.0
0.17.0
0.16.2
0.16.1
0.16.0
0.15.1
0.15.0
0.14.0
0.14.0-rc.0
0.13.2
0.13.1
0.13.0
0.12.1
0.12.0
0.11.0
0.11.0-rc.0
0.10.1
0.10.0
0.9.0
0.8.1
0.8.0
0.7.4
0.7.3
0.7.2
0.7.1
0.7.0
0.6.2
0.6.1
0.6.0
0.5.2
0.5.1
0.5.0
0.4.3
0.4.2
0.4.1
0.4.0
0.3.0
0.2.1
0.2.0
0.1.0
0.0.5
0.0.4
0.0.3
0.0.2
0.0.1
Event store using PostgreSQL for persistence.
Current section
Files
Jump to
Current section
Files
lib/event_store/writer.ex
defmodule EventStore.Writer do
@moduledoc """
Single process writer to assign a monotonically increasing id and persist events to the store
"""
use GenServer
require Logger
alias EventStore.{Subscriptions,RecordedEvent,Writer}
alias EventStore.Storage.{Appender,QueryLatestEventId}
defstruct conn: nil, next_event_id: 1
def start_link do
GenServer.start_link(__MODULE__, %Writer{}, name: __MODULE__)
end
def init(%Writer{} = state) do
storage_config = Application.get_env(:eventstore, EventStore.Storage)
{:ok, conn} = Postgrex.start_link(storage_config)
GenServer.cast(self, {:latest_event_id})
{:ok, %Writer{state | conn: conn}}
end
@doc """
Append the given list of events to the stream
"""
def append_to_stream(events, stream_id, stream_uuid)
def append_to_stream([], _stream_id, _stream_uuid), do: :ok
def append_to_stream(events, stream_id, stream_uuid) do
GenServer.call(__MODULE__, {:append_to_stream, events, stream_id, stream_uuid})
end
def handle_call({:append_to_stream, events, stream_id, stream_uuid}, _from, %Writer{conn: conn, next_event_id: next_event_id} = state) do
recorded_events = assign_event_id(events, next_event_id)
{reply, state} = case append_events(conn, stream_id, recorded_events) do
{:ok, count} ->
publish_events(stream_uuid, recorded_events)
{:ok, %Writer{state | next_event_id: next_event_id + count}}
{:error, _reason} = reply -> {reply, state}
end
{:reply, reply, state}
end
def handle_cast({:latest_event_id}, %Writer{conn: conn} = state) do
{:ok, last_event_id} = QueryLatestEventId.execute(conn)
{:noreply, %Writer{state | next_event_id: last_event_id + 1}}
end
defp assign_event_id(events, next_event_id) do
events
|> Enum.with_index(0)
|> Enum.map(fn {recorded_event, index} ->
%RecordedEvent{recorded_event |
event_id: next_event_id + index
}
end)
end
defp append_events(conn, stream_id, recorded_events) do
Appender.append(conn, stream_id, recorded_events)
end
defp publish_events(stream_uuid, recorded_events) do
Subscriptions.notify_events(stream_uuid, recorded_events)
end
end