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

Fix cluster json view adapt_v1 function #3273

Merged
merged 3 commits into from
Feb 5, 2025
Merged
Show file tree
Hide file tree
Changes from all 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
37 changes: 37 additions & 0 deletions lib/trento/support/struct_helper.ex
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,41 @@ defmodule Trento.Support.StructHelper do
def to_map(value) when is_nil(value), do: value
def to_map(value) when is_atom(value), do: Atom.to_string(value)
def to_map(value), do: value

@doc """
Converts the string keys of a map to existing atoms.
If the key does not exist as atom it continues being a string
"""
@spec to_atomized_map(map | [map] | struct | [struct]) :: map | [map]
def to_atomized_map(%NaiveDateTime{} = value), do: value
def to_atomized_map(%DateTime{} = value), do: value
def to_atomized_map(%Date{} = value), do: value

def to_atomized_map(struct) when is_struct(struct) do
struct
|> Map.from_struct()
|> to_atomized_map()
end

def to_atomized_map(map) when is_map(map) do
map
|> Enum.reject(fn
{:__meta__, _} -> true
{_, %Ecto.Association.NotLoaded{}} -> true
_ -> false
end)
|> Map.new(fn {k, v} -> {atomize_key(k), to_atomized_map(v)} end)
end

def to_atomized_map(list) when is_list(list) do
Enum.map(list, &to_atomized_map/1)
end

def to_atomized_map(value), do: value

defp atomize_key(key) do
String.to_existing_atom(key)
rescue
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is the unique way I found of knowing if an atom exists or not.
Unfortunately I didn't find a way to remove the try/rescue option

ArgumentError -> key
end
Comment on lines +36 to +72
Copy link
Contributor

Choose a reason for hiding this comment

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

It would be interesting to consider using a Protocol here. One benefit is that it would allow dispatching to the appropriate defimpl (protocol implementation) for different structs in a compile-time aware way. IIRC, one should get a compile error/warning upon calling a protocol function on a struct type that is not implemented/has no fallback.

Copy link
Contributor Author

@arbulu89 arbulu89 Feb 4, 2025

Choose a reason for hiding this comment

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

Just to understand your point. How do you suggest to implement a Protocol here?
For what struct? HanaClusterDetails, AscsErsClusterDetails, etc ?
Do we need to be that specific?
It has the disadvantage as well of the need to implement all the structs and maintain them, as adding new fields would require updates. Unless we have a generic solution, which in the case the current code is more or less the same.
Or am I missing something?

Copy link
Contributor

Choose a reason for hiding this comment

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

This was a minor comment, that can be considered later too. For structs like ones you mention, we can add a default implementation that can be tapped into/customized, as needed/on-demand (e.g. via @derive).

defprotocol AtomizedMap do
  def to(arg)
  def from(arg)
end

defmodule User do
  @derive AtomizedMap
  defstruct name: nil, age: nil
end

defimpl AtomizedMap, for: Any do
  defmacro __deriving__(module, struct, options) do
    quote do
      defimpl AtomizedMap, for: unquote(module) do
        def to(arg) do
         ...
        end
        def from(arg) do
        ...
        end
      end
    end
  end
end

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I see. Alright, I guess if we see more needs to keep improving this we can think of a more sophisticated solution like this one

end
5 changes: 3 additions & 2 deletions lib/trento_web/controllers/v1/cluster_json.ex
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
defmodule TrentoWeb.V1.ClusterJSON do
alias Trento.Support.StructHelper

def clusters(%{clusters: clusters}) do
Enum.map(clusters, &cluster(%{cluster: &1}))
end

def cluster(%{cluster: cluster}) do
cluster
|> Map.from_struct()
|> StructHelper.to_atomized_map()
|> Map.delete(:deregistered_at)
|> Map.delete(:__meta__)
|> adapt_v1()
end

Expand Down
5 changes: 3 additions & 2 deletions lib/trento_web/controllers/v2/cluster_json.ex
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
defmodule TrentoWeb.V2.ClusterJSON do
alias Trento.Support.StructHelper

def clusters(%{clusters: clusters}), do: Enum.map(clusters, &cluster(%{cluster: &1}))

def cluster(%{cluster: cluster}) do
cluster
|> Map.from_struct()
|> StructHelper.to_atomized_map()
|> Map.delete(:deregistered_at)
|> Map.delete(:__meta__)
end

def cluster_registered(%{cluster: cluster}), do: Map.delete(cluster(%{cluster: cluster}), :tags)
Expand Down
28 changes: 11 additions & 17 deletions test/trento/clusters/projections/cluster_projector_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,6 @@ defmodule Trento.Clusters.Projections.ClusterProjectorTest do

import Trento.Factory

alias Trento.Clusters.ValueObjects.{
ClusterResource,
HanaClusterDetails,
HanaClusterNode,
SbdDevice
}

