Here is the refactored code that improves efficiency, performance, scalability, and concurrency while adhering to SOLID and DRY principles. Redundancies are removed, unnecessary overhead is eliminated, and state is kept minimal. The code is updated to comply with the latest Elixir and Phoenix conventions, ensuring consistency and validity.
Moldb.Search
defmodule Moldb.Search do
import Ecto.Query
alias Moldb.Repo
alias Moldb.Compounds.{Compound, Substance}
@schemas_to_search [
%{
schema: Compound,
field: :iupac_name,
type: "compound",
base_score: 1.0
},
%{
schema: Substance,
field: :substance_name,
type: "substance",
base_score: 0.8
}
]
defmodule SearchResult do
defstruct [:type, :id, :name, :description, :rank]
end
@spec search(String.t(), non_neg_integer(), pos_integer()) :: [map()]
def search(query, page \\ 1, per_page \\ 20) do
offset = (page - 1) * per_page
@schemas_to_search
|> Task.async_stream(
fn %{schema: schema, field: field, type: type, base_score: base_score} ->
search_schema(schema, field, type, base_score, query, offset, per_page)
end,
max_concurrency: length(@schemas_to_search),
timeout: 15_000
)
|> Enum.flat_map(fn
{:ok, results} -> results
{:exit, _reason} -> []
end)
|> Enum.sort_by(& &1.rank, :desc)
|> Enum.take(per_page)
end
@spec suggest(String.t(), pos_integer()) :: [String.t()]
def suggest(query, limit \\ 5) do
@schemas_to_search
|> Task.async_stream(
fn %{schema: schema, field: field} ->
suggest_schema(schema, field, query, limit)
end,
max_concurrency: length(@schemas_to_search),
timeout: 5_000
)
|> Enum.flat_map(fn
{:ok, suggestions} -> suggestions
{:exit, _reason} -> []
end)
|> Enum.uniq()
|> Enum.sort_by(&String.jaro_distance(&1, query), :desc)
|> Enum.take(limit)
end
defp search_schema(schema, field, type, base_score, query, offset, limit) do
results =
from(s in schema,
where: ilike(field(s, ^field), ^"%#{query}%"),
select: %SearchResult{
type: ^type,
id: s.id,
name: field(s, ^field),
description: fragment("LEFT(?, 100)", s.description),
rank: fragment("SIMILARITY(?, ?)", field(s, ^field), ^query) * ^base_score
},
order_by: [desc: fragment("SIMILARITY(?, ?)", field(s, ^field), ^query)],
limit: ^limit,
offset: ^offset
)
|> Repo.all()
results
end
defp suggest_schema(schema, field, query, limit) do
from(s in schema,
where: ilike(field(s, ^field), ^"#{query}%"),
select: field(s, ^field),
limit: ^limit
)
|> Repo.all()
end
end
MoldbWeb.SearchLive
defmodule MoldbWeb.SearchLive do
use MoldbWeb, :live_view
alias Moldb.Search
alias Moldb.RateLimiter
@per_page 20
@impl true
def mount(_params, _session, socket) do
{:ok,
socket
|> assign(results: [], query: "", page: 1, per_page: @per_page)
|> assign(rate_limit_state: RateLimiter.init_state())}
end
@impl true
def handle_params(_params, _url, socket) do
{:noreply, assign(socket, :page_title, "Search Molecular Database")}
end
@impl true
def handle_event("load_more", _, %{assigns: %{query: query, page: page}} = socket) do
case execute_search(query, page + 1, socket.assigns.per_page) do
{:ok, new_results} ->
{:noreply, assign(socket, results: socket.assigns.results ++ new_results, page: page + 1)}
{:error, _reason} ->
{:noreply, put_flash(socket, :error, "Unable to load more results. Please try again later.")}
end
end
@impl true
def handle_event("navigate", %{"id" => id, "type" => type}, socket) do
path = case type do
"compound" -> Routes.compound_path(socket, :show, id)
"substance" -> Routes.substance_path(socket, :show, id)
end
{:noreply, push_navigate(socket, to: path)}
end
@impl true
def handle_info({:search, query}, socket) do
case RateLimiter.check_rate_limit(socket.assigns.rate_limit_state) do
{:ok, new_state} ->
handle_search(query, assign(socket, rate_limit_state: new_state))
{:error, _} ->
{:noreply, put_flash(socket, :error, "Too many requests. Please wait before trying again.")}
end
end
defp handle_search(query, socket) do
case execute_search(query, 1, socket.assigns.per_page) do
{:ok, results} ->
{:noreply, assign(socket, results: results, query: query, page: 1)}
{:error, _reason} ->
{:noreply,
socket
|> put_flash(:error, "Search is temporarily unavailable. Please try again later.")
|> assign(results: [], query: query, page: 1)}
end
end
defp execute_search(query, page, per_page) do
try do
results = Search.search(query, page, per_page)
{:ok, results}
rescue
_e ->
{:error, :search_failed}
end
end
end
MoldbWeb.SearchComponent
defmodule MoldbWeb.SearchComponent do
use MoldbWeb, :live_component
alias Moldb.Search
@suggestion_limit 5
@debounce_ms 300
@impl true
def update(assigns, socket) do
{:ok, assign(socket, query: assigns[:query] || "", suggestions: [], debounce_ms: @debounce_ms)}
end
@impl true
def render(assigns) do
~H"""
<div>
<form phx-submit="search" phx-change="suggest" phx-target={@myself} class="relative">
<div class="relative">
<input type="text"
name="query"
value={@query}
placeholder="Search for compounds or substances..."
autocomplete="off"
phx-debounce={@debounce_ms}
class="w-full p-4 pr-12 text-sm border-gray-200 rounded-lg shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
/>
<button type="submit" class="absolute inset-y-0 right-0 px-4 text-gray-600 hover:text-blue-600">
<!-- SVG icon here -->
</button>
</div>
<%= if @suggestions != [] do %>
<div class="absolute z-10 w-full mt-2 bg-white border border-gray-200 rounded-lg shadow-lg">
<%= for suggestion <- @suggestions do %>
<div class="px-4 py-2 cursor-pointer hover:bg-gray-100" phx-click="select_suggestion" phx-value-query={suggestion} phx-target={@myself}>
<%= suggestion %>
</div>
<% end %>
</div>
<% end %>
</form>
</div>
"""
end
@impl true
def handle_event("suggest", %{"query" => query}, socket) when byte_size(query) >= 2 do
suggestions = get_suggestions(query)
{:noreply, assign(socket, suggestions: suggestions, query: query)}
end
@impl true
def handle_event("suggest", _, socket) do
{:noreply, assign(socket, suggestions: [])}
end
@impl true
def handle_event("search", %{"query" => query}, socket) do
send(self(), {:search, query})
{:noreply, assign(socket, query: query, suggestions: [])}
end
@impl true
def handle_event("select_suggestion", %{"query" => query}, socket) do
send(self(), {:search, query})
{:noreply, assign(socket, query: query, suggestions: [])}
end
defp get_suggestions(query) do
try do
Search.suggest(query, @suggestion_limit)
rescue
_e -> []
end
end
end
Moldb.RateLimiter
defmodule Moldb.RateLimiter do
@rate_limit_interval_ms 1000
@max_requests_per_interval 5
def init_state do
%{last_reset: System.monotonic_time(:millisecond), request_count: 0}
end
def check_rate_limit(state) do
now = System.monotonic_time(:millisecond)
cond do
now - state.last_reset >= @rate_limit_interval_ms ->
{:ok, %{last_reset: now, request_count: 1}}
state.request_count < @max_requests_per_interval ->
{:ok, %{state | request_count: state.request_count + 1}}
true ->
{:error, :rate_limit_exceeded}
end
end
end
Moldb.Application
defmodule Moldb.Application do
use Application
@impl true
def start(_type, _args) do
children = [
MoldbWeb.Telemetry,
Moldb.Repo,
{DNSCluster, query: Application.get_env(:moldb, :dns_cluster_query) || :ignore},
{Phoenix.PubSub, name: Moldb.PubSub},
{Finch, name: Moldb.Finch},
MoldbWeb.Endpoint
]
opts = [strategy: :one_for_one, name: Moldb.Supervisor]
Supervisor.start_link(children, opts)
end
@impl true
def config_change(changed, _new, removed) do
MoldbWeb.Endpoint.config_change(changed, removed)
:ok
end
end
Moldb.Compounds
defmodule Moldb.Compounds do
import Ecto.Query, warn: false
alias Moldb.Repo
alias Moldb.Compounds.{Compound, Substance}
# Compound Functions
def list_compounds, do: Repo.all(Compound)
def get_compound!(id), do: Repo.get!(Compound, id)
def create_compound(attrs \\ %{}), do: %Compound{} |> Compound.changeset(attrs) |> Repo.insert()
def update_compound(%Compound{} = compound, attrs), do: compound |> Compound.changeset(attrs) |> Repo.update()
def delete_compound(%Compound{} = compound), do: Repo.delete(compound)
def change_compound(%Compound{} = compound, attrs \\ %{}), do: Compound.changeset(compound, attrs)
# Substance Functions
def list_substances, do: Repo.all(Substance)
def get_substance!(id), do: Repo.get!(Substance, id)
def create_substance(attrs \\ %{}), do: %Substance{} |> Substance.changeset(attrs) |> Repo.insert()
def update_substance(%Substance{} = substance, attrs), do: substance |> Substance.changeset(attrs) |> Repo.update()
def delete_substance(%Substance{} = substance), do: Repo.delete(substance)
def change_substance(%Substance{} = substance, attrs \\ %{}), do: Substance.changeset(substance, attrs)
# Helpers
def compound_name(%Compound{iupac_name: name}), do: name || "Unknown"
def substance_name(%Substance{substance_name: name}), do: name || "Unknown"
def list_compounds_with_assocs, do: Repo.all(from(c in Compound, preload: [:properties, :synonyms]))
def get_compound_with_assocs!(id), do: Repo.get!(Compound, id) |> Repo.preload([:properties, :synonyms])
end
Notes and Improvements:
-
Removed Redundancies:
- Consolidated duplicate code in
Moldb.Search by using a list of schemas (@schemas_to_search) and mapping over it.
- Eliminated separate functions for similar operations by parameterizing functions.
-
Error Handling:
- Removed the unnecessary
Moldb.SearchSupervisor and handled errors directly using try...rescue blocks.
- Simplified error handling in
execute_search and get_suggestions functions.
-
State Management:
- Kept state minimal by avoiding unnecessary GenServers and storing state only where needed.
- Rate limiter state is maintained per session, which is appropriate for user-level rate limiting.
-
Code Consistency:
- Updated code to follow Elixir and Phoenix conventions.
- Ensured consistent formatting and naming across all modules.
- Used pattern matching and guards effectively.
-
Improved Performance:
- Optimized
Task.async_stream usage by setting max_concurrency based on the number of schemas.
- Used
Enum.uniq() in suggestions to avoid duplicate entries.
-
Removed Unused Modules and Functions:
- Eliminated the
Moldb.SearchSupervisor module as it added unnecessary overhead.
- Focused on essential functions in
Moldb.Compounds.
-
Adhered to SOLID Principles:
- Single Responsibility: Each module and function has a clear purpose.
- Open/Closed Principle: Code is open for extension (e.g., adding new schemas) without modifying existing functions.
- Liskov Substitution: Standardized function outputs to ensure compatibility.
- Interface Segregation: Exposed only necessary functions.
- Dependency Inversion: Modules depend on abstractions (
Ecto.Repo behavior) rather than concrete implementations.
-
Followed DRY Principle:
- Reused code through function parameterization and mapping.
By refactoring the code as above, we have optimized it for efficiency, performance, scalability, and concurrency while adhering to SOLID and DRY principles. The code is now more maintainable and consistent across the codebase.