1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Plugs.IdempotencyPlug do
6 import Phoenix.Controller, only: [json: 2]
12 def init(opts), do: opts
14 # Sending idempotency keys in `GET` and `DELETE` requests has no effect
15 # and should be avoided, as these requests are idempotent by definition.
18 def call(%{method: method} = conn, _) when method in ["POST", "PUT", "PATCH"] do
19 case get_req_header(conn, "idempotency-key") do
20 [key] -> process_request(conn, key)
25 def call(conn, _), do: conn
27 def process_request(conn, key) do
28 case Cachex.get(:idempotency_cache, key) do
30 cache_resposnse(conn, key)
33 send_cached(conn, key, record)
35 {atom, message} when atom in [:ignore, :error] ->
36 render_error(conn, message)
40 defp cache_resposnse(conn, key) do
41 register_before_send(conn, fn conn ->
42 [request_id] = get_resp_header(conn, "x-request-id")
43 content_type = get_content_type(conn)
45 record = {request_id, content_type, conn.status, conn.resp_body}
46 {:ok, _} = Cachex.put(:idempotency_cache, key, record)
49 |> put_resp_header("idempotency-key", key)
50 |> put_resp_header("x-original-request-id", request_id)
54 defp send_cached(conn, key, record) do
55 {request_id, content_type, status, body} = record
58 |> put_resp_header("idempotency-key", key)
59 |> put_resp_header("idempotent-replayed", "true")
60 |> put_resp_header("x-original-request-id", request_id)
61 |> put_resp_content_type(content_type)
62 |> send_resp(status, body)
66 defp render_error(conn, message) do
68 |> put_status(:unprocessable_entity)
69 |> json(%{error: message})
73 defp get_content_type(conn) do
74 [content_type] = get_resp_header(conn, "content-type")
76 if String.contains?(content_type, ";") do