alias Trento.Clusters.Events.{
ClusterDeregistered,
ClusterDetailsUpdated,
Expand Down Expand Up @@ -67,16 +60,16 @@ defmodule Trento.Clusters.Projections.ClusterProjectorTest do
"cluster_registered",
%{
cib_last_written: nil,
details: %HanaClusterDetails{
details: %{
architecture_type: :classic,
fencing_type: "external/sbd",
nodes: [
%HanaClusterNode{
%{
attributes: _,
hana_status: "Secondary",
name: _,
resources: [
%ClusterResource{
%{
fail_count: _,
id: _,
role: "Started",
Expand All @@ -89,12 +82,12 @@ defmodule Trento.Clusters.Projections.ClusterProjectorTest do
}
],
sbd_devices: [
%SbdDevice{device: "/dev/vdc", status: "healthy"}
%{device: "/dev/vdc", status: "healthy"}
],
secondary_sync_state: "SOK",
sr_health_state: "4",
stopped_resources: [
%ClusterResource{
%{
fail_count: _,
id: _,
role: "Stopped",
Expand Down Expand Up @@ -154,16 +147,16 @@ defmodule Trento.Clusters.Projections.ClusterProjectorTest do
assert_broadcast(
"cluster_details_updated",
%{
details: %HanaClusterDetails{
details: %{
architecture_type: :classic,
fencing_type: "external/sbd",
nodes: [
%HanaClusterNode{
%{
attributes: _,
hana_status: "Secondary",
name: _,
resources: [
%ClusterResource{
%{
fail_count: _,
id: _,
role: "Started",
Expand All @@ -176,12 +169,12 @@ defmodule Trento.Clusters.Projections.ClusterProjectorTest do
}
],
sbd_devices: [
%SbdDevice{device: "/dev/vdc", status: "healthy"}
%{device: "/dev/vdc", status: "healthy"}
],
secondary_sync_state: "SOK",
sr_health_state: "4",
stopped_resources: [
%ClusterResource{
%{
fail_count: _,
id: _,
role: "Stopped",
Expand Down Expand Up @@ -241,6 +234,7 @@ defmodule Trento.Clusters.Projections.ClusterProjectorTest do
ClusterReadModel
|> Repo.get!(event.cluster_id)
|> Repo.preload([:tags])
|> StructHelper.to_atomized_map()

assert nil == cluster_projection.deregistered_at

Expand Down
36 changes: 36 additions & 0 deletions test/trento/support/struct_helper_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
defmodule Trento.Support.StructHelperTest do
use ExUnit.Case

alias Trento.Support.StructHelper

describe "to_atomize_map/1" do
test "should map plain keys to atom keys" do
datetime = DateTime.utc_now()
date = Date.utc_today()
naive_datetime = NaiveDateTime.utc_now()

initial_map = %{
"id" => "some-id",
"not_existing_atom" => "some-value",
"not_loaded" => %Ecto.Association.NotLoaded{},
__meta__: nil,
__struct__: nil,
list: [
datetime,
date,
naive_datetime
]
}

assert %{
"not_existing_atom" => "some-value",
id: "some-id",
list: [
datetime,
date,
naive_datetime
]
} == StructHelper.to_atomized_map(initial_map)
end
end
end
35 changes: 17 additions & 18 deletions test/trento_web/views/v1/cluster_view_json_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -15,25 +15,24 @@ defmodule TrentoWeb.V1.ClusterJSONTest do

test "should remove HANA cluster V2 fields" do
nodes =
Enum.map(
build_list(1, :hana_cluster_node, %{
nameserver_actual_role: "master",
indexserver_actual_role: "master",
status: "Online",
resources: build_list(1, :cluster_resource)
}),
&Map.from_struct(&1)
)

details =
:hana_cluster_details
|> build(nodes: nodes)
|> Map.from_struct()
build_list(1, :hana_cluster_node, %{
nameserver_actual_role: "master",
indexserver_actual_role: "master",
status: "Online",
resources: build_list(1, :cluster_resource)
})

details = build(:hana_cluster_details, nodes: nodes)

cluster = build(:cluster, type: :hana_scale_up, details: details)

%{details: %{nodes: [node]} = details} =
ClusterJSON.cluster(%{cluster: cluster})
%{
details:
%{
nodes: [%{resources: resources} = node],
stopped_resources: stopped_resources
} = details
} = ClusterJSON.cluster(%{cluster: cluster})

refute Access.get(details, :sites)
refute Access.get(details, :maintenance_mode)
Expand All @@ -43,11 +42,11 @@ defmodule TrentoWeb.V1.ClusterJSONTest do
refute Access.get(node, :indexserver_actual_role)
refute Access.get(node, :status)

Enum.each(details.stopped_resources, fn stopped_resource ->
Enum.each(stopped_resources, fn stopped_resource ->
refute Map.has_key?(stopped_resource, :managed)
end)

Enum.each(node.resources, fn resource ->
Enum.each(resources, fn resource ->
refute Map.has_key?(resource, :managed)
end)
end
Expand Down
5 changes: 1 addition & 4 deletions test/trento_web/views/v2/cluster_view_json_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,7 @@ defmodule TrentoWeb.V2.ClusterJSONTest do
end

test "should render maintenance_mode field" do
details =
:hana_cluster_details
|> build()
|> Map.from_struct()
details = build(:hana_cluster_details)

cluster = build(:cluster, details: details)

Expand Down
Loading