diff --git a/.github/workflows/sdk-spec.yml b/.github/workflows/sdk-spec.yml index 61b675e..bb978e9 100644 --- a/.github/workflows/sdk-spec.yml +++ b/.github/workflows/sdk-spec.yml @@ -11,8 +11,8 @@ permissions: jobs: sdk-spec: # Keep the ref in `uses:` and `spec-ref` in sync. - uses: Flagsmith/sdk-spec/.github/workflows/run-spec.yml@v0.7.1 + uses: Flagsmith/sdk-spec/.github/workflows/run-spec.yml@v0.9.0 with: - spec-ref: v0.7.1 + spec-ref: v0.9.0 language: elixir - tags: core or events or local-evaluation + tags: core events local-evaluation diff --git a/lib/engine/mappers.ex b/lib/engine/mappers.ex index 22d0656..4160bd2 100644 --- a/lib/engine/mappers.ex +++ b/lib/engine/mappers.ex @@ -128,6 +128,7 @@ defmodule Flagsmith.Engine.Mappers do defp map_variant(%Environment.MultivariateFeatureStateValue{} = value) do %{ "value" => value.multivariate_feature_option.value, + "key" => value.multivariate_feature_option.key, "weight" => value.percentage_allocation, "priority" => value.id || value.mv_fs_value_uuid } diff --git a/lib/flagsmith_client.ex b/lib/flagsmith_client.ex index bbe160b..ce21534 100644 --- a/lib/flagsmith_client.ex +++ b/lib/flagsmith_client.ex @@ -328,6 +328,50 @@ defmodule Flagsmith.Client do def track_exposure_event(opts, feature_name, event_opts) when is_list(opts), do: track_exposure_event(new(opts), feature_name, event_opts) + @doc """ + Sends the events tracked so far to Flagsmith without waiting for the flush interval, + and returns once each of them has been delivered, dropped, or kept for the next flush. + + Sending a batch of events is attempted up to 3 times, giving up on an attempt after + 3 seconds and backing off from 1 second, doubling, with full jitter. A batch the + events API rejects is dropped, and one it keeps failing is kept for the next flush, + ahead of the events tracked since. An events API refusing the environment key stops + event tracking. Up to 1000 events are buffered: when full, the oldest one is dropped. + """ + @spec flush_events(Configuration.t() | Keyword.t()) :: :ok | :noop | {:error, term()} + def flush_events(%Configuration{enable_events: false}), do: {:error, :events_disabled} + + def flush_events(%Configuration{environment_key: environment_key}), + do: Events.Processor.flush(environment_key) + + def flush_events(opts) when is_list(opts), do: flush_events(new(opts)) + + @doc """ + Closes the client: sends its buffered events, waiting for at most `timeout` + milliseconds (5 seconds by default), and stops the processes running for its + environment key, polling the environment and sending events. Events not sent by + then are dropped. + + Using the client again starts them again. + """ + @spec close(Configuration.t() | Keyword.t(), timeout :: non_neg_integer()) :: + :ok | :noop | {:error, term()} + def close(configuration_or_opts, timeout \\ 5000) + + def close( + %Configuration{ + environment_key: environment_key, + enable_local_evaluation: local?, + enable_events: events? + }, + timeout + ) do + if local?, do: Flagsmith.Client.Poller.stop(environment_key) + if events?, do: Events.Processor.close(environment_key, timeout), else: :noop + end + + def close(opts, timeout) when is_list(opts), do: close(new(opts), timeout) + @doc """ Return all flags from an environment as a list. If a `t:Flagsmith.Schemas.Environment.t/0` is passed instead of a @@ -482,23 +526,39 @@ defmodule Flagsmith.Client do do: analytics_track(new(opts), tracking) @doc false - # Submits a batch of events to the Flagsmith events API. - @spec events_track(Configuration.t(), list(Events.Processor.event())) :: - {:ok, term()} | {:error, term()} - def events_track(%Configuration{events_api_url: events_api_url} = config, events) do - case Tesla.post( - http_client(%{config | api_url: events_api_url}), - @api_paths.events, - %{events: events} + # Submits a batch of events to the Flagsmith events API, once, giving up on it after + # `timeout` milliseconds. Returns the response's status, or the reason no response was + # received; retrying is up to the caller. + @spec events_track(Configuration.t(), list(Events.Processor.event()), pos_integer()) :: + {:ok, Tesla.Env.status()} | {:error, term()} + def events_track(%Configuration{} = config, events, timeout) do + case Tesla.post(events_http_client(config, timeout), @api_paths.events, %{events: events}, + opts: [adapter: [timeout: timeout]] ) do - {:ok, %{status: status, body: body}} when status >= 200 and status < 300 -> - {:ok, body} - - error_resp -> - return_error(error_resp) + {:ok, %Tesla.Env{status: status}} -> {:ok, status} + {:error, _} = error -> error end end + @spec events_http_client(Configuration.t(), pos_integer()) :: Tesla.Client.t() + defp events_http_client( + %Configuration{ + environment_key: environment_key, + events_api_url: events_api_url, + custom_headers: custom_headers + }, + timeout + ) do + Tesla.client([ + base_url_middleware(events_api_url), + auth_middleware(environment_key), + user_agent_middleware(), + Tesla.Middleware.JSON, + {Tesla.Middleware.Headers, custom_headers}, + {Tesla.Middleware.Timeout, timeout: timeout} + ]) + end + @doc false # Given an `t:Flagsmith.Schemas.Environment.t/0` or a list composed of # `t:Flagsmith.Schemas.Environment.FeatureState.t/0` or diff --git a/lib/flagsmith_client_events_processor.ex b/lib/flagsmith_client_events_processor.ex index b2c8bfa..db08bed 100644 --- a/lib/flagsmith_client_events_processor.ex +++ b/lib/flagsmith_client_events_processor.ex @@ -19,12 +19,35 @@ defmodule Flagsmith.Client.Events.Processor do @flag_exposure_event "$flag_exposure" @max_buffered_events 1000 + @max_attempts 3 + @request_timeout_milliseconds 3000 + @retry_base_milliseconds if(Mix.env() == :test, do: 20, else: 1000) + @default_close_timeout_milliseconds 5000 + @close_margin_milliseconds 500 + # Statuses that a later attempt may not get, besides server errors. + @retried_statuses [408, 429] + # Statuses meaning the events API refuses the environment key. + @refused_statuses [401, 403] @enforce_keys [:configuration] defstruct [ :configuration, - buffer: [], - exposure_keys: MapSet.new() + buffer: :queue.new(), + buffered: 0, + # Whether events were tracked since the last attempt to send the buffer. + unsent: false, + refused: false, + exposure_keys: MapSet.new(), + # The batch being sent, by a task, so that the processor keeps buffering events + # (and applying the buffer's limit) while it waits on the events API. + sending: nil, + # Callers of flush/1 waiting for the batch being sent. + flush_waiters: [], + # Callers of flush/1 who arrived while a batch was being sent, with events tracked + # since: they wait for one more batch, then get a reply whatever is tracked meanwhile. + next_flush_waiters: [], + # The caller of close/2, once closing. + closing: nil ] ################################# @@ -60,13 +83,66 @@ defmodule Flagsmith.Client.Events.Processor do end @doc """ - Sends every buffered event to the Flagsmith events API, returning once done. + Sends the events tracked so far to the Flagsmith events API, retries included, and + returns once each of them has been delivered, dropped, or kept for the next flush. + Returns `:noop` when there is nothing to send, including when the buffer only holds + events already kept from a failed flush, which the next timed flush sends. + Never exits: returns `{:error, :closed}` if the processor is closed meanwhile. """ @spec flush(environment_key()) :: :ok | :noop | {:error, term()} def flush(environment_key) do case whereis(environment_key) do - pid when is_pid(pid) -> GenServer.call(pid, :flush) - :undefined -> :noop + pid when is_pid(pid) -> + try do + GenServer.call(pid, :flush, :infinity) + catch + # The processor stopped between being looked up and called. + :exit, {reason, _} when reason in [:noproc, :normal, :shutdown] -> :noop + :exit, {reason, _} -> {:error, reason} + end + + :undefined -> + :noop + end + end + + @doc """ + Sends the buffered events, and stops the processor, returning after at most + `timeout` milliseconds. Events not sent by then are dropped, and a batch still being + sent, e.g. retried by a flush already running, is abandoned: no attempt to send it + is made after this returns. + """ + @spec close(environment_key(), non_neg_integer()) :: :ok | :noop | {:error, term()} + def close(environment_key, timeout \\ @default_close_timeout_milliseconds) do + case whereis(environment_key) do + pid when is_pid(pid) -> + try do + # The processor replies by the deadline itself; the margin only covers one + # that can't, for which it's killed. + GenServer.call(pid, {:close, timeout}, timeout + @close_margin_milliseconds) + catch + :exit, {:timeout, _} -> + Logger.warning("Gave up sending events after #{timeout} milliseconds while closing") + kill(pid) + {:error, :timeout} + + :exit, {reason, _} when reason in [:noproc, :normal, :shutdown] -> + :noop + end + + :undefined -> + :noop + end + end + + # Kills the processor, returning once it's gone. It traps exits, so only :kill stops + # it; its supervisor doesn't restart it, being :temporary. + defp kill(pid) do + ref = Process.monitor(pid) + Process.exit(pid, :kill) + + receive do + {:DOWN, ^ref, :process, ^pid, _reason} -> :ok end end @@ -113,6 +189,11 @@ defmodule Flagsmith.Client.Events.Processor do end @impl GenServer + def handle_cast({:track, event}, %__MODULE__{refused: true} = data) do + Logger.debug("Not tracking #{event.event} event: the events API refused the environment key") + {:noreply, data} + end + def handle_cast({:track, event}, %__MODULE__{} = data) do case exposure_key(event) do nil -> @@ -137,56 +218,295 @@ defmodule Flagsmith.Client.Events.Processor do end @impl GenServer - def handle_call(:flush, _from, %__MODULE__{} = data) do - {result, data} = do_flush(data) - {:reply, result, data} + def handle_call(:flush, from, %__MODULE__{sending: %{}, unsent: true} = data), + do: {:noreply, %{data | next_flush_waiters: [from | data.next_flush_waiters]}} + + def handle_call(:flush, from, %__MODULE__{sending: %{}} = data), + do: {:noreply, add_flush_waiter(data, from)} + + def handle_call(:flush, _from, %__MODULE__{unsent: false} = data), + do: {:reply, :noop, data} + + def handle_call(:flush, from, %__MODULE__{} = data), + do: {:noreply, data |> send_batch(:infinity) |> add_flush_waiter(from)} + + # Already closing: the first caller is the one waiting for the buffered events. + def handle_call({:close, _timeout}, _from, %__MODULE__{closing: %{}} = data), + do: {:reply, :noop, data} + + def handle_call({:close, timeout}, from, %__MODULE__{} = data) do + Process.send_after(self(), :close_timeout, timeout) + deadline = System.monotonic_time(:millisecond) + timeout + closing = %{from: from, timeout: timeout, deadline: deadline, final_batch: false} + + case data.sending do + # Waits for the batch being sent, until the deadline, then sends what's left. + %{} -> {:noreply, %{data | closing: closing}} + nil -> close_next(%{data | closing: closing}, :noop) + end end @impl GenServer def handle_info(:flush, %__MODULE__{configuration: config} = data) do - {_, data} = do_flush(data) schedule_flush(config) - {:noreply, data} + + case data do + %{sending: nil, closing: nil} -> {:noreply, send_batch(data, :infinity)} + _ -> {:noreply, data} + end + end + + def handle_info({ref, outcome}, %__MODULE__{sending: %{task: %Task{ref: ref}}} = data) do + Process.demonitor(ref, [:flush]) + sent(data, outcome) + end + + def handle_info( + {:DOWN, ref, :process, _pid, reason}, + %__MODULE__{sending: %{task: %Task{ref: ref}}} = data + ), + do: sent(data, {:kept, reason}) + + def handle_info(:close_timeout, %__MODULE__{closing: %{timeout: timeout}} = data) do + Logger.warning("Gave up sending events after #{timeout} milliseconds while closing") + stop_closing(abandon_batch(data), {:error, :timeout}) end def handle_info(_, data), do: {:noreply, data} @impl GenServer - def terminate(_reason, %__MODULE__{} = data), do: do_flush(data) + def terminate(_reason, %__MODULE__{} = data) do + data = abandon_batch(data) + + case take_batch(data) do + nil -> + :noop + + {events, data} -> + deadline = System.monotonic_time(:millisecond) + @default_close_timeout_milliseconds + apply_outcome(data, events, deliver(data.configuration, events, deadline, 1)) + end + end defp exposure_key(%{event: @flag_exposure_event} = event), do: {event.feature_name, event.identifier, event.value} defp exposure_key(_), do: nil - defp buffer(%__MODULE__{buffer: buffer} = data, event) do - data = %{data | buffer: [event | buffer]} + # A full buffer drops its oldest event for the new one. Filling it up sends it + # without waiting for the flush interval, or as soon as the batch being sent is done. + defp buffer(%__MODULE__{buffered: @max_buffered_events} = data, event) do + {{:value, dropped}, buffer} = :queue.out(data.buffer) + Logger.warning("Event buffer is full, dropping the oldest #{dropped.event} event") + forget_exposures(%{data | buffer: :queue.in(event, buffer), unsent: true}, [dropped]) + end - case length(data.buffer) >= @max_buffered_events do - true -> elem(do_flush(data), 1) - false -> data + defp buffer(%__MODULE__{} = data, event) do + data = %{ + data + | buffer: :queue.in(event, data.buffer), + buffered: data.buffered + 1, + unsent: true + } + + case {data.buffered, data.sending, data.closing} do + {@max_buffered_events, nil, nil} -> send_batch(data, :infinity) + _ -> data end end - defp do_flush(%__MODULE__{buffer: []} = data), do: {:noop, data} + defp add_flush_waiter(data, from), do: %{data | flush_waiters: [from | data.flush_waiters]} - defp do_flush(%__MODULE__{configuration: config, buffer: buffer} = data) do - events = Enum.reverse(buffer) + # Starts sending the buffered events, in a task, unless there are none. + defp send_batch(%__MODULE__{configuration: config} = data, deadline) do + case take_batch(data) do + nil -> + data - case Flagsmith.Client.events_track(config, events) do - {:ok, _} -> - {:ok, %{data | buffer: [], exposure_keys: MapSet.new()}} + {events, data} -> + task = Task.async(fn -> deliver(config, events, deadline, 1) end) + %{data | sending: %{task: task, events: events}} + end + end + + defp take_batch(%__MODULE__{buffered: 0}), do: nil + + defp take_batch(%__MODULE__{} = data), + do: {:queue.to_list(data.buffer), %{data | buffer: :queue.new(), buffered: 0, unsent: false}} + + # Kills the task sending a batch, if any, putting the batch back in the buffer. + defp abandon_batch(%__MODULE__{sending: nil} = data), do: data + + defp abandon_batch(%__MODULE__{sending: %{task: task, events: events}} = data) do + Task.shutdown(task, :brutal_kill) + keep(%{data | sending: nil}, events) + end + + # The batch being sent is done with: replies to the callers of flush/1 waiting for it, + # and sends one more batch for those who arrived meanwhile, with events tracked since. + defp sent(%__MODULE__{sending: %{events: events}} = data, outcome) do + {result, data} = apply_outcome(%{data | sending: nil}, events, outcome) + reply_all(data.flush_waiters, result) + data = %{data | flush_waiters: []} + + cond do + data.closing != nil -> + close_next(data, result) + + data.next_flush_waiters != [] and data.unsent -> + data = send_batch(data, :infinity) + {:noreply, %{data | flush_waiters: data.next_flush_waiters, next_flush_waiters: []}} + + true -> + reply_all(data.next_flush_waiters, result) + data = %{data | next_flush_waiters: []} + + # Events tracked meanwhile filled the buffer up; a kept batch alone doesn't. + case {data.buffered, data.unsent} do + {@max_buffered_events, true} -> {:noreply, send_batch(data, :infinity)} + _ -> {:noreply, data} + end + end + end - {:error, reason} = error -> - Logger.warning("Failed to send events to Flagsmith, keeping them to retry", + defp reply_all(callers, reply), do: Enum.each(callers, &GenServer.reply(&1, reply)) + + # Sends the buffer once while closing, by the deadline, then stops. + defp close_next(%__MODULE__{closing: %{final_batch: false} = closing} = data, result) do + case send_batch(data, closing.deadline) do + %{sending: nil} = data -> stop_closing(data, result) + data -> {:noreply, %{data | closing: %{closing | final_batch: true}}} + end + end + + defp close_next(%__MODULE__{} = data, result), do: stop_closing(data, result) + + defp stop_closing(%__MODULE__{closing: closing} = data, result) do + GenServer.reply(closing.from, result) + reply_all(data.flush_waiters ++ data.next_flush_waiters, {:error, :closed}) + + {:stop, :normal, + %{ + data + | buffer: :queue.new(), + buffered: 0, + flush_waiters: [], + next_flush_waiters: [], + closing: nil + }} + end + + # What became of a batch: forgets it once delivered or dropped, and puts it back in + # the buffer, ahead of the events tracked since, when kept for the next flush. + defp apply_outcome(data, events, outcome) do + case outcome do + :delivered -> + {:ok, forget_exposures(data, events)} + + {:dropped, reason} -> + {{:error, reason}, forget_exposures(data, events)} + + {:refused, reason} -> + Logger.error("The events API refused the environment key, stopping event tracking") + + {{:error, reason}, + %{ + data + | buffer: :queue.new(), + buffered: 0, + unsent: false, + refused: true, + exposure_keys: MapSet.new() + }} + + {:kept, reason} -> + Logger.warning("Failed to send events to Flagsmith, keeping them for the next flush", reason: inspect(reason), events: length(events) ) - {error, %{data | buffer: Enum.take(buffer, @max_buffered_events)}} + {{:error, reason}, keep(data, events)} + end + end + + defp keep(data, events) do + {dropped, kept} = + Enum.split(events ++ :queue.to_list(data.buffer), -@max_buffered_events) + + if dropped != [], + do: Logger.warning("Event buffer is full, dropping the oldest #{length(dropped)} events") + + forget_exposures(%{data | buffer: :queue.from_list(kept), buffered: length(kept)}, dropped) + end + + # Forgets the exposures among events no longer buffered, so that they're tracked again. + defp forget_exposures(data, events) do + keys = events |> Enum.map(&exposure_key/1) |> Enum.reject(&is_nil/1) |> MapSet.new() + %{data | exposure_keys: MapSet.difference(data.exposure_keys, keys)} + end + + # Sends a batch up to @max_attempts times, backing off with full jitter between + # attempts, until `deadline`. Returns what became of the batch: delivered, dropped + # (rejected by the events API, or failed with a 500 on its last attempt), refused + # (the events API refuses the environment key), or kept for the next flush. + defp deliver(config, events, deadline, attempt) do + case remaining(deadline) do + 0 -> + {:kept, :timeout} + + remaining -> + config + |> Flagsmith.Client.events_track(events, min(remaining, @request_timeout_milliseconds)) + |> handle_attempt(config, events, deadline, attempt) end end + defp handle_attempt({:ok, status}, _, _, _, _) when status in 200..299, do: :delivered + + defp handle_attempt({:ok, status}, _, _, _, _) when status in @refused_statuses, + do: {:refused, {:status, status}} + + defp handle_attempt({:ok, status}, _, events, _, _) + when status < 500 and status not in @retried_statuses do + Logger.warning( + "The events API rejected #{length(events)} events with #{status}, dropping them" + ) + + {:dropped, {:status, status}} + end + + defp handle_attempt({:ok, 500}, _, events, _, @max_attempts) do + Logger.warning("The events API failed #{length(events)} events with 500, dropping them") + {:dropped, {:status, 500}} + end + + defp handle_attempt(result, _, _, _, @max_attempts), do: {:kept, failure(result)} + + defp handle_attempt(result, config, events, deadline, attempt) do + Logger.warning( + "Failed to send #{length(events)} events, attempt #{attempt} of #{@max_attempts}", + reason: inspect(failure(result)) + ) + + backoff = :rand.uniform(@retry_base_milliseconds * 2 ** (attempt - 1) + 1) - 1 + + case remaining(deadline) do + remaining when remaining <= backoff -> + {:kept, failure(result)} + + _ -> + Process.sleep(backoff) + deliver(config, events, deadline, attempt + 1) + end + end + + defp failure({:ok, status}), do: {:status, status} + defp failure({:error, reason}), do: reason + + # As an atom, :infinity compares greater than any number, e.g. in min/2. + defp remaining(:infinity), do: :infinity + defp remaining(deadline), do: max(deadline - System.monotonic_time(:millisecond), 0) + defp schedule_flush(%Configuration{events_flush_interval_milliseconds: interval}), do: Process.send_after(self(), :flush, interval) end diff --git a/lib/flagsmith_client_poller.ex b/lib/flagsmith_client_poller.ex index 8878cf3..aa62d8a 100644 --- a/lib/flagsmith_client_poller.ex +++ b/lib/flagsmith_client_poller.ex @@ -73,6 +73,17 @@ defmodule Flagsmith.Client.Poller do end end + # Stops the poller for the environment key, if one is running. + @spec stop(environment_key()) :: :ok | :noop + def stop(environment_key) do + with pid when is_pid(pid) <- whereis(environment_key), + :ok <- DynamicSupervisor.terminate_child(__MODULE__.Supervisor, pid) do + :ok + else + _ -> :noop + end + end + @spec start_link(Configuration.t()) :: {:ok, pid()} def start_link(%Configuration{environment_key: environment_key} = config) do name = via_tuple(environment_key) diff --git a/lib/flagsmith_engine.ex b/lib/flagsmith_engine.ex index 060394d..fea86ee 100644 --- a/lib/flagsmith_engine.ex +++ b/lib/flagsmith_engine.ex @@ -154,12 +154,23 @@ defmodule Flagsmith.Engine do defp to_feature_states(feature_states, flags) do Enum.map(feature_states, fn %{feature: %{name: name}} -> case Map.fetch!(flags, name) do - %FlagResult{enabled: enabled, value: value, metadata: %{feature_state: feature_state}} - when enabled === feature_state.enabled and value === feature_state.feature_state_value -> + %FlagResult{ + enabled: enabled, + value: value, + variant: variant, + metadata: %{feature_state: feature_state} + } + when enabled === feature_state.enabled and value === feature_state.feature_state_value and + variant === feature_state.variant -> feature_state - %FlagResult{enabled: enabled, value: value, metadata: %{feature_state: feature_state}} -> - %{feature_state | enabled: enabled, feature_state_value: value} + %FlagResult{ + enabled: enabled, + value: value, + variant: variant, + metadata: %{feature_state: feature_state} + } -> + %{feature_state | enabled: enabled, feature_state_value: value, variant: variant} end end) end diff --git a/lib/schemas/environment_feature_state.ex b/lib/schemas/environment_feature_state.ex index 4b9a92b..dfac852 100644 --- a/lib/schemas/environment_feature_state.ex +++ b/lib/schemas/environment_feature_state.ex @@ -2,7 +2,7 @@ defmodule Flagsmith.Schemas.Environment.FeatureState do use TypedEctoSchema import Ecto.Changeset - alias Flagsmith.Schemas.Environment + alias Flagsmith.Schemas.{Environment, Features} alias Flagsmith.Schemas.Types @moduledoc """ @@ -20,6 +20,10 @@ defmodule Flagsmith.Schemas.Environment.FeatureState do embeds_one(:feature, Environment.Feature) embeds_one(:feature_segment, __MODULE__.FeatureSegment) embeds_many(:multivariate_feature_state_values, Environment.MultivariateFeatureStateValue) + embeds_one(:metadata, Features.FeatureState.Metadata) + + # The variant an identity is served, set when evaluating its flags. + field(:variant, :string, virtual: true) end @doc false @@ -33,6 +37,7 @@ defmodule Flagsmith.Schemas.Environment.FeatureState do |> cast_embed(:feature) |> cast_embed(:feature_segment) |> cast_embed(:multivariate_feature_state_values) + |> cast_embed(:metadata) end @doc false diff --git a/lib/schemas/environment_multivariate_feature_option.ex b/lib/schemas/environment_multivariate_feature_option.ex index 8a00c52..936da88 100644 --- a/lib/schemas/environment_multivariate_feature_option.ex +++ b/lib/schemas/environment_multivariate_feature_option.ex @@ -9,6 +9,7 @@ defmodule Flagsmith.Schemas.Environment.MultivariateFeatureOption do @primary_key {:id, :id, autogenerate: false} typed_embedded_schema do field(:value, :string) + field(:key, :string) end @doc false @@ -16,7 +17,7 @@ defmodule Flagsmith.Schemas.Environment.MultivariateFeatureOption do @spec changeset(__MODULE__.t(), map()) :: Ecto.Changeset.t() def changeset(struct \\ %__MODULE__{}, params) do struct - |> cast(params, [:id, :value], empty_values: []) + |> cast(params, [:id, :value, :key], empty_values: []) end @doc false diff --git a/lib/schemas/flag.ex b/lib/schemas/flag.ex index 60cc3e1..aba4160 100644 --- a/lib/schemas/flag.ex +++ b/lib/schemas/flag.ex @@ -21,6 +21,8 @@ defmodule Flagsmith.Schemas.Flag do def from(%Environment.FeatureState{ enabled: enabled, feature_state_value: value, + variant: variant, + metadata: metadata, feature: %Environment.Feature{ name: name, id: id @@ -30,7 +32,9 @@ defmodule Flagsmith.Schemas.Flag do enabled: enabled, feature_name: name, value: value, - feature_id: id + feature_id: id, + variant: variant, + experiment: metadata && metadata.experiment } end diff --git a/lib/supervisors/events_processor_supervisor.ex b/lib/supervisors/events_processor_supervisor.ex index c0d83f1..52dcd63 100644 --- a/lib/supervisors/events_processor_supervisor.ex +++ b/lib/supervisors/events_processor_supervisor.ex @@ -25,7 +25,9 @@ defmodule Flagsmith.Client.Events.Processor.Supervisor do id: Flagsmith.Client.Events.Processor, start: {Flagsmith.Client.Events.Processor, :start_link, [config]}, shutdown: 25_000, - restart: :permanent, + # Not restarted once stopped, by closing the client or killing it when closing + # times out: `Flagsmith.Client.Events.Processor.track/2` starts a new one if needed. + restart: :temporary, type: :worker } ) diff --git a/sdk-spec/steps.exs b/sdk-spec/steps.exs index 6100244..fe44a15 100644 --- a/sdk-spec/steps.exs +++ b/sdk-spec/steps.exs @@ -46,6 +46,23 @@ defmodule SDKSpec.Steps do end end + # Create the SDK client with local evaluation and events enabled + def create_client_with_local_evaluation_and_events(environment_key, api_url, events_api_url) do + client = + Client.new( + environment_key: environment_key, + api_url: api_url, + enable_local_evaluation: true, + enable_events: true, + events_api_url: events_api_url + ) + + with :ok <- start_supervisor(), + {:ok, _environment} <- Client.get_environment(client) do + {:ok, client} + end + end + defp start_supervisor do case Flagsmith.Supervisor.start_link() do {:ok, _pid} -> :ok @@ -90,4 +107,23 @@ defmodule SDKSpec.Steps do metadata: metadata ) end + + # When the application tracks events "event_{first}" to "event_{last}" for identity "{identifier}" + def track_numbered_events(client, first, last, identifier) do + Enum.each(first..last, fn number -> + :ok = Client.track_event(client, "event_#{number}", identifier: identifier) + end) + end + + # When the application flushes events + def flush_events(client) do + Client.flush_events(client) + :ok + end + + # When the application closes the client with a timeout of {timeout} seconds + def close_client(client, timeout) do + Client.close(client, round(timeout * 1000)) + :ok + end end diff --git a/test/flagsmith_events_test.exs b/test/flagsmith_events_test.exs index 0dd6452..ded052c 100644 --- a/test/flagsmith_events_test.exs +++ b/test/flagsmith_events_test.exs @@ -2,7 +2,8 @@ defmodule Flagsmith.Client.Events.Test do use ExUnit.Case, async: false import ExUnit.CaptureLog - import Mox, only: [verify_on_exit!: 1, set_mox_global: 1, expect: 3, expect: 4] + import Flagsmith.Test.Helpers, only: [wait_until: 2] + import Mox, only: [verify_on_exit!: 1, set_mox_global: 1, expect: 3, expect: 4, stub: 3] alias Flagsmith.Client alias Flagsmith.Client.Events.Processor @@ -219,6 +220,148 @@ defmodule Flagsmith.Client.Events.Test do end end + describe "get_experiment_flag with local evaluation" do + setup do + Mox.stub_with(Flagsmith.Engine.MockHashing, Flagsmith.Engine.HashingUtils) + + [ + local_config: + Client.new( + environment_key: "events_test_key", + enable_local_evaluation: true, + enable_events: true, + events_api_url: @events_url + ) + ] + end + + for {case_name, rollout, allocation, variant, value} <- [ + {"to the variant it was served", 100.0, 100.0, "treatment", "new checkout"}, + {"to control when served no variant", 100.0, 0.0, "control", "control"} + ] do + test "an identity in a running experiment is exposed #{case_name}", %{ + local_config: config, + receive_events: receive_events + } do + # Given + expect(Tesla.Adapter.Mock, :call, fn _tesla_env, _options -> + {:ok, + %Tesla.Env{ + status: 200, + body: experiment_environment(unquote(rollout), unquote(allocation)) + }} + end) + + expect(Tesla.Adapter.Mock, :call, receive_events) + + # When + flag = + Client.get_experiment_flag(config, "checkout", "user_123", [ + %{trait_key: "plan", trait_value: "premium"} + ]) + + :ok = Client.flush_events(config) + + # Then + assert %Schemas.Flag{ + value: unquote(value), + variant: unquote(variant), + experiment: %Schemas.Experiment{id: 9, in_experiment: true} + } = flag + + assert_receive {:events_request, _tesla_env, %{"events" => [event]}} + + assert %{ + "event" => "$flag_exposure", + "feature_name" => "checkout", + "identifier" => "user_123", + "value" => unquote(variant), + "traits" => %{"plan" => "premium"}, + "metadata" => %{"experiment_id" => 9} + } = event + end + end + + test "an identity a running experiment does not enroll is not exposed", %{ + local_config: config + } do + # Given + expect(Tesla.Adapter.Mock, :call, fn _tesla_env, _options -> + {:ok, %Tesla.Env{status: 200, body: experiment_environment(0.0, 100.0)}} + end) + + # When + flag = Client.get_experiment_flag(config, "checkout", "user_123", []) + + # Then + assert %Schemas.Flag{ + value: "control", + experiment: %Schemas.Experiment{in_experiment: false} + } = flag + + assert :noop = Client.flush_events(config) + end + end + + # An environment document with an experiment on feature "checkout", as Flagsmith + # sends it: enrolled identities match the experiment's rollout segment, whose + # override serves the "treatment" variant to `allocation`% of them. + defp experiment_environment(rollout, allocation) do + feature_state = fn id, allocation, in_experiment -> + %{ + "feature" => %{"id" => 43, "name" => "checkout", "type" => "MULTIVARIATE"}, + "enabled" => true, + "django_id" => id, + "featurestate_uuid" => Ecto.UUID.generate(), + "feature_state_value" => "control", + "multivariate_feature_state_values" => [ + %{ + "multivariate_feature_option" => %{ + "id" => 9, + "key" => "treatment", + "value" => "new checkout" + }, + "percentage_allocation" => allocation, + "id" => id, + "mv_fs_value_uuid" => Ecto.UUID.generate() + } + ], + "metadata" => %{ + "experiment" => %{ + "id" => 9, + "name" => "checkout experiment", + "in_experiment" => in_experiment + } + } + } + end + + segment = %{ + "id" => 19, + "name" => "experiment-9-rollout", + "rules" => [ + %{ + "type" => "ALL", + "rules" => [], + "conditions" => [ + %{ + "operator" => "PERCENTAGE_SPLIT", + "value" => to_string(rollout), + "property_" => "$.identity.key" + } + ] + } + ], + "feature_states" => [ + Map.put(feature_state.(62, allocation, true), "feature_segment", %{"priority" => 0}) + ] + } + + Flagsmith.Engine.Test.Generators.map_env() + |> Map.put("feature_states", [feature_state.(61, 0.0, false)]) + |> put_in(["project", "segments"], [segment]) + end + describe "track_event" do test "a tracked event reaches Flagsmith with its value, traits and metadata", %{ config: config, @@ -396,32 +539,158 @@ defmodule Flagsmith.Client.Events.Test do assert_receive {:events_request, _, %{"events" => [%{"event" => "second"}]}}, 500 end - test "events Flagsmith fails to receive are sent again on the next flush", %{ - config: config, - receive_events: receive_events - } do + test "a batch is retried until the events API accepts it, giving up on each attempt after 3 seconds", + %{config: config, receive_events: receive_events} do # Given - expect(Tesla.Adapter.Mock, :call, fn _tesla_env, _options -> + test_pid = self() + + expect(Tesla.Adapter.Mock, :call, fn tesla_env, _options -> + send(test_pid, {:attempt, tesla_env.opts[:adapter][:timeout]}) {:ok, %Tesla.Env{status: 503, body: "unavailable"}} end) + expect(Tesla.Adapter.Mock, :call, fn _tesla_env, _options -> {:error, :econnreset} end) expect(Tesla.Adapter.Mock, :call, receive_events) - :ok = Client.track_event(config, "checkout_completed", identifier: "user_123") + :ok = Client.track_event(config, "checkout", identifier: "user_123") # When + log = capture_log(fn -> assert :ok = Client.flush_events(config) end) + + # Then + assert_receive {:attempt, 3000} + assert_receive {:events_request, _tesla_env, %{"events" => [%{"event" => "checkout"}]}} + assert log =~ "attempt 1 of 3" + assert log =~ "attempt 2 of 3" + assert :noop = Client.flush_events(config) + end + + test "a batch that keeps failing is sent with the next flush, ahead of events tracked since", + %{config: config, receive_events: receive_events} do + # Given + expect(Tesla.Adapter.Mock, :call, 3, fn _tesla_env, _options -> + {:ok, %Tesla.Env{status: 503, body: "unavailable"}} + end) + + expect(Tesla.Adapter.Mock, :call, receive_events) + :ok = Client.track_event(config, "add_to_cart", identifier: "user_123") + log = capture_log(fn -> - assert {:error, "unavailable"} = Processor.flush(config.environment_key) + assert {:error, {:status, 503}} = Client.flush_events(config) end) - :ok = Client.track_event(config, "signed_out", identifier: "user_123") - :ok = Processor.flush(config.environment_key) + # When + :ok = Client.track_event(config, "checkout", identifier: "user_123") + :ok = Client.flush_events(config) # Then - assert log =~ "Failed to send events to Flagsmith, keeping them to retry" + assert log =~ "keeping them for the next flush" + assert_receive {:events_request, _tesla_env, %{"events" => events}} + assert ["add_to_cart", "checkout"] = Enum.map(events, & &1["event"]) + end + + for {case_name, failures} <- [ + {"a batch the events API rejects is dropped", [400]}, + {"a batch whose last attempt gets a server error is dropped", [503, 503, 500]} + ] do + test case_name, %{config: config, receive_events: receive_events} do + # Given + for status <- unquote(failures) do + expect(Tesla.Adapter.Mock, :call, fn _tesla_env, _options -> + {:ok, %Tesla.Env{status: status, body: "failed"}} + end) + end + + expect(Tesla.Adapter.Mock, :call, receive_events) + :ok = Client.track_event(config, "add_to_cart", identifier: "user_123") + + log = + capture_log(fn -> + assert {:error, {:status, _}} = Client.flush_events(config) + end) + + # When + :ok = Client.track_event(config, "checkout", identifier: "user_123") + :ok = Client.flush_events(config) + + # Then + assert log =~ "dropping them" + assert_receive {:events_request, _tesla_env, %{"events" => [%{"event" => "checkout"}]}} + end + end + + test "a batch whose last attempt fails otherwise is kept, after server errors", %{ + config: config, + receive_events: receive_events + } do + # Given + for status <- [500, 500, 503] do + expect(Tesla.Adapter.Mock, :call, fn _tesla_env, _options -> + {:ok, %Tesla.Env{status: status, body: "failed"}} + end) + end + + expect(Tesla.Adapter.Mock, :call, receive_events) + :ok = Client.track_event(config, "add_to_cart", identifier: "user_123") + capture_log(fn -> assert {:error, {:status, 503}} = Client.flush_events(config) end) + # When + :ok = Client.track_event(config, "checkout", identifier: "user_123") + :ok = Client.flush_events(config) + + # Then assert_receive {:events_request, _tesla_env, %{"events" => events}} - assert ["checkout_completed", "signed_out"] = Enum.map(events, & &1["event"]) + assert ["add_to_cart", "checkout"] = Enum.map(events, & &1["event"]) + end + + for status <- [401, 403] do + test "an events API refusing the environment key with #{status} stops event tracking", %{ + config: config + } do + # Given + expect(Tesla.Adapter.Mock, :call, fn _tesla_env, _options -> + {:ok, %Tesla.Env{status: unquote(status), body: "refused"}} + end) + + :ok = Client.track_event(config, "add_to_cart", identifier: "user_123") + + log = + capture_log(fn -> + assert {:error, {:status, unquote(status)}} = Client.flush_events(config) + end) + + # When + :ok = Client.track_event(config, "checkout", identifier: "user_123") + + # Then + assert log =~ "stopping event tracking" + assert :noop = Client.flush_events(config) + end + end + + test "a full buffer drops its oldest event", %{config: config, receive_events: receive_events} do + # Given + expect(Tesla.Adapter.Mock, :call, 3, fn _tesla_env, _options -> + {:ok, %Tesla.Env{status: 503, body: "unavailable"}} + end) + + expect(Tesla.Adapter.Mock, :call, receive_events) + + log = + capture_log(fn -> + for n <- 1..1000, do: :ok = Client.track_event(config, "event_#{n}") + # Waits for, or finds done, the batch the full buffer sent by itself. + assert Client.flush_events(config) in [:noop, {:error, {:status, 503}}] + + # When + :ok = Client.track_event(config, "event_1001") + :ok = Client.flush_events(config) + end) + + # Then + assert log =~ "dropping the oldest event_1 event" + assert_receive {:events_request, _tesla_env, %{"events" => events}} + assert Enum.map(events, & &1["event"]) == for(n <- 2..1001, do: "event_#{n}") end test "a full buffer of events is sent without waiting for the flush interval", %{ @@ -437,7 +706,45 @@ defmodule Flagsmith.Client.Events.Test do # Then assert_receive {:events_request, _tesla_env, %{"events" => events}}, 1000 assert length(events) == 1000 - assert :noop = Processor.flush(config.environment_key) + assert Processor.flush(config.environment_key) in [:ok, :noop] + end + + test "events tracked while a batch is being sent are buffered, up to the buffer's limit", %{ + config: config + } do + # Given a full buffer, whose batch the events API holds on to + test_pid = self() + + stub(Tesla.Adapter.Mock, :call, fn tesla_env, _options -> + send(test_pid, {:holding, self(), Jason.decode!(tesla_env.body)}) + + receive do + :release -> {:ok, %Tesla.Env{status: 202, body: ""}} + end + end) + + for n <- 1..1000, do: :ok = Client.track_event(config, "event_#{n}") + assert_receive {:holding, request, %{"events" => first_batch}}, 1000 + + # When + log = + capture_log(fn -> + for n <- 1001..2500, do: :ok = Client.track_event(config, "event_#{n}") + + # Then the processor keeps up, holding at most a full buffer besides the batch + pid = Processor.whereis(config.environment_key) + assert %Processor{buffered: 1000, sending: %{}} = :sys.get_state(pid) + assert {:message_queue_len, 0} = Process.info(pid, :message_queue_len) + end) + + assert log =~ "dropping the oldest event_1001 event" + assert Enum.map(first_batch, & &1["event"]) == for(n <- 1..1000, do: "event_#{n}") + + # And the full buffer is sent once the batch is done with + send(request, :release) + assert_receive {:holding, request, %{"events" => second_batch}}, 1000 + send(request, :release) + assert Enum.map(second_batch, & &1["event"]) == for(n <- 1501..2500, do: "event_#{n}") end test "buffered events are sent when the application stops", %{ @@ -456,6 +763,230 @@ defmodule Flagsmith.Client.Events.Test do assert %{"event" => "checkout_completed"} = event end + test "closing the client sends the buffered events, and stops sending events", %{ + config: config, + receive_events: receive_events + } do + # Given + expect(Tesla.Adapter.Mock, :call, fn _tesla_env, _options -> + {:ok, %Tesla.Env{status: 503, body: "unavailable"}} + end) + + expect(Tesla.Adapter.Mock, :call, receive_events) + :ok = Client.track_event(config, "checkout", identifier: "user_123") + + # When + capture_log(fn -> assert :ok = Client.close(config) end) + + # Then + assert_receive {:events_request, _tesla_env, %{"events" => [%{"event" => "checkout"}]}} + assert :undefined = Processor.whereis(config.environment_key) + end + + test "closing the client returns within its timeout when the events API does not answer", %{ + config: config + } do + # Given + test_pid = self() + + stub(Tesla.Adapter.Mock, :call, fn tesla_env, _options -> + timeout = tesla_env.opts[:adapter][:timeout] + send(test_pid, {:attempt, timeout}) + Process.sleep(timeout) + {:error, :timeout} + end) + + :ok = Client.track_event(config, "checkout", identifier: "user_123") + + # When + {elapsed, result} = + :timer.tc(fn -> capture_log(fn -> send(test_pid, Client.close(config, 200)) end) end) + + # Then + assert_received {:error, :timeout} + assert_receive {:attempt, timeout} when timeout <= 200 + assert elapsed < 400_000 + assert is_binary(result) + end + + test "a flush waits for one more batch at most while events keep being tracked", %{ + config: config + } do + # Given an events API holding on to each batch until released + test_pid = self() + + stub(Tesla.Adapter.Mock, :call, fn tesla_env, _options -> + events = Enum.map(Jason.decode!(tesla_env.body)["events"], & &1["event"]) + send(test_pid, {:holding, self(), events}) + + receive do + :release -> {:ok, %Tesla.Env{status: 202, body: ""}} + end + end) + + flush = fn n -> + spawn(fn -> send(test_pid, {:flushed, n, Client.flush_events(config)}) end) + end + + :ok = Client.track_event(config, "first") + pid = Processor.whereis(config.environment_key) + flush.(1) + assert_receive {:holding, request, ["first"]} + + # When a flush arrives while that batch is sent, with an event tracked since + :ok = Client.track_event(config, "second") + flush.(2) + assert wait_until(fn -> :sys.get_state(pid).next_flush_waiters != [] end, 500) + send(request, :release) + + # Then it waits for the batch in flight and one more, whatever is tracked meanwhile + assert_receive {:flushed, 1, :ok} + assert_receive {:holding, request, ["second"]} + :ok = Client.track_event(config, "third") + _ = :sys.get_state(pid) + send(request, :release) + assert_receive {:flushed, 2, :ok} + refute_receive {:holding, _, _}, 100 + end + + test "an exposure dropped from a full buffer is tracked again", %{config: config} do + # Given an exposure dropped from a buffer the events API failed to receive + stub(Tesla.Adapter.Mock, :call, fn _tesla_env, _options -> + {:ok, %Tesla.Env{status: 503, body: "unavailable"}} + end) + + exposure = [identifier: "user_123", value: "treatment"] + + capture_log(fn -> + :ok = Client.track_exposure_event(config, "banner", exposure) + for n <- 2..1000, do: :ok = Client.track_event(config, "event_#{n}") + assert Client.flush_events(config) in [:noop, {:error, {:status, 503}}] + :ok = Client.track_event(config, "event_1001") + end) + + # When + pid = Processor.whereis(config.environment_key) + + {state, log} = + with_log(fn -> + :ok = Client.track_exposure_event(config, "banner", exposure) + :sys.get_state(pid) + end) + + # Then it's buffered again, the buffer dropping its oldest event for it + assert log =~ "dropping the oldest event_2 event" + events = :queue.to_list(state.buffer) + assert ["event_3" | _] = Enum.map(events, & &1.event) + assert %{event: "$flag_exposure", feature_name: "banner"} = List.last(events) + end + + test "an exposure dropped when a kept batch no longer fits the buffer is tracked again", %{ + config: config + } do + # Given a batch with an exposure, held then failed by the events API, while the + # buffer fills up with events tracked meanwhile + test_pid = self() + + stub(Tesla.Adapter.Mock, :call, fn tesla_env, _options -> + events = Enum.map(Jason.decode!(tesla_env.body)["events"], & &1["event"]) + send(test_pid, {:holding, self(), events}) + + receive do + :release -> {:ok, %Tesla.Env{status: 503, body: "unavailable"}} + end + end) + + exposure = [identifier: "user_123", value: "treatment"] + + capture_log(fn -> + :ok = Client.track_exposure_event(config, "banner", exposure) + for n <- 2..1000, do: :ok = Client.track_event(config, "event_#{n}") + for n <- 1001..2000, do: :ok = Client.track_event(config, "event_#{n}") + + for _attempt <- 1..3 do + assert_receive {:holding, request, ["$flag_exposure" | _]}, 1000 + send(request, :release) + end + + # The batch is kept, but only the newest 1000 events fit the buffer, which the + # events tracked meanwhile filled up: they're sent straight away. + assert_receive {:holding, _request, ["event_1001" | _]}, 1000 + end) + + # When + :ok = Client.track_exposure_event(config, "banner", exposure) + + # Then + pid = Processor.whereis(config.environment_key) + + assert [%{event: "$flag_exposure", feature_name: "banner"}] = + :queue.to_list(:sys.get_state(pid).buffer) + end + + test "closing the client stops a flush still sending when its timeout expires", %{ + config: config + } do + # Given a flush already sending, which the events API keeps failing slowly + test_pid = self() + + stub(Tesla.Adapter.Mock, :call, fn _tesla_env, _options -> + send(test_pid, :attempt) + Process.sleep(100) + {:ok, %Tesla.Env{status: 503, body: "unavailable"}} + end) + + :ok = Client.track_event(config, "checkout", identifier: "user_123") + pid = Processor.whereis(config.environment_key) + monitor = Process.monitor(pid) + spawn(fn -> send(test_pid, {:flushed, Processor.flush(config.environment_key)}) end) + assert_receive :attempt + + # When + log = capture_log(fn -> assert {:error, :timeout} = Client.close(config, 50) end) + + # Then the flush caller is told, rather than exiting, and nothing more is sent + assert log =~ "Gave up sending events after 50 milliseconds while closing" + assert_receive {:flushed, {:error, :closed}} + assert_receive {:DOWN, ^monitor, :process, ^pid, :normal} + refute_receive :attempt, 500 + end + + test "closing the client while it's already closing is a no-op", %{config: config} do + # Given a close waiting on the events API + test_pid = self() + + stub(Tesla.Adapter.Mock, :call, fn _tesla_env, _options -> + send(test_pid, {:holding, self()}) + + receive do + :release -> {:ok, %Tesla.Env{status: 202, body: ""}} + end + end) + + :ok = Client.track_event(config, "checkout", identifier: "user_123") + spawn(fn -> send(test_pid, {:closed, Client.close(config)}) end) + assert_receive {:holding, request} + + # When / Then + assert :noop = Client.close(config) + send(request, :release) + assert_receive {:closed, :ok} + end + + test "flushing events after the processor has stopped is a no-op", %{config: config} do + # Given + expect(Tesla.Adapter.Mock, :call, fn _, _ -> {:ok, %Tesla.Env{status: 202}} end) + :ok = Client.track_event(config, "checkout", identifier: "user_123") + :ok = Client.close(config) + + # When / Then + assert :noop = Client.flush_events(config) + end + + test "flushing events requires events to be enabled" do + assert {:error, :events_disabled} = Client.flush_events(environment_key: "A") + end + test "nothing is sent when there are no events", %{config: config} do # Given expect(Tesla.Adapter.Mock, :call, fn _, _ -> {:ok, %Tesla.Env{status: 202}} end)