<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sergey Chechaev on Medium]]></title>
        <description><![CDATA[Stories by Sergey Chechaev on Medium]]></description>
        <link>https://medium.com/@SergeyChechaev?source=rss-8561476f7ca5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KH9w18uHefzsAkm5x7gjFQ@2x.jpeg</url>
            <title>Stories by Sergey Chechaev on Medium</title>
            <link>https://medium.com/@SergeyChechaev?source=rss-8561476f7ca5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 00:06:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@SergeyChechaev/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Railway Oriented Programming]]></title>
            <link>https://medium.com/better-programming/railway-oriented-programming-4ee949a3b444?source=rss-8561476f7ca5------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ee949a3b444</guid>
            <category><![CDATA[phoenix-framework]]></category>
            <category><![CDATA[erlang]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[Sergey Chechaev]]></dc:creator>
            <pubDate>Mon, 06 Mar 2023 17:09:38 GMT</pubDate>
            <atom:updated>2023-04-25T13:55:01.507Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*WgFLdydgkeciz3T5w5c4ew.png" /><figcaption>Image generated by Midjourney</figcaption></figure><p>This pattern is one of the useful patterns for functional programming languages, especially for the Elixir programming language, because of pattern matching. You can read more about it in the articles below:</p><ol><li><a href="https://medium.com/elixirlabs/railway-oriented-programming-in-elixir-with-pattern-matching-on-function-level-and-pipelining-e53972cede98">Railway Oriented Programming in Elixir with Pattern Matching on Function Level and Pipelining</a></li><li><a href="https://cbailey.co.uk/posts/elixirs_with_statement_and_railway_oriented_programming#">Elixir’s </a><a href="https://cbailey.co.uk/posts/elixirs_with_statement_and_railway_oriented_programming#">with statement and Railway Oriented Programming</a></li></ol><p>This article will show you how clear and easy it is to solve difficult issues and write code that is really simple to read and maintain.</p><p>We continue to develop our example application, as seen in the following link: <a href="https://github.com/sergey-chechaev/example_app">https://github.com/sergey-chechaev/example_app</a>, to show you the benefits of this pattern and how it works.</p><p>Let’s imagine an external service sends some data to our endpoint, and we need to save data to different data tables, send an email and run a background job. This time, create a service that can do all the above using the railway approach.</p><ol><li>Create the folder services and a payment_executor.ex file in which to put this logic:</li></ol><pre>mkdir lib/services/ &amp;&amp; touch lib/services/payment_executor.ex</pre><p>2. Write a module doc explaining what this service does.</p><pre>defmodule Services.PaymentExecutor do<br>  @moduledoc &quot;&quot;&quot;<br>    This service creates the payment, an invoice and<br>    sends an email to the manager and calculates statistics<br>  &quot;&quot;&quot;<br>end</pre><p>3. Write a struct that helps to implement the railway pattern. This struct must contain two required attributes: valid? and error.</p><pre>defmodule Services.PaymentExecutor do<br>  @moduledoc &quot;&quot;&quot;<br>    This service creates the payment, an invoice and<br>    sends an email to the manager and calculates statistics<br>  &quot;&quot;&quot;<br><br>  defstruct payment_params: nil,<br>            payment: nil,<br>            invoice: nil,<br>            valid?: true,<br>            error: nil<br>end</pre><p>Defstruct helps to provide compile-time checks, default values, and it also provides specifications to understand the data this service works with. Attributes payment_params, payment andinvoice are needed to store data for the functions described below.</p><p>Define this module as a service, so a function call is used for the entry point. This function must consist of functions that solve specific tasks. Their names are explanatory and help to read the function call as a specification:</p><pre>defmodule Services.PaymentExecutor do<br>  @moduledoc &quot;&quot;&quot;<br>    This service creates the payment, an invoice and<br>    sends an email to the manager and calculates statistics<br>  &quot;&quot;&quot;<br><br>  defstruct payment_params: nil,<br>            payment: nil,<br>            invoice: nil,<br>            valid?: true,<br>            error: nil<br><br>  def call(payment_params) do<br>    payment_params<br>    |&gt; build_struct()<br>    |&gt; create_payment()<br>    |&gt; create_invoice()<br>    |&gt; send_email()<br>    |&gt; execute_statistic_worker()<br>    |&gt; transform_result()<br>  end<br>end</pre><p>The function call can be read as a specification.</p><ul><li>build_struct — fill in the structure of the module Services.PaymentExecutor</li><li>create_payment — insert data to the payment’s data table</li><li>create_invoice –insert data to the invoice’s data table</li><li>send_email — send an email to the manager</li><li>execute_statistic_worker — start background job to calculate some payment statistics</li><li>transform_result — the last function that returns results</li></ul><p>All that remains is to implement these functions by using the Railway Pattern.</p><p>4. Create the schema Invoice for the same context Payments</p><pre>mix phx.gen.json Payments Invoice invoices from:string bill_to:string amount:decimal tax:decimal</pre><p>We add the Schema Invoice to show how we can use this pattern for solving issues when we need to insert data into many tables. In OOP languages, we use Pattern Service Object or Form Object. For functional programming, languages like Elixir and Railway-Oriented Programming have common principles.</p><p>5. The best practice in the Elixir community is to create good documentation and specifications for the module.</p><p>See the following example:</p><pre>@type payment_executor_struct_t :: %__MODULE__{}<br>  @spec call(<br>          payment_params ::<br>            Map.t(<br>              sum: float(),<br>              bonus: float(),<br>              tax: float(),<br>              operation_type: Enum.values(Payment, :operation_type),<br>              pay_period_from: UtcDate.t(),<br>              pay_period_to: UtcDate.t()<br>            )<br>        ) ::<br>          Tuple.t(:error, Ecto.Changeset.t())<br>          | Tuple.t(:ok, payment_executor_struct_t())</pre><ul><li>@type payment_executor_struct_t — define custom types helps communicate the intention of your code and increase its readability. Describing the module struct itself helps to understand what the module is to return.</li><li>@spec call() — define function specification indicates what external parameters look like and their type.</li></ul><p>6. Add all necessary functions. All the functions listed below are private. Since they are hidden for execution, it is indicated that only the call function needs to be performed.</p><pre> defp build_struct(payment_params) do<br>   %__MODULE__{payment_params: payment_params}<br> end</pre><ul><li>build_struct — this function needs to prepare initial data and set it to defstruct. This entry point can be used for adding extra data to the struct or manipulating data.</li></ul><pre>defp create_payment(%__MODULE__{valid?: false} = struct), do: struct<br><br>defp create_payment(%__MODULE__{payment_params: payment_params} = struct) do<br>    case Payments.create_payment(payment_params) do<br>      {:ok, %Payment{} = payment} -&gt;<br>        %__MODULE__{struct | payment: payment}<br><br>      {:error, error} -&gt;<br>        %__MODULE__{<br>          struct<br>          | valid?: false,<br>            error: {:create_payment, &quot;can&#39;t create Payment #{inspect(error)}&quot;}<br>        }<br>    end<br>end</pre><ul><li>create_payment — the first function that illustrates the action of the principle of the railway pattern. The beauty of pattern matching is revealed here in full. If the value of the attribute valid? is false, this means we get red railway, and we return struct without any business logic execution.<br>Conversely, if the value of the attribute valid? is true, this means that we get a green railway, and the business logic will be executed. Inside this function for the green railway, we create Payment and store the result in Module struct. If we can’t create Payment , for example, because of validation, we set the attribute valid? to false and the next function produces a red railway match.</li></ul><pre>defp create_invoice(%__MODULE__{valid?: false} = struct), do: struct<br><br>defp create_invoice(%__MODULE__{payment: %{sum: amount, tax: tax}} = struct) do<br>    invoice_params = %{<br>      amount: amount,<br>      tax: tax,<br>      from: &quot;example app&quot;,<br>      bill_to: &quot;other example app&quot;<br>    }<br><br>    case Payments.create_invoice(invoice_params) do<br>      {:ok, %Invoice{} = invoice} -&gt;<br>        struct<br><br>      {:error, error} -&gt;<br>        %__MODULE__{<br>          struct<br>          | valid?: false,<br>            error: {:create_invoice, &quot;can&#39;t create Invoice #{inspect(error)}&quot;}<br>        }<br>    end<br>  end</pre><ul><li>create_invoice — is similar to the create_payment and has the same pattern matching for the red and green paths. Inside this function, we create an invoice and store data to struct or set the attribute valid? to false and the next function produces a red railway path.</li></ul><pre>  defp send_email(%__MODULE__{valid?: false} = struct), do: struct<br><br>  defp send_email(struct) do<br>    IO.puts(&quot;Execute the worker to send an email to the manager&quot;)<br>    struct<br>  end<br><br>  defp execute_statistic_worker(%__MODULE__{valid?: false} = struct), do: struct<br><br>  defp execute_statistic_worker(struct) do<br>    IO.puts(&quot;Execute the worker to calculate statistics&quot;)<br>    struct<br>  end</pre><ul><li>send_email, execute_statistic_worker — this function emulates sending an email to someone and executes worker. In other words, it starts the background job. These functions have the same pattern-matching principle to produce red and green paths.</li></ul><pre> defp transform_result(%__MODULE__{valid?: false, error: error} = struct) do<br>   Logger.error(inspect(error))<br>   {:error, struct}<br> end<br><br> defp transform_result(struct) do<br>   {:ok, struct}<br> end</pre><ul><li>transform_result — this function, the last function in the pipeline, returns struct tuple {:ok, payment_executor_strucy} or {:error, payment_exacutor_struct}. It’s easy to use for matching red or green path in other services or controllers. Use Logger.error to catch errors in console or logger services if we get a red path. Logger.error helps to debug in the future. Sentry or other debugging services can also be used to send information.</li></ul><p>7. Add this service to the Internal Controller.</p><pre>defmodule ExampleAppWeb.Internal.PaymentController do<br>  use ExampleAppWeb, :controller<br><br>  alias ExampleApp.Payments.Payment<br>  alias Params.Internal.Payment, as: PaymentParams<br>  alias Services.PaymentExecutor<br><br>  action_fallback ExampleAppWeb.FallbackController<br><br>  def create(conn, payment_params) do<br>    with {:ok, prepared_params} &lt;- PaymentParams.prepare(:create, payment_params),<br>         params &lt;- Map.from_struct(prepared_params),<br>         {:ok, %{payment: payment}} &lt;- PaymentExecutor.call(params) do<br>      conn<br>      |&gt; put_status(:created)<br>      |&gt; put_resp_header(&quot;location&quot;, Routes.payment_path(conn, :show, payment))<br>      |&gt; render(ExampleAppWeb.PaymentView, &quot;show.json&quot;, payment: payment)<br>    end<br>  end<br>end</pre><p>Replace the Payments module with PaymentExecuter and as a result, business logic is hidden from the controller to this service. An option is to add action_fallback ExampleAppWeb.FallbackController to handle errors, therefore creating a service that puts all errors into Ecto.Changeset struct.</p><p>8. To facilitate work with errors, add a new module Services.ErrorBuilder.</p><pre>defmodule Services.ErrorBuilder do<br>  @moduledoc &quot;&quot;&quot;<br>  Wrap error into Ecto.Changeset struct<br>  &quot;&quot;&quot;<br><br>  import Logger<br>  alias Ecto.Changeset<br><br>  def call(error, module) do<br>    if Application.get_env(:pushsms, :env)  != :test do<br>      Logger.error(%{module: module, description: error})<br>    end<br><br>    call(error)<br>  end<br><br>  def call({key, message}),<br>    do: %Changeset{types: Map.new([{:key, :string}])} |&gt; Changeset.add_error(key, message)<br><br>  def call(%Changeset{} = error), do: error<br>end</pre><p>This service helps to work with errors in a familiar way because it wraps errors to Changeset.</p><p>The function transform_result in PaymentExecuter needs modifying like this:</p><pre>defp transform_result(%__MODULE__{valid?: false, error: error}) do<br>  {:error, ErrorBuilder.call(error, __MODULE__)}<br>end<br><br>defp transform_result(struct) do<br>  {:ok, struct}<br>end</pre><p>As a result, action_fallback is used to handle errors that may occur when performing the PaymentExecutor service.</p><h3>Conclusion</h3><p>The benefits of using the Railway pattern are:</p><ol><li>The Controller is thin, easy to read, and maintains and follows the principle single responsibility (the letter S from SOLID).</li><li>It is easy to test business logic because it is separate from the controller, and there is no need to emulate POST or GET requests.</li><li>PaymentExecutor is easy to expose and not change the code. Otherwise, the principle Open-Close (the letter O from SOLID) would be broken.</li><li>The service PaymentExecuter helps to get rid of nested cases.</li><li>This approach is convenient to use when there is more than one record and also maintains complex form or business logic.</li><li>The red and green paths help to handle errors.</li><li>This provides a service with a specification that is easy to read, maintain and understand.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ee949a3b444" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/railway-oriented-programming-4ee949a3b444">Railway Oriented Programming</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design pattern parameter]]></title>
            <link>https://medium.com/@SergeyChechaev/design-pattern-parameter-724150a59191?source=rss-8561476f7ca5------2</link>
            <guid isPermaLink="false">https://medium.com/p/724150a59191</guid>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[phoenix-framework]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sergey Chechaev]]></dc:creator>
            <pubDate>Thu, 29 Dec 2022 11:18:09 GMT</pubDate>
            <atom:updated>2022-12-29T11:33:02.661Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*xzsLpAjTFb9ma8hxBctX5w.jpeg" /></figure><p>Sometimes we need to unify data that we get from external services. For example, we have two different versions of endpoint but under the hood we need to use the same services. Also, we want to check external data types, validate data especially if we are talking about non database validation, and calculate or execute something that prepares data before sending it to services. This pattern has common principles like Protocol Buffers and XML where we also have mechanisms to describe schema and set data types, but inside the well known Phoenix framework.</p><p>To show this pattern in action, we create a simple application,<a href="https://github.com/sergey-chechaev/example_app"> https://github.com/sergey-chechaev/example_app</a>, where we have endpoint <strong>Payments</strong> for obtaining payment information from an external system.</p><p>So lats generates the <strong>controller</strong>, <strong>view</strong>, and <strong>context</strong> for a <strong>Payment </strong>JSON resource.</p><pre>mix phx.gen.json Payments Payment payment_logs \<br>sum:decimal bonus:decimal tax:decimal \<br>operation_type:enum:refill:withdrawal \<br>status:enum:initial:processed:rejected \<br>comment:text pay_period_from:utc_datetime \<br>pay_period_to:utc_datetime</pre><p>Imagine that the external service sends data for us to create <strong>Payment</strong></p><pre>curl -X POST \<br>  &#39;http://localhost:4000/api/payments?sum=100&amp;operation_type=refill&amp;pay_period_from=2022-10-01&amp;comment=comment&#39;</pre><p>We get the errors</p><pre>{<br>    &quot;errors&quot;: {<br>        &quot;bonus&quot;: [<br>            &quot;can&#39;t be blank&quot;<br>        ],<br>        &quot;pay_period_from&quot;: [<br>            &quot;is invalid&quot;<br>        ],<br>        &quot;pay_period_to&quot;: [<br>            &quot;can&#39;t be blank&quot;<br>        ],<br>        &quot;status&quot;: [<br>            &quot;can&#39;t be blank&quot;<br>        ],<br>        &quot;tax&quot;: [<br>            &quot;can&#39;t be blank&quot;<br>        ]<br>    }<br>}</pre><p>The problem here is that we must send other required attributes, but what if we need to calculate status, tax, bonus, pay_period_to itself, format pay_period_from and create a record in another table. But at the same time, we don’t want to change the <strong>changeset </strong>and<strong> context</strong>. There may be many variants to solve this issue, let’s look at <strong>Pattern Parameter.</strong></p><p>Firstly, we need to create special interface <strong>params </strong>such as <strong>controller</strong>, <strong>view</strong>, <strong>changeset</strong> and so on. Inside entrypoint <strong>lib/example_app_web.ex </strong>add new function <strong>params,</strong> the definition of this function will be executed for every <strong>params</strong> interface.</p><pre>def params do<br>    quote do<br>      use Ecto.Schema<br>      import Ecto.Changeset<br>      import ExampleAppWeb.Gettext<br><br>      @primary_key false<br><br>      def fetch(term, key) do<br>        term<br>        |&gt; Map.from_struct()<br>        |&gt; Map.fetch(String.to_existing_atom(key))<br>      end<br>    end<br> end</pre><p>– <strong>Ecto.Schema </strong>for maps external data into Elixir structs.</p><p>– <strong>Ecto.Changeset </strong>for<strong> </strong>filtering, casting, validation and definition of constraints when manipulating structs.</p><p>– <strong>ExampleAppWeb.Gettext</strong> for based API for working with internationalized applications.</p><p>– <strong>@primary_key</strong> <strong>false</strong> to disable generation of additional primary key fields.</p><p>– <strong>fetch</strong> is the function for fetching data from struct. We can add other functions here if we need to.</p><p>Secondly, we add new folder <strong>params </strong>where we will save our <strong>params</strong> modules: mkdir lib/example_app_web/params</p><p>Then create the first <strong>params</strong> module Params.External.Payment We use <strong>external</strong> scope to show that we can use different formatting for different endpoints:</p><pre>mkdir lib/example_app_web/params/external/ &amp;&amp; touch lib/example_app_web/params/external/payment.ex</pre><p>And add code to it:</p><pre>defmodule Params.External.Payment do<br>  @moduledoc &quot;&quot;&quot;<br>    Resolves validation params for external payment creation<br>  &quot;&quot;&quot;<br>  use ExampleAppWeb, :params<br><br>  alias ExampleApp.Payments.Payment<br>  alias Ecto.Enum<br><br>  @required [:operation_type, :sum]<br><br>  embedded_schema do<br>    field :bonus, :decimal, default: 0<br>    field :comment, :string<br>    field :operation_type, Enum, values: Enum.values(Payment, :operation_type)<br>    field :status, Enum, values: Enum.values(Payment, :status)<br>    field :pay_period_from, :utc_datetime<br>    field :pay_period_to, :utc_datetime<br>    field :sum, :decimal<br>    field :tax, :decimal, default: 0<br>  end<br><br>  def prepare(:create, params) do<br>    params<br>    |&gt; create_changeset()<br>    |&gt; apply_action(:insert)<br>  end<br><br>  defp create_changeset(params) do<br>    %__MODULE__{}<br>    |&gt; cast(params, [<br>      :operation_type,<br>      :status,<br>      :sum,<br>      :bonus,<br>      :pay_period_from,<br>      :pay_period_to,<br>      :tax<br>    ])<br>    |&gt; validate_required(@required)<br>  end<br>end<br><br></pre><p>For this external endpoint, we only need <strong>:operation_type</strong> and <strong>:sum</strong>.</p><p>–<strong>use ExampleAppWeb, :params</strong> here we add our new function that we define inside the entrypoint.</p><p>–<strong>embedded_schema</strong> to validate data, set data type and show how the data is represented in your applications.</p><p>– <strong>prepare(:create, params)</strong> is the entrypoint to execute this module inside the controller for the action create.</p><p>– <strong>create_changeset</strong> for casting parameters and validation.</p><p>Now execute this module and see how it works:</p><pre>iex(1)&gt; Params.External.Payment.prepare(:create, %{operation_type: :refill, sum: 100})<br><br>{:ok,<br> %Params.External.Payment{<br>   bonus: 0,<br>   comment: nil,<br>   operation_type: :refill,<br>   pay_period_from: nil,<br>   pay_period_to: nil,<br>   status: nil,<br>   sum: #Decimal&lt;100&gt;,<br>   tax: 0<br> }}<br></pre><p>As a result, we get what we need for this external endpoint, only two requirement fields were transferred. But we can’t send this struct to module <strong>Payment</strong> because we need to calculate other requirement fields for this. Let’s do that.</p><pre>  def prepare(:create, params) do<br>    params<br>    |&gt; cast_start_pay_period()<br>    |&gt; cast_end_pay_period()<br>    |&gt; maybe_add_bonus_sum()<br>    |&gt; add_tax()<br>    |&gt; fetch_status()<br>    |&gt; create_changeset()<br>    |&gt; apply_action(:insert)<br>  end<br><br>  defp cast_start_pay_period(params) do<br>    pay_period_from =<br>      Timex.today()<br>      |&gt; Timex.to_datetime()<br><br>    Map.put(params, &quot;pay_period_from&quot;, pay_period_from)<br>  end<br><br>  def cast_end_pay_period(params) do<br>    pay_period_to =<br>      Timex.today()<br>      |&gt; Timex.end_of_month()<br>      |&gt; Timex.to_datetime()<br><br>    Map.put(params, &quot;pay_period_to&quot;, pay_period_to)<br>  end<br><br>  defp maybe_add_bonus_sum(<br>         %{<br>           operation_type: :refill,<br>           sum: sum<br>         } = params<br>       ) do<br>    Map.put(params, &quot;bonus&quot;, Payment.calculate_bonus(sum))<br>  end<br><br>  defp maybe_add_bonus_sum(params), do: params<br><br>  defp add_tax(%{sum: sum, operation_type: :refill} = params) do<br>    Map.put(params, &quot;tax&quot;, Payment.calculate_tax(sum))<br>  end<br><br>  defp add_tax(params), do: params<br><br>  def fetch_status(params) do<br>    {:ok, status} = fetch(Payment, &quot;status&quot;)<br>    Map.put(params, &quot;status&quot;, status)<br>  end</pre><p>We also need to add the functions <strong>calculate_bonus</strong> and <strong>calculate_tax</strong> to the <strong>Payment Changeset:</strong></p><pre>defmodule ExampleApp.Payments.Payment do<br>  use Ecto.Schema<br>  import Ecto.Changeset<br><br>  @tax_percent 0.1<br><br>  schema &quot;payment_logs&quot; do<br>    field :bonus, :decimal<br>    field :comment, :string<br>    field :operation_type, Ecto.Enum, values: [:refill, :withdrawal]<br>    field :pay_period_from, :utc_datetime<br>    field :pay_period_to, :utc_datetime<br>    field :status, Ecto.Enum, values: [:initial, :processed, :rejected], default: :initial<br>    field :sum, :decimal<br>    field :tax, :decimal<br><br>    timestamps()<br>  end<br><br>  @doc false<br>  def changeset(payment, attrs) do<br>    payment<br>    |&gt; cast(attrs, [:sum, :bonus, :tax, :operation_type, :status, :comment, :pay_period_from, :pay_period_to])<br>    |&gt; validate_required([:sum, :bonus, :tax, :operation_type, :status, :pay_period_from, :pay_period_to])<br>  end<br><br>  def calculate_bonus(sum) do<br>    sum = Decimal.new(sum) |&gt; Decimal.to_float()<br>    case sum do<br>      n when n &gt;= 100 -&gt;<br>        2<br>      _ -&gt;<br>        0<br>    end<br>  end<br><br>  def calculate_tax(sum) do<br>    sum = Decimal.new(sum) |&gt; Decimal.to_float()<br>    sum * @tax_percent<br>  end<br>end</pre><p>Then execute <strong>Params.External.Payment </strong>inside <strong>Controller:</strong></p><pre>defmodule ExampleAppWeb.PaymentController do<br>  use ExampleAppWeb, :controller<br><br>  alias ExampleApp.Payments<br>  alias ExampleApp.Payments.Payment<br>  alias Params.External.Payment, as: PaymentParams<br><br>  action_fallback ExampleAppWeb.FallbackController<br><br>  def create(conn, payment_params) do<br>    with {:ok, prepared_params} &lt;- PaymentParams.prepare(:create, payment_params),<br>         params &lt;- Map.from_struct(prepared_params),<br>         {:ok, %Payment{} = payment} &lt;- Payments.create_payment(params) do<br>      conn<br>      |&gt; put_status(:created)<br>      |&gt; put_resp_header(&quot;location&quot;, Routes.payment_path(conn, :show, payment))<br>      |&gt; render(&quot;show.json&quot;, payment: payment)<br>    end<br>  end<br>end</pre><p>Now we can use the same Payment module for different <strong>Params</strong> modules and endpoints. For example: we separate external and internal endpoints. Change <strong>router.ex</strong> by adding internal and external scopes:</p><pre>  scope &quot;/external&quot;, ExampleAppWeb.External do<br>    pipe_through :api<br><br>    resources &quot;/payments&quot;, PaymentController<br>  end<br><br>  scope &quot;/internal&quot;, ExampleAppWeb.Internal do<br>    pipe_through :api<br><br>    resources &quot;/payments&quot;, PaymentController<br>  end</pre><p>Add a <strong>controller</strong> and add a different <strong>Params</strong> module to it where there are different required fields.</p><p><strong>External Controller with External Payment Params</strong></p><pre>mkdir lib/example_app_web/controller/external/ &amp;&amp; touch lib/example_app_web/controller/external/payment_controller.ex</pre><pre>defmodule ExampleAppWeb.External.PaymentController do<br>  use ExampleAppWeb, :controller<br><br>  alias ExampleApp.Payments<br>  alias ExampleApp.Payments.Payment<br>  alias Params.External.Payment, as: PaymentParams<br><br>  def create(conn, payment_params) do<br>    with {:ok, prepared_params} &lt;- PaymentParams.prepare(:create, payment_params),<br>         params &lt;- Map.from_struct(prepared_params),<br>         {:ok, %Payment{} = payment} &lt;- Payments.create_payment(params) do<br>      conn<br>      |&gt; put_status(:created)<br>      |&gt; put_resp_header(&quot;location&quot;, Routes.payment_path(conn, :show, payment))<br>      |&gt; render(ExampleAppWeb.PaymentView, &quot;show.json&quot;, payment: payment)<br>    end<br>  end<br>end</pre><p><strong>Internal Controller with Internal Payment Params</strong></p><pre>mkdir lib/example_app_web/controller/internal/ &amp;&amp; touch lib/example_app_web/controller/internal/payment_controller.ex</pre><pre>defmodule ExampleAppWeb.Internal.PaymentController do<br>  use ExampleAppWeb, :controller<br><br>  alias ExampleApp.Payments<br>  alias ExampleApp.Payments.Payment<br>  alias Params.Internal.Payment, as: PaymentParams<br><br>  def create(conn, payment_params) do<br>    with {:ok, prepared_params} &lt;- PaymentParams.prepare(:create, payment_params),<br>         params &lt;- Map.from_struct(prepared_params),<br>         {:ok, %Payment{} = payment} &lt;- Payments.create_payment(params) do<br>      conn<br>      |&gt; put_status(:created)<br>      |&gt; put_resp_header(&quot;location&quot;, Routes.payment_path(conn, :show, payment))<br>      |&gt; render(ExampleAppWeb.PaymentView, &quot;show.json&quot;, payment: payment)<br>    end<br>  end<br>end</pre><p>And finally create the Internal <strong>Payment</strong> <strong>Params</strong> module with different data logic</p><pre>mkdir lib/example_app_web/params/internal/ &amp;&amp; touch lib/example_app_web/params/internal/payment.ex</pre><pre>defmodule Params.Internal.Payment do<br>  @moduledoc &quot;&quot;&quot;<br>    Resolves validation params for internal payment creation<br>  &quot;&quot;&quot;<br>  use ExampleAppWeb, :params<br><br>  alias ExampleApp.Payments.Payment<br>  alias Ecto.Enum<br><br>  @required [:operation_type, :sum, :bonus, :tax, :comment]<br><br>  embedded_schema do<br>    field :bonus, :decimal<br>    field :comment, :string<br>    field :operation_type, Enum, values: Enum.values(Payment, :operation_type)<br>    field :status, Enum, values: Enum.values(Payment, :status)<br>    field :pay_period_from, :utc_datetime<br>    field :pay_period_to, :utc_datetime<br>    field :sum, :decimal<br>    field :tax, :decimal<br>  end<br><br>  def prepare(:create, params) do<br>    params<br>    |&gt; cast_start_pay_period()<br>    |&gt; cast_end_pay_period()<br>    |&gt; fetch_status()<br>    |&gt; create_changeset()<br>    |&gt; apply_action(:insert)<br>  end<br><br>  defp cast_start_pay_period(params) do<br>    pay_period_from =<br>      Timex.today()<br>      |&gt; Timex.to_datetime()<br><br>    Map.put(params, &quot;pay_period_from&quot;, pay_period_from)<br>  end<br><br>  def cast_end_pay_period(params) do<br>    pay_period_to =<br>      Timex.today()<br>      |&gt; Timex.end_of_month()<br>      |&gt; Timex.to_datetime()<br><br>    Map.put(params, &quot;pay_period_to&quot;, pay_period_to)<br>  end<br><br>  def fetch_status(params) do<br>    {:ok, status} = fetch(Payment, &quot;status&quot;)<br>    Map.put(params, &quot;status&quot;, status)<br>  end<br><br>  defp create_changeset(params) do<br>    %__MODULE__{}<br>    |&gt; cast(params, [<br>      :operation_type,<br>      :status,<br>      :sum,<br>      :bonus,<br>      :pay_period_from,<br>      :pay_period_to,<br>      :tax,<br>      :comment<br>    ])<br>    |&gt; validate_required(@required)<br>  end<br>end</pre><h4>Conclusion</h4><p>We use different endpoints and different <strong>Params</strong> modules, but under the hood we use the same <strong>Payment</strong> context. This approach encapsulates parameters logic, helps us validate and prepare data for our controller and separate responsibility between our incoming data and business logic. It also helps us prepare data for complex service where we use more than one context. We will see this when we create a service based on the pattern <strong>Railway Oriented Programming — </strong>Part 2<strong>.</strong></p><p><a href="https://medium.com/@SergeyChechaev/principles-of-elixir-application-development-a4f5018094c5"><strong>Go to main page</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=724150a59191" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Principles of Elixir Application Development]]></title>
            <link>https://medium.com/@SergeyChechaev/principles-of-elixir-application-development-a4f5018094c5?source=rss-8561476f7ca5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4f5018094c5</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[phoenix-framework]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[patterns]]></category>
            <dc:creator><![CDATA[Sergey Chechaev]]></dc:creator>
            <pubDate>Thu, 29 Dec 2022 11:17:39 GMT</pubDate>
            <atom:updated>2023-03-06T17:10:55.975Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*hyxdhfyJ44ncjnQf23vzQg.jpeg" /></figure><h3>Intro</h3><p>Many programmers use the <strong>Unix</strong>-like system to develop and serve web applications. We often use Unix commands such as: grep, cat, mkdir, ls, ps etc. All these commands have common properties: they solve specific tasks, their utility names are explanatory, they are encapsulated, are idempotent and convenient to use. <strong>Unix</strong> commands are a process. Since one process has an input and the other has an output, and they can be substituted, it is logical to assume that they can be connected. This approach is called the pipeline.</p><p>For example:</p><p>cat mix.exs | grep elixir | uniq | sort</p><ol><li>Read the file <strong>mix.exs</strong></li><li>The input data is grappled by the substring “elixir”</li><li>Duplicates are removed</li><li>The input data is sorted and displayed on the screen</li></ol><p>The main idea is that <strong>Unix</strong> commands have many similarities with Elixir and functional programming. We often use the <strong>pipeline </strong>mechanism in <strong>Elixir</strong> and our function looks like the <strong>Unix</strong> command which drags data through a chain of functions, each of which acts as a converter or filter. When I start to create a new service or solve a new business issue, I try to design functions and programs as separate <strong>Unix</strong> utilities, following the principles below:</p><ol><li>It is important to understand what you are doing and why.</li><li>Always ask yourself why this solution was chosen and how it fits into the concept of the system and how other developers will use it.</li><li>Also important, is the logic of the organization of the code, the context, the names of the classes of modules and of functions.</li><li>There should clearly be a logical chain that, as a guiding star, paves the way to how to use and where to find a particular function. If there is no clear logic and principles in the organization of the code, the system becomes difficult to maintain and difficult to expand.</li><li>It is important not to complicate the system when designing like a Swiss penknife, sometimes simple solutions are more reliable, clearer and easier to expand than complex logic.</li></ol><p>Now let’s try to implement this principle in real life to solve real problems when we are designing an Elixir Web Application.</p><h4><a href="https://medium.com/@SergeyChechaev/design-pattern-parameter-724150a59191">Design pattern parameter — Part 1</a></h4><p>In this chapter, we use this approach to validate data, prepare and unify for further services.</p><h4><a href="https://medium.com/@SergeyChechaev/railway-oriented-programming-4ee949a3b444">Railway Oriented Programming — Part 2</a></h4><p>This pattern helps create the structure of our program as a specification, handle errors, solve nested case statements, and simplify complex logic with the SOLID principle.</p><blockquote>If you like the first and second part, please give me your positive feedback to inspire me to continue writing.</blockquote><h4>Feature toggle — Part 3 (in progress)</h4><p>This chapter covers the principle used for the introduction of new functionality partials for specific users, the turn-off/on function, the A/B test or the test complex functionality in production.</p><h4><strong>Protocol </strong>— Part 4 (in progress)</h4><p>One of the ways to create the pattern Factory for Elixir is to use Protocol, in this chapter we will see how to do it.</p><h4>Presenter — Part 5 (in progress)</h4><p>This pattern helps us prepare and simplify data for our <strong>view</strong>, hide if, case statement and organization code.</p><h4>GenServer organization — Part 6 (in progress)</h4><p>This chapter introduces some principles on how to organize our GenServer, what type of mistake we can make if we don’t understand how GenServer works.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4f5018094c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Selenoid image for Apple Silicon (M1)]]></title>
            <link>https://medium.com/@SergeyChechaev/build-selenoid-image-for-apple-silicon-m1-6dc6fc1a50c1?source=rss-8561476f7ca5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6dc6fc1a50c1</guid>
            <category><![CDATA[silicon]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[selenoid]]></category>
            <category><![CDATA[arm]]></category>
            <category><![CDATA[selenium]]></category>
            <dc:creator><![CDATA[Sergey Chechaev]]></dc:creator>
            <pubDate>Tue, 17 May 2022 11:03:32 GMT</pubDate>
            <atom:updated>2022-05-17T15:24:04.357Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pR5LIpIk6wFxLzpoC2rgvA.jpeg" /></figure><h4>First, we need to prepare the environment</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab538c69b39fdfd3874700cf326648ba/href">https://medium.com/media/ab538c69b39fdfd3874700cf326648ba/href</a></iframe><h4>Then we need to build a basic image</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1a04e7edec8d3e5ea7a01bde6fc1406/href">https://medium.com/media/f1a04e7edec8d3e5ea7a01bde6fc1406/href</a></iframe><p><em>Building basic image will take some time ~ 20 min</em></p><h4>Build Selenoid image for Chrome</h4><p>Files for building image: G<a href="https://github.com/sergey-chechaev/selenoid_m1_docker_files">itHub link</a>.</p><p>I’m uncertain if this is necessary, but it’s probably better that the version of Сhromium and ChromeDriver will be match. Therefore, we look at the repository page with Сhromium: <a href="https://launchpad.net/~saiarcot895/+archive/ubuntu/chromium-beta/+packages">Chromium Beta branch</a>.</p><p>Check at the current version of chromium-browser. At the time of writing the instructions, it was 91. Links to different versions of the ChromeDriver are available <a href="https://stackoverflow.com/questions/38732822/compile-chromedriver-on-arm">here</a>.</p><h4>Download and unzip ChromeDriver</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9be7c3e30c4db99d31b6e7b127c23865/href">https://medium.com/media/9be7c3e30c4db99d31b6e7b127c23865/href</a></iframe><p>In file Dockerfile.chrome, the 12th line specifies the name of the base image that we have just assembled. There, you need to substitute your data M1${hub.dicker.com account/${image name and version} from the base image build.</p><h4>Run build</h4><p>docker buildx build --progress=plain --platform linux/arm64 --file ./Dockerfile.chrome --tag ${hub.docker.com account}/selenium_vnc_chrome_arm64:91.0.a -o type=docker .</p><h4>Run selenoid and selenoid-ui for M1</h4><p>You can use own docker image or a ready-made image:dumbdumbych/selenium_vnc_chrome_arm64:91.0.b</p><ol><li>If you use a ready-made image, download it:</li></ol><pre>docker pull dumbdumbych/selenium_vnc_chrome_arm64:91.0.b</pre><p>2. Create inside the folder config file browsers.json with the following content:</p><pre>{<br>    &quot;chrome&quot;: {<br>        &quot;default&quot;: &quot;chrome&quot;,<br>        &quot;versions&quot;: {<br>            &quot;91.0&quot;: {<br>                &quot;image&quot;: &quot;dumbdumbych/selenium_vnc_chrome_arm64:91.0.b&quot;,<br>                &quot;port&quot;: &quot;4444&quot;,<br>                &quot;path&quot;: &quot;/&quot;,<br>                &quot;privileged&quot;: true<br>            }<br>        }<br>    }<br>}</pre><p>3. In the directory where the config folder is located, run docker with the Selenoid image:</p><pre>docker run -d                                   \<br>--name selenoid                                 \<br>-p 4444:4444                                    \<br>-v /var/run/docker.sock:/var/run/docker.sock    \<br>-v `pwd`/config/:/etc/selenoid/:ro              \<br>--privileged                                    \<br>aerokube/selenoid:latest-release                \<br>-service-startup-timeout 1m</pre><p>4. We check that at the address <a href="http://localhost:4444/">localhost:4444</a>, the solenoid is launched and the status is written:</p><pre>You are using Selenoid 1.10.4!</pre><p>5. Download and run selenoid-ui:</p><pre>docker run -d         \<br>    --name selenoid-ui  \<br>    --link selenoid     \<br>    -p 8080:8080        \<br>    aerokube/selenoid-ui --selenoid-uri=http://selenoid:4444</pre><p>6. Go to <a href="http://localhost:8080/">localhost:8080</a> and check that SSE and SELENOID are in the <strong>connected</strong> status.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q8q944PoVW_UPrxWQD69VQ.png" /></figure><p><strong>Conclusion</strong></p><p>In this article, we created Selenoid Docker image for M1 and run it. I hope everything worked out for you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6dc6fc1a50c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Preload, or not preload, that is the question]]></title>
            <link>https://medium.com/@SergeyChechaev/preload-or-not-preload-that-is-the-question-2b706da51cea?source=rss-8561476f7ca5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b706da51cea</guid>
            <category><![CDATA[ecto]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[phoenix-framework]]></category>
            <category><![CDATA[phoenix]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Sergey Chechaev]]></dc:creator>
            <pubDate>Fri, 17 May 2019 11:36:07 GMT</pubDate>
            <atom:updated>2019-05-20T08:43:34.593Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iFEiMUdRq3gb-bb3z6uh8g.png" /></figure><p>Preload is a part of Ecto.Query module that provides the Query DSL. Preload is a powerful tool that allows you to avoid N+1 queries from negatively affecting our performance. We must explicitly preload the data that we are accessing for an association between data. However, it’s easy to make mistakes when using preload. During the article, I will try to answer questions about making a decision on how to use preload.</p><h4>Questions</h4><ol><li>What&#39;s better: allow preload to generate the extra query or generate one query by ourselves?</li><li>Can we always write one query when using preload?</li><li>Can we get a slow query when using preload for has_many?</li><li>Does preload generate complex structs and hold it in memory?</li></ol><p>In order to answer these questions, we create a little social network which contains the following schema: User, Country, City, Post, PostPhoto.</p><p>– User has many Posts</p><p>– User belongs to Country and City</p><p>– Post has many PostPhotos</p><h3>What’s better: allow preload to generate the extra query or generate one query by ourselves?</h3><p>Now, say we want to display a list of posts with a user that has a country and city. We create function list_user_posts:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91995c1fb5ad5470f8f7609ae4013fe4/href">https://medium.com/media/91995c1fb5ad5470f8f7609ae4013fe4/href</a></iframe><p>Run this function in iex console:</p><pre>Feed.list_user_posts(67) |&gt; Repo.all</pre><p>Ecto.Query generates five queries (I intentionally removed some attributes from <strong>SELECT</strong> replacing them with <strong>… </strong>to make the query more convenient to read):</p><pre>[debug] QUERY OK source=&quot;posts&quot; db=2.8ms decode=0.6ms<br>SELECT p0.&quot;id&quot;, p0.&quot;content&quot;, p0.&quot;created_at&quot;, p0.&quot;deleted_at&quot;, p0.&quot;user_id&quot;, ... FROM &quot;posts&quot; AS p0 WHERE (p0.&quot;user_id&quot; = $1)</pre><pre>[debug] QUERY OK source=&quot;post_photos&quot; db=2.0ms<br>SELECT p0.&quot;id&quot;, p0.&quot;created_at&quot;, p0.&quot;deleted_at&quot;,p0.&quot;post_id&quot;, ... FROM &quot;post_photos&quot; AS p0 WHERE (p0.&quot;post_id&quot; = ANY($1)) ORDER BY p0.&quot;post_id&quot; [[79, 78, 74, 71, 73, 72, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 41, 42, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, ...]]</pre><pre>[debug] QUERY OK source=&quot;users&quot; db=8.8ms<br>SELECT d0.&quot;id&quot;, ... FROM &quot;users&quot; AS d0 WHERE (d0.&quot;id&quot; = $1)</pre><pre>[debug] QUERY OK source=&quot;cities&quot; db=2.8ms queue=0.1ms<br>SELECT d0.&quot;id&quot;, ... FROM &quot;cities&quot; AS d0 WHERE (d0.&quot;id&quot; = $1) </pre><pre>[debug] QUERY OK source=&quot;countries&quot; db=2.7ms queue=0.2ms<br>SELECT d0.&quot;id&quot;, ... FROM &quot;countries&quot; AS d0 WHERE (d0.&quot;id&quot; = $1)</pre><p>So we have 5 queries in total: one query per preloaded association. We can do it with just one query using join and preloading our associations directly into the structs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/246a6889afde290694f367c268a7ee73/href">https://medium.com/media/246a6889afde290694f367c268a7ee73/href</a></iframe><p>We preloaded all of our data using join and binding result to preload and getting one query as a result:</p><pre>[debug] QUERY OK source=&quot;posts&quot; db=21.8ms decode=4.4ms<br>SELECT DISTINCT p0.&quot;id&quot;, <br>FROM &quot;posts&quot; AS p0 <br>LEFT OUTER JOIN &quot;users&quot; AS d1 ON d1.&quot;id&quot; = p0.&quot;user_id&quot; <br>LEFT OUTER JOIN &quot;user_countries&quot; AS d2 ON d2.&quot;id&quot; = d1.&quot;user_country_id&quot; <br>LEFT OUTER JOIN &quot;user_cities&quot; AS d3 ON d3.&quot;id&quot; = d1.&quot;user_city_id&quot; LEFT OUTER JOIN &quot;post_photos&quot; AS p4 ON p4.&quot;post_id&quot; = p0.&quot;id&quot; <br>WHERE (p0.&quot;user_id&quot; = $1) [67]</pre><p>Perfect! We generated a single query instead of five. <a href="https://medium.com/u/2c9426b88373">thoughtbot</a> in their article <a href="https://thoughtbot.com/blog/preloading-nested-associations-with-ecto">https://thoughtbot.com/blog/preloading-nested-associations-with-ecto</a> tell us that Postgres is totally capable of joining multiple tables in a single query and that joins are also a better solution than subqueries. However, we need to check this statement, so let’s do a benchmark. For this, we use lib <a href="https://github.com/bencheeorg/benchee">Benchee</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb58071030e7f1ec928d9fe52d15378a/href">https://medium.com/media/fb58071030e7f1ec928d9fe52d15378a/href</a></iframe><h4>Benchmark suite executing with the following configuration</h4><p>– Ecto 3.1.4<br>– Elixir 1.8<br>– Erlang/OTP 21<br>– Postgres 9.6.11<br>– Operating System: Linux<br>– CPU Information: Intel(R) Xeon(R) CPU E5–2676 v3 @ 2.40GHz<br>– Number of Available Cores: 4<br>– Available memory: 16 GB</p><p>We got almost the same ips for “<strong>Preload 5 query async” </strong>and<strong> “Preload 1 query async” </strong>but <strong>“Preload 1 query async” </strong>uses<strong> </strong>5.8 times more memory. Why do we get this result and <a href="https://context.reverso.net/%D0%BF%D0%B5%D1%80%D0%B5%D0%B2%D0%BE%D0%B4/%D0%B0%D0%BD%D0%B3%D0%BB%D0%B8%D0%B9%D1%81%D0%BA%D0%B8%D0%B9-%D1%80%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9/what">what</a> <em>in_parallel</em> <a href="https://context.reverso.net/%D0%BF%D0%B5%D1%80%D0%B5%D0%B2%D0%BE%D0%B4/%D0%B0%D0%BD%D0%B3%D0%BB%D0%B8%D0%B9%D1%81%D0%BA%D0%B8%D0%B9-%D1%80%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9/settings">setting</a> does<em>? </em>If we open <a href="https://github.com/elixir-ecto/ecto/blob/88affbcea0d345253c1f4795a7853ba1b59899fa/lib/ecto/repo/preloader.ex#L99">Ecto source code</a> we see:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c2c903eb2cfee2e8a76a8bae2fa9112/href">https://medium.com/media/1c2c903eb2cfee2e8a76a8bae2fa9112/href</a></iframe><p>It means Ecto spawns tasks for parallel preload and then adds the data together using the map for better performance. Parameter :in_parallel (Defaults to `true`) can only be performed when we have more than one preload and the repository is not in a transaction.</p><p>So <strong>what’s the best way</strong> <strong>to use preload</strong>? I recommend the following approach:</p><p>– if we have a query with join and we need to preload this association you need to use preload with the binding result.</p><p>– in other cases, it is more effective to use preload without binding. Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/040c8b1b6aa3cd614d877f35bab97797/href">https://medium.com/media/040c8b1b6aa3cd614d877f35bab97797/href</a></iframe><h3>Can we always write one query when using preload?</h3><p>Sometimes we need preload with an ordered data. In this case, you need a separate query:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/996d2c9b2671b3080821ce87c1a7a46a/href">https://medium.com/media/996d2c9b2671b3080821ce87c1a7a46a/href</a></iframe><p>Answering the question, <strong>not always</strong>.</p><h3>Can we get a slow query when using preload for has_many?</h3><p>Function list_user_posts was is not so terrible even without optimization if we have a belongs_to association and we did not notice a performance problem. However, Post has_many association with post_photos and if we preload it we get:</p><pre>[debug] QUERY OK source=&quot;post_photos&quot; db=2.0ms<br>SELECT p0.&quot;id&quot;, p0.&quot;created_at&quot;, p0.&quot;deleted_at&quot;,p0.&quot;post_id&quot;, ... FROM &quot;post_photos&quot; AS p0 WHERE (p0.&quot;post_id&quot; = ANY($1)) ORDER BY p0.&quot;post_id&quot; [[79, 78, 74, 71, 73, 72, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 41, 42, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, ...]]</pre><p>Bigger array for ANY is not so cool because it takes more planning time. <strong>Thus try to preload has_many association by join and binding it to preload or use limit with an offset if you can paginate the data</strong>.</p><h3>Does preload generate complex structs and hold it in memory?</h3><p>Every time when we preload data we load the result in memory. If the schema has many attributes and we create a complex query with many associations all this stuff will be loaded in memory. To solve this problem <strong>use SELECT</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f22123e338787f19b9f50b72fbdd62c/href">https://medium.com/media/1f22123e338787f19b9f50b72fbdd62c/href</a></iframe><p>For example, we need only Post: ID, Content and User: ID, Email. We select these fields and do a benchmark to check the memory usage:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e5c35db9b403f91a3d77b26a3c5ce7f/href">https://medium.com/media/7e5c35db9b403f91a3d77b26a3c5ce7f/href</a></iframe><p>Of course, the result depends on how many fields we need. The main idea is to <strong>select only the necessary fields to reduce memory usage</strong>.</p><h3>Conclusion</h3><p>In this article, we described particular examples which show that preload usage can produce both positive and negative results. For your specific case, you need benchmarking to test preload efficiency. You can move preload to a separate module inside context so that it will be more convenient to work with it later.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b706da51cea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails and Phoenix microservice synergy]]></title>
            <link>https://medium.com/@SergeyChechaev/rails-and-phoenix-microservice-synergy-5433598ab333?source=rss-8561476f7ca5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5433598ab333</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[phoenix]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Sergey Chechaev]]></dc:creator>
            <pubDate>Thu, 21 Sep 2017 08:40:17 GMT</pubDate>
            <atom:updated>2017-09-21T08:48:33.371Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, step by step, I will tell you how we’ve improved our personal feeds service performance and compare Rails and Phoenix solutions,<strong> spoiler Phoenix has won the battle</strong>.</p><h4>Step 1. Explore JSON structure</h4><p>Before we start concentrating on more complex things, we should audit and remove all rudiment data from JSON structure. It will allow us to reduce object’s attributes and its’ quantity, as well as, send less data through the network. Having accomplished that, we got a structure which contained heavy objects, we serialized it into JSON and paginated 10 items per page.</p><p>After we’ve audited the structure, we’ve received the following result:</p><ul><li>Feeds include objects: photos, last_like, last_comment, user</li><li>Photos include object: photo and many version of images</li><li>LastLikes include objects: user, avatar</li><li>LastComments include objects: user, avatar</li></ul><p><em>Response JSON Feeds structure:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81eacabc7e523210ff95ff9dc2a31b87/href">https://medium.com/media/81eacabc7e523210ff95ff9dc2a31b87/href</a></iframe><p>Having done this, we gained our minimum JSON response structure, next we were able to switch over to other performance problem.</p><h4>Step 2. Optimize JSON serializer and Ruby code</h4><p>We were finding slow ruby code and running benchmark tests in order to compare different methods and gems, for example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/329a2ced8c33ed6783b5c34a270e3cb2/href">https://medium.com/media/329a2ced8c33ed6783b5c34a270e3cb2/href</a></iframe><p>We used RailsPanel (Rails development chrome extension) for ActiveRecord vs Rendering execution time determination:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GMau8cYmy_vVnujcjI_VDw.png" /><figcaption>RailsPanel Breakdoown</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B_GWoapLXJ1qyQOWPYoZuA.png" /><figcaption>RailsPanel ActiveRecord</figcaption></figure><p>Then we compared alternative JSON implementation gems. And finally we opted for Oj:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pcNFzv73YEO6xy9BETKHfQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8vYLOq6G7ycmJlUhSL8FdQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*48snF1Pv220bDD1POON2Nw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yxUKwdBTVUHJR4tIedQe9Q.png" /></figure><h4>Step 3. Analyze sql query</h4><p>We were seeking for slow queries which response time was more than 150 ms and collected them in a file, for the purpose of further analysis. Alternatively, you can use NewRelic service for these kind of tasks. We used Postgres <em>log_duration</em> setting, so we could log all our slow queries.</p><p>To turn on <em>log_duration</em> in file postgresql.conf set:</p><pre>log_duration = on                  <em># Turn on logging </em><br>log_min_duration_statement = 150   <em># Set minimum time ( </em>milliseconds<em>) for query</em></pre><p>Restart <em>posgresql</em> service.</p><p>By using <em>explain analyze</em> tools, we’ve added necessary indexes. I’d like to stress that you should run <em>explain analyz</em>e only on real data in order to get accurate query plan results.</p><p>Minimal <strong>query plan</strong> information for making a decision whether we need to add an index or edit the query itself:</p><ul><li>Seq Scan — bad, since it scans entire table</li><li>Index Scan — good, because it uses index.</li><li>Bitmap Index Scan — good, as it uses index, besides, it’s very effective for a large number of rows.</li><li>Index Only Scan — the best, the fastest one, it reads only from index.</li></ul><p>For more details on how to understand <em>query plan</em>, I’d recommend you to read <a href="https://robots.thoughtbot.com/reading-an-explain-analyze-query-plan">this article</a> by great guys from <a href="https://medium.com/u/2c9426b88373">thoughtbot</a></p><h4>Step 4. Choose the right production configuration</h4><p>It’s highly important to setup the right production configuration for your project, since if you do it wrong, It will spoil all these three steps above. Configuration always depends on your purpose and server configuration.</p><p><strong>Database</strong></p><p>To configure Postgres database, you can use online service <a href="http://pgtune.leopard.in.ua/">PGTune</a>. This site allows you to set parameters of your system and get PostgreSQL settings.</p><p><strong>Application service</strong></p><p>We use Puma as Rails application server, and as we mentioned earlier, the settings in a config file, depend on your system parameters. There is a great article by <a href="https://medium.com/u/cb0ff141a131">Nate Berkopec</a> about <a href="https://www.speedshop.co/2017/05/25/railsconf-2017-the-performance-update.html">Application Server Performance</a> and Puma.</p><p>After we’ve ended up with this stuff we realized that we stuck in serializer performance.</p><h3>Rails benchmark</h3><p><strong>Testing configuration</strong></p><ul><li><em>Database:</em> PostgreSQL 9.5.4 RDS db.m4.xlarge</li><li><em>Instance: </em>one db.m4.xlarge ubuntu</li><li><em>Server:</em> Nginx</li><li><em>Application server:</em> puma (puma_workers=8, puma_min_threads=8, puma_max_threads = 16)</li><li><em>Application:</em> Ruby 2.4.1, Rails 5.0.3, ActiveModelSerializer 0.10.6, oj gem</li></ul><p>For load-testing we use <strong>JMeter</strong> with the following configuration:</p><ul><li>15 threads,</li><li>ramp-up period 1 seconds</li><li>loop count 6000</li><li>request 6 most biggest users feeds and scroll from 1 to 10 pages</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZUM_ZoOpdPAtSxXyzyxMDg.png" /><figcaption>JMeter Rails load-testing</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E0olG68-85B4VZPyxEA_kA.png" /><figcaption>NewRelic Rails load-testing</figcaption></figure><p>Based on the results of Rails load-testing we get:</p><ul><li>AVG 602 RPM because of slow response and network traffic.</li><li>AVG response time application 1.210 ms and JMeter 1.499 ms (response + network traffic)</li></ul><h4>We spend 46.3% time on data serialization.</h4><h3>Phoenix benchmark</h3><p><strong>Testing configuration</strong></p><ul><li><em>Database:</em> PostgreSQL 9.5.4 RDS db.m4.xlarge</li><li><em>Instance: </em>one db.m4.xlarge ubuntu</li><li><em>Application server:</em> Cowboy</li><li><em>Application:</em> Erlang/OTP 20, elixir 1.5.1, phoenix 1.3.0</li></ul><p>For load-testing we use <strong>JMeter</strong> with the following configuration:</p><ul><li>15 threads,</li><li>ramp-up period 1 seconds</li><li>loop count 6000</li><li>request 6 most biggest users feeds and scroll from 1 to 10 pages</li></ul><p>We’ve rewritten feeds service to phoenix and obtained the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-qW3p4vj2aEUuJEAio89Bw.png" /><figcaption>JMeter Phoenix load-testing</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M0xK2aw_0ECsx4-mMS3vNg.png" /><figcaption>DataDog Phoenix load-testing</figcaption></figure><p>Based on the results of Phoenix load-testing we get:</p><ul><li>AVG<strong> 2.55K</strong> RPM in the same network</li><li>AVG response time application <strong>273</strong> ms and JMeter <strong>356</strong> ms (response+ network traffic)</li></ul><p><strong>Conclusion</strong>: Phoenix can serve 4 times more RPM and respond 5 times faster than Rails solution.</p><h3>Trying to repeat the same performance on Rails</h3><p>For this purpose, we launched <strong>8</strong> db.m4.xlarge instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*98kitW7VSoLpbW7lRlFWYQ.png" /><figcaption>AWS 8 Rails applications instances</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*foK9M4tq7_XlAOgW5iUxpA.png" /><figcaption>JMeter Rails load-testing</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*714I_CjldosbPm2RoF9VhQ.png" /><figcaption>NewRelic Rails load-testing</figcaption></figure><p>Based on the results of Rails load-testing we get:</p><ul><li>AVG<strong> 1.330</strong> RPM</li><li>AVG response<strong> </strong>application<strong> 373</strong> ms and JMeter <strong>656</strong> ms (responce + network traffic).</li></ul><p><strong>Conclusion: </strong>we’re nearly there…</p><h4>We spend 69.2% time on data serialization.</h4><h3><strong>Conclusion</strong></h3><p>Prior to making a decision to rewrite feeds service on Phoenix(elixir), we did a lot of job on finding out the reason of bad serialization performance. Only by conducting this research, we were able to make the right step in dealing with this problem.</p><p>To sum up, I want to say that it’s really important to understand how your application works and what tools you may use to check your system’s bottlenecks. I don’t suggest rewriting every single service into elixir, but it solves its’ tasks quite well and drastically reduces server expenses.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5433598ab333" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Phoenix/Elixir — Export data to XLSX]]></title>
            <link>https://medium.com/@SergeyChechaev/elixir-phoenix-everyday-tips-create-xlsx-66cd70268eb4?source=rss-8561476f7ca5------2</link>
            <guid isPermaLink="false">https://medium.com/p/66cd70268eb4</guid>
            <category><![CDATA[web]]></category>
            <category><![CDATA[export]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[phoenix]]></category>
            <dc:creator><![CDATA[Sergey Chechaev]]></dc:creator>
            <pubDate>Wed, 08 Mar 2017 20:46:41 GMT</pubDate>
            <atom:updated>2017-03-16T07:31:20.311Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kTvoGHEqxqKx5ucm-nOp_A.png" /></figure><p>In this tutorial, we create phoenix application with Post model whitсh is going to be exported like a <strong>xlsx</strong>. First of all <a href="http://www.phoenixframework.org/docs/installation">install Phoenix project</a> (i use elixir v1.4.0, phoenix v1.2.1, psql (PostgreSQL) 9.6.1) and create phoenix project:</p><pre>mix phoenix.new posts_xlsx</pre><p>Before moving on, configure your database in config/dev.exs and run:</p><pre>$ mix ecto.create<br>The database for PostsXlsx.Repo has been created<br>$ mix phoenix.server</pre><p>After running phoenix server we can open URL <a href="http://localhost:4000/">http://localhost:4000</a> and see starting page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tpC02CYCQXoUO97qr8COOQ.png" /></figure><p>As we had our phoenix project we need to create Post table where we can store our posts content and show it in our application. Elixir provides Mix build tools and Phoenix has currently a number of built-in Phoenix-specific and ecto-specific mix tasks. Mix task<strong> mix phoenix.gen.html</strong> the generated resource will contain:</p><ul><li><em>a schema in web/models</em></li><li><em>a view in web/views</em></li><li><em>a controller in web/controllers</em></li><li><em>a migration file for the repository</em></li><li><em>default CRUD templates in web/templates</em></li><li><em>test files for generated model and controller</em></li></ul><p>Generates a Phoenix resource:</p><pre>mix phoenix.gen.html Post posts name:string title:string content:text</pre><p>Add the resource to your browser scope in <strong>web/router.ex</strong>:</p><pre>scope &quot;/&quot;, PostsXlsx do<br>  pipe_through :browser</pre><pre>  get &quot;/&quot;, PageController, :index<br>  resources &quot;/posts&quot;, PostController<br>end</pre><p>Remember to update your repository by running migrations:</p><pre>$ mix ecto.migrate</pre><p>Open page <a href="http://localhost:4000/posts">http://localhost:4000/posts</a> and add some posts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sbwSooOvgBBkh-ct2Sb0wQ.png" /></figure><p>Create scope folders:</p><pre>$ mkdir web/controllers/exports/<br>$ mkdir web/view/exports/</pre><p>Create controller and view that responsible for export generation:</p><pre>touch web/controllers/exports/post_controller.ex<br>touch web/view/exports/post_view.ex</pre><p>For creating <strong>xlsx</strong> export we going to use <a href="https://github.com/xou/elixlsx"><strong>elixlsx</strong></a><strong> </strong>lib, add it to <strong>mix.exs</strong> file:</p><pre>defp deps do<br> [{:phoenix, “~&gt; 1.2.1”},<br> {:phoenix_pubsub, “~&gt; 1.0”},<br> {:phoenix_ecto, “~&gt; 3.0”},<br> {:postgrex, “&gt;= 0.0.0”},<br> {:phoenix_html, “~&gt; 2.6”},<br> {:phoenix_live_reload, “~&gt; 1.0”, only: :dev},<br> {:gettext, “~&gt; 0.11”},<br> {:cowboy, “~&gt; 1.0”},<br> <strong>{:elixlsx, “~&gt; 0.1.1”}]</strong><br>end</pre><p>Add code to <strong>web/controller/exports/post_controller.ex</strong></p><pre>defmodule PostsXlsx.Exports.PostController do<br>  use PostsXlsx.Web, :controller</pre><pre>  alias PostsXlsx.Post</pre><pre>  def index(conn, _params) do<br>    posts =<br>      Post<br>      |&gt; limit(10_000)<br>      |&gt; Repo.all</pre><pre>    conn<br>    |&gt; put_resp_content_type(“text/xlsx”)<br>    |&gt; put_resp_header(“content-disposition”, “attachment; filename=posts_report”)<br>    |&gt; render(“report.xlsx”, %{posts: posts})<br>  end<br>end</pre><p>And for <strong>web/views/reports/post_view.ex</strong>:</p><pre>defmodule PostsXlsx.Exports.PostView do<br>  use PostsXlsx.Web, :view</pre><pre>alias Elixlsx.{Workbook, Sheet}</pre><pre>@header [<br>    “ID”,<br>    “Name”,<br>    “Title”,<br>    “Content”<br>  ]</pre><pre>def render(“report.xlsx”, %{posts: posts}) do<br>    report_generator(posts) <br>    |&gt; Elixlsx.write_to_memory(“report.xlsx”) <br>    |&gt; elem(1) <br>    |&gt; elem(1)<br>  end</pre><pre>def report_generator(posts) do<br>    rows = posts |&gt; Enum.map(&amp;(row(&amp;1)))<br>    %Workbook{sheets: [%Sheet{name: “Posts”, rows: [<a href="http://twitter.com/header">@header</a>] ++ rows}]}<br>  end</pre><pre>def row(post) do<br>    [<br>      post.id,<br>      post.name,<br>      post.title,<br>      post.content<br>    ]<br>  end<br>end</pre><p>Also, we need to create the route for our report controller, open file <strong>web/router.ex</strong> and add scope:</p><pre>scope “/exports”, as: :exports, alias: PostsXlsx.Exports do<br>  pipe_through :browser</pre><pre>  resources “/posts”, PostController, only: [:index]<br>end</pre><p>You can check your routes by mix task:</p><pre>$ mix phoenix.routes</pre><pre>page_path  GET     /               PostsXlsx.PageController :index<br>post_path  GET     /posts          PostsXlsx.PostController :index<br>post_path  GET     /posts/:id/edit PostsXlsx.PostController :edit<br>post_path  GET     /posts/new      PostsXlsx.PostController :new<br>post_path  GET     /posts/:id      PostsXlsx.PostController :show<br>post_path  POST    /posts          PostsXlsx.PostController :create<br>post_path  PATCH   /posts/:id      PostsXlsx.PostController :update<br>           PUT     /posts/:id      PostsXlsx.PostController :update<br>post_path  DELETE  /posts/:id      PostsXlsx.PostController :delete<br>exports_post_path GET /exports/posts PostsXlsx.Exports.PostController :index</pre><p>Phoenix generates path helper for us <strong>exports_post_path</strong>. We need to create a button for export our post <strong>xlsx</strong> report. Open file <strong>web/template/post/index.html.eex </strong>and add code:</p><pre>&lt;h2&gt;Listing posts&lt;/h2&gt;<br><strong>&lt;ul class=&quot;nav pull-right&quot;&gt;<br>  &lt;li&gt;<br>    &lt;%= link &quot;Export XLSX&quot;, to: exports_post_path(</strong><a href="http://twitter.com/conn"><strong>@conn</strong></a><strong>, :index), class: &quot;btn btn-default&quot; %&gt;<br>  &lt;/li&gt;<br>&lt;/ul&gt;</strong><br>&lt;table class=&quot;table&quot;&gt;<br>  &lt;thead&gt;<br>    &lt;tr&gt;<br>      &lt;th&gt;Name&lt;/th&gt;<br>      &lt;th&gt;Title&lt;/th&gt;<br>      &lt;th&gt;Content&lt;/th&gt;</pre><pre>&lt;th&gt;&lt;/th&gt;<br>    &lt;/tr&gt;<br>  &lt;/thead&gt;<br>  &lt;tbody&gt;<br>&lt;%= for post &lt;- <a href="http://twitter.com/posts">@posts</a> do %&gt;<br>    &lt;tr&gt;<br>      &lt;td&gt;&lt;%= post.name %&gt;&lt;/td&gt;<br>      &lt;td&gt;&lt;%= post.title %&gt;&lt;/td&gt;<br>      &lt;td&gt;&lt;%= post.content %&gt;&lt;/td&gt;</pre><pre>&lt;td class=&quot;text-right&quot;&gt;<br>        &lt;%= link &quot;Show&quot;, to: post_path(<a href="http://twitter.com/conn">@conn</a>, :show, post), class: &quot;btn btn-default btn-xs&quot; %&gt;<br>        &lt;%= link &quot;Edit&quot;, to: post_path(<a href="http://twitter.com/conn">@conn</a>, :edit, post), class: &quot;btn btn-default btn-xs&quot; %&gt;<br>        &lt;%= link &quot;Delete&quot;, to: post_path(<a href="http://twitter.com/conn">@conn</a>, :delete, post), method: :delete, data: [confirm: &quot;Are you sure?&quot;], class: &quot;btn btn-danger btn-xs&quot; %&gt;<br>      &lt;/td&gt;<br>    &lt;/tr&gt;<br>&lt;% end %&gt;<br>  &lt;/tbody&gt;<br>&lt;/table&gt;</pre><pre>&lt;%= link &quot;New post&quot;, to: post_path(<a href="http://twitter.com/conn">@conn</a>, :new) %&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qSnUc6TUYLlglJH3l3Lbyw.png" /></figure><p>If you press the button, phoenix application generate for you <strong>xlsx</strong> report with Posts data.</p><p>P.S. Example Post XLSX Phoenix application code available <a href="https://github.com/sergey-chechaev/posts_xlsx">by link</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66cd70268eb4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>