Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: use tenants from external source #1967

Merged
merged 5 commits into from
Nov 12, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions packages/sync-service/config/runtime.exs
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,7 @@ case {database_url, default_tenant} do

config :electric, default_connection_opts: Electric.Utils.obfuscate_password(connection_opts)

# if `default_tenant` is nil, generate a random UUID for it
tenant_id = default_tenant || Electric.Utils.uuid4()
tenant_id = default_tenant || "00000000-0000-0000-0000-000000000000"
config :electric, default_tenant: tenant_id
end

Expand Down Expand Up @@ -209,4 +208,6 @@ config :electric,
prometheus_port: prometheus_port,
storage: storage,
persistent_kv: persistent_kv,
listen_on_ipv6?: env!("ELECTRIC_LISTEN_ON_IPV6", :boolean, false)
control_plane: env!("ELECTRIC_CONTROL_PLANE", &Electric.ControlPlane.parse_config/1, nil),
listen_on_ipv6?: env!("ELECTRIC_LISTEN_ON_IPV6", :boolean, false),
tenant_tables_name: :tenant_tables
3 changes: 2 additions & 1 deletion packages/sync-service/lib/electric/application.ex
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,8 @@ defmodule Electric.Application do
},
pool_opts: %{
size: Application.fetch_env!(:electric, :db_pool_size)
}
},
control_plane: Application.get_env(:electric, :control_plane, nil)
}

Electric.Application.Configuration.save(config)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ defmodule Electric.Application.Configuration do
persistent_kv
replication_opts
pool_opts
control_plane
]a

@type t :: %__MODULE__{}
Expand Down
136 changes: 136 additions & 0 deletions packages/sync-service/lib/electric/control_plane.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
defmodule Electric.ControlPlane do
@moduledoc """
Functions that interact with the control plane that exists outside Electric.
"""
require Logger

defstruct [
:base_url,
:auth,
paths: %{
"tenant_shape" => %{
"url" => "/v1/shape",
"params" => %{
"offset" => "-1",
"table" => "databases",
"where" => "electric_url ILIKE '%%{instance_id}'",
msfstef marked this conversation as resolved.
Show resolved Hide resolved
"select" => "id,connection_url"
}
}
}
]

@type t() :: %__MODULE__{
base_url: String.t(),
auth: nil | String.t() | {:basic, String.t()} | {:bearer, String.t()},
paths: %{optional(String.t()) => map()}
}

def parse_config(""), do: nil

def parse_config(config_string) do
result = Jason.decode!(config_string)

%__MODULE__{
base_url: Map.fetch!(result, "base_url"),
auth: Map.get(result, "auth", nil),
paths: Map.get(result, "paths", %__MODULE__{}.paths)
}
end

@spec list_tenants(t(), keyword()) ::
{:ok, included :: list(map()), deleted :: list(map())} | {:error, :unreachable}
def list_tenants(%__MODULE__{} = plane, opts) do
%{electric_instance_id: instance_id} =
Keyword.get_lazy(opts, :app_config, fn -> Electric.Application.Configuration.get() end)

plane
|> build_req("tenant_shape", instance_id)
|> read_electric_api_until_done()
|> case do
{:ok, result} when is_list(result) ->
# We expect the control plane to fulfill the Electric API, so we can decode it here from the complete response
{ins_acc, del_acc} =
result
|> Stream.reject(&get_in(&1, ["headers", "control"]))
|> Stream.map(
&{get_in(&1, ["headers", "operation"]), Map.fetch!(&1, "key"),
Map.fetch!(&1, "value")}
)
|> collect_ops()

{:ok, Map.values(ins_acc), Map.values(del_acc)}

{:ok, %Req.Response{status: status, body: body}} ->
Logger.error(
"Could not reach the control plane while trying to list tenants. Latest response has status #{status} and body #{inspect(body)}"
)

{:error, :unreachable}

{:error, error} ->
Logger.error(
"Could not reach the control plane while trying to list tenants. Latest response was #{inspect(error)}"
)

{:error, :unreachable}
end
end

# We need to read the Electric stream until complete
defp read_electric_api_until_done(req, agg \\ []) do
with {:ok, %Req.Response{status: 200} = resp} <-
Req.get(req, max_retries: 4, retry_delay: 1_000) do
if Req.Response.get_header(resp, "electric-up-to-date") != [] do
{:ok, agg ++ resp.body}
else
[electric_handle] = Req.Response.get_header(resp, "electric-handle")
[electric_offset] = Req.Response.get_header(resp, "electric-offset")

req
|> Req.merge(params: [handle: electric_handle, offset: electric_offset])
|> read_electric_api_until_done(agg ++ resp.body)
end
end
end

defp build_req(%__MODULE__{} = plane, path_name, instance_id) do
%{"url" => url} = path_spec = Map.fetch!(plane.paths, path_name)
url = insert_instance_id(url, instance_id)

params =
path_spec
|> Map.get("params", [])
|> Enum.map(fn {k, v} -> {k, insert_instance_id(v, instance_id)} end)

headers =
path_spec
|> Map.get("headers", [])
|> Enum.map(fn {k, v} -> {k, insert_instance_id(v, instance_id)} end)

Req.new(
base_url: plane.base_url,
url: url,
params: params,
auth: plane.auth,
headers: headers
)
end

defp insert_instance_id(string, instance_id),
do: String.replace(string, "%{instance_id}", to_string(instance_id))

@spec collect_ops(Enumerable.t()) :: {map(), map()}
defp collect_ops(ops) do
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought we had written an elixir client (?) which we could reuse - if not ignore me!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Enum.reduce(ops, {%{}, %{}}, fn
{"insert", key, value}, {ins_acc, del_acc} ->
{Map.put(ins_acc, key, value), del_acc}

{"update", key, value}, {ins_acc, del_acc} ->
{Map.update!(ins_acc, key, &Map.merge(&1, value)), del_acc}

{"delete", key, value}, {ins_acc, del_acc} ->
{Map.delete(ins_acc, key), Map.put(del_acc, key, value)}
end)
end
end
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ defmodule Electric.Plug.RemoveDatabasePlug do
|> send_resp(200, Jason.encode_to_iodata!(tenant_id))
|> halt()

:not_found ->
{:error, :not_found} ->
conn
|> send_resp(404, Jason.encode_to_iodata!("Database #{tenant_id} not found."))
|> halt()
Expand Down
Loading
Loading