2.6 KiB · text History 44bc4f7
defmodule CartosnapApp.Storage.S3 do
  @moduledoc """
  The production storage backend: a Backblaze B2 bucket over its
  S3-compatible API, signed with Req's built-in AWS SigV4.

  Not ExAws: ExAws looks up a default AWS host for the region before it
  applies a configured host, and raises for B2's regions (`us-west-004` is
  no AWS region). B2 checks the region in the signature, so it can't just
  be swapped for an AWS one.

      config :cartosnap_app, CartosnapApp.Storage.S3,
        endpoint: "https://s3.us-west-004.backblazeb2.com",
        region: "us-west-004",
        access_key_id: "...",
        secret_access_key: "...",
        # optional; defaults to https://<bucket>.<endpoint host>
        public_url: "https://cdn.example.com"

  Requests are path-style (`<endpoint>/<bucket>/<key>`), which B2 and other
  S3-compatibles (MinIO, for one) all take.
  """

  @behaviour CartosnapApp.Storage

  alias CartosnapApp.Storage

  @impl true
  def put(key, body, content_type) do
    with {:ok, _resp} <- request(:put, key, body: body, headers: [content_type: content_type]),
         do: :ok
  end

  @impl true
  def get(key) do
    with {:ok, %{body: body}} <- request(:get, key, decode_body: false), do: {:ok, body}
  end

  @impl true
  def delete(key) do
    with {:ok, _resp} <- request(:delete, key, []), do: :ok
  end

  @impl true
  def url(key) do
    base =
      config()[:public_url] ||
        (
          uri = URI.parse(config()[:endpoint])
          "#{uri.scheme}://#{Storage.bucket()}.#{uri.host}"
        )

    "#{String.trim_trailing(base, "/")}/#{encode(key)}"
  end

  defp request(method, key, opts) do
    cfg = config()

    [
      method: method,
      url: "#{String.trim_trailing(cfg[:endpoint], "/")}/#{Storage.bucket()}/#{encode(key)}",
      aws_sigv4: [
        service: :s3,
        region: cfg[:region],
        access_key_id: cfg[:access_key_id],
        secret_access_key: cfg[:secret_access_key]
      ],
      retry: :transient
    ]
    |> Keyword.merge(opts)
    |> Keyword.merge(Keyword.get(cfg, :req_options, []))
    |> Req.request()
    |> case do
      {:ok, %Req.Response{status: status} = resp} when status in 200..299 -> {:ok, resp}
      {:ok, %Req.Response{status: status, body: body}} -> {:error, {:http, status, body}}
      {:error, exception} -> {:error, exception}
    end
  end

  # Keys are `<uuid>/<uuid>/<variant>.<ext>`, but encode each segment anyway.
  defp encode(key) do
    key
    |> String.split("/")
    |> Enum.map_join("/", fn segment -> URI.encode(segment, &URI.char_unreserved?/1) end)
  end

  defp config, do: Application.get_env(:cartosnap_app, __MODULE__, [])
end