Attached.StorageBackends (Attached v0.2.0)

Copy Markdown View Source

Registry and facade for storage backends.

Backends are named instances: each registry entry pairs a backend module with that instance's config. All blob storage access goes through this module — call sites use upload/3, download/1, etc.; the facade resolves the default instance and dispatches to its module with its config.

Configuration

config :attached,
  default_storage_backend: :s3_main,
  storage_backends: [
    local: {Attached.StorageBackends.Disk, root: "priv/attachments"},
    s3_main: {Attached.StorageBackends.S3,
      bucket: "my-bucket",
      region: "eu-central-1",
      access_key_id: System.fetch_env!("AWS_ACCESS_KEY_ID"),
      secret_access_key: System.fetch_env!("AWS_SECRET_ACCESS_KEY")}
  ]

:default_storage_backend may be omitted when exactly one backend is configured — it then becomes the default. With no storage configuration at all, a local Disk instance rooted at priv/attachments is used, so development works without setup.

Because the same module can appear under several names (e.g. two S3 buckets), backends are addressed by name everywhere — including the storage_backend column on attached_originals, which records the instance name an original was written to.

Implement Attached.StorageBackends.Behaviour to add a custom backend and register it under a name like any built-in.

Summary

Functions

Returns the name of the default backend instance.

Returns {:ok, %{url: url, headers: headers}} for a direct browser upload (HTTP PUT) of key, or {:error, :not_supported} when the default backend doesn't implement the optional direct_upload_url/3 callback.

Returns the backend registry: a keyword of name => {module, config} entries from config :attached, :storage_backends.

Resolves a backend instance name to its {module, config} pair.

Functions

compose(source_keys, destination_key)

default_name()

Returns the name of the default backend instance.

config :attached, :default_storage_backend when set; otherwise the only registry entry. Multiple entries without an explicit default raise — registry order must never decide where files go.

delete(key)

delete_prefixed(prefix)

direct_upload_url(key, opts \\ [])

Returns {:ok, %{url: url, headers: headers}} for a direct browser upload (HTTP PUT) of key, or {:error, :not_supported} when the default backend doesn't implement the optional direct_upload_url/3 callback.

See Attached.StorageBackends.Behaviour for the supported options.

download(key)

download_chunk(key, range)

exists?(key)

registry()

Returns the backend registry: a keyword of name => {module, config} entries from config :attached, :storage_backends.

resolve!(name)

Resolves a backend instance name to its {module, config} pair.

Raises ArgumentError for unknown names or malformed entries.

upload(key, source_path, opts \\ [])

url(key, opts \\ [])