logo

pleroma

My custom branche(s) on git.pleroma.social/pleroma/pleroma

cache.ex (3892B)


  1. # Pleroma: A lightweight social networking server
  2. # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
  3. # SPDX-License-Identifier: AGPL-3.0-only
  4. defmodule Pleroma.Plugs.Cache do
  5. @moduledoc """
  6. Caches successful GET responses.
  7. To enable the cache add the plug to a router pipeline or controller:
  8. plug(Pleroma.Plugs.Cache)
  9. ## Configuration
  10. To configure the plug you need to pass settings as the second argument to the `plug/2` macro:
  11. plug(Pleroma.Plugs.Cache, [ttl: nil, query_params: true])
  12. Available options:
  13. - `ttl`: An expiration time (time-to-live). This value should be in milliseconds or `nil` to disable expiration. Defaults to `nil`.
  14. - `query_params`: Take URL query string into account (`true`), ignore it (`false`) or limit to specific params only (list). Defaults to `true`.
  15. - `tracking_fun`: A function that is called on successfull responses, no matter if the request is cached or not. It should accept a conn as the first argument and the value assigned to `tracking_fun_data` as the second.
  16. Additionally, you can overwrite the TTL inside a controller action by assigning `cache_ttl` to the connection struct:
  17. def index(conn, _params) do
  18. ttl = 60_000 # one minute
  19. conn
  20. |> assign(:cache_ttl, ttl)
  21. |> render("index.html")
  22. end
  23. """
  24. import Phoenix.Controller, only: [current_path: 1, json: 2]
  25. import Plug.Conn
  26. @behaviour Plug
  27. @defaults %{ttl: nil, query_params: true}
  28. @impl true
  29. def init([]), do: @defaults
  30. def init(opts) do
  31. opts = Map.new(opts)
  32. Map.merge(@defaults, opts)
  33. end
  34. @impl true
  35. def call(%{method: "GET"} = conn, opts) do
  36. key = cache_key(conn, opts)
  37. case Cachex.get(:web_resp_cache, key) do
  38. {:ok, nil} ->
  39. cache_resp(conn, opts)
  40. {:ok, {content_type, body, tracking_fun_data}} ->
  41. conn = opts.tracking_fun.(conn, tracking_fun_data)
  42. send_cached(conn, {content_type, body})
  43. {:ok, record} ->
  44. send_cached(conn, record)
  45. {atom, message} when atom in [:ignore, :error] ->
  46. render_error(conn, message)
  47. end
  48. end
  49. def call(conn, _), do: conn
  50. # full path including query params
  51. defp cache_key(conn, %{query_params: true}), do: current_path(conn)
  52. # request path without query params
  53. defp cache_key(conn, %{query_params: false}), do: conn.request_path
  54. # request path with specific query params
  55. defp cache_key(conn, %{query_params: query_params}) when is_list(query_params) do
  56. query_string =
  57. conn.params
  58. |> Map.take(query_params)
  59. |> URI.encode_query()
  60. conn.request_path <> "?" <> query_string
  61. end
  62. defp cache_resp(conn, opts) do
  63. register_before_send(conn, fn
  64. %{status: 200, resp_body: body} = conn ->
  65. ttl = Map.get(conn.assigns, :cache_ttl, opts.ttl)
  66. key = cache_key(conn, opts)
  67. content_type = content_type(conn)
  68. conn =
  69. unless opts[:tracking_fun] do
  70. Cachex.put(:web_resp_cache, key, {content_type, body}, ttl: ttl)
  71. conn
  72. else
  73. tracking_fun_data = Map.get(conn.assigns, :tracking_fun_data, nil)
  74. Cachex.put(:web_resp_cache, key, {content_type, body, tracking_fun_data}, ttl: ttl)
  75. opts.tracking_fun.(conn, tracking_fun_data)
  76. end
  77. put_resp_header(conn, "x-cache", "MISS from Pleroma")
  78. conn ->
  79. conn
  80. end)
  81. end
  82. defp content_type(conn) do
  83. conn
  84. |> Plug.Conn.get_resp_header("content-type")
  85. |> hd()
  86. end
  87. defp send_cached(conn, {content_type, body}) do
  88. conn
  89. |> put_resp_content_type(content_type, nil)
  90. |> put_resp_header("x-cache", "HIT from Pleroma")
  91. |> send_resp(:ok, body)
  92. |> halt()
  93. end
  94. defp render_error(conn, message) do
  95. conn
  96. |> put_status(:internal_server_error)
  97. |> json(%{error: message})
  98. |> halt()
  99. end
  100. end