Skip to content

fix(assets): extract metadata after the upload on Rails 8.1.4+ - #266

Open
TheRealAnubis wants to merge 1 commit into
maglevhq:mainfrom
TheRealAnubis:fix/asset-metadata-callback-order
Open

TheRealAnubis wants to merge 1 commit into
maglevhq:mainfrom
TheRealAnubis:fix/asset-metadata-callback-order

Conversation

@TheRealAnubis

Copy link
Copy Markdown

Creating an asset raises ActiveStorage::FileNotFoundError on Rails 8.1.4+ (with the default load_defaults ≥ 7.1).

Root cause: Maglev::ActiveStorage registers save_metadata_now with prepend: true so that it runs after the upload callback that has_one_attached adds (attachment_changes.delete(...).upload). That relied on the legacy, reverse order of after_commit callbacks.

Rails 8.1.4 fixed prepend: true for after_commit/after_rollback when run_after_transaction_callbacks_in_order_defined is enabled (see the "Fix incorrect callback execution order…" entry in the activerecord 8.1.4 CHANGELOG): a prepended callback now really runs first. So the metadata hook analyzes a blob that hasn't been uploaded yet.

Fix: only prepend the callback when the legacy order is in use:

after_commit :save_metadata_now, on: :create,
                                 prepend: !::ActiveRecord.run_after_transaction_callbacks_in_order_defined

Tests:

  • The existing spec/models/maglev/asset_spec.rb ("sets the width and height of the image") reproduces the bug as soon as Rails is bumped to 8.1.4.1 (bundle update rails --conservative): red before the fix, green after.
  • Checked locally (SQLite) on Rails 7.2.3, 8.1.3.1 and 8.1.4.1, with run_after_transaction_callbacks_in_order_defined both enabled and disabled.
  • The lockfile still pins Rails 8.1.3.1, so CI won't exercise the regression. Happy to add the Gemfile.lock bump to this PR if you'd like.

Found while running Maglev 3.1.0 on Rails 8.1.4 in production, where we've been carrying a monkey-patch for it.

Maglev::ActiveStorage registered `save_metadata_now` with `prepend: true`
so that, with the legacy (reverse) after_commit order, it ran after the
upload callback added by `has_one_attached`.

Rails 8.1.4 fixed `prepend: true` for after_commit callbacks when
`run_after_transaction_callbacks_in_order_defined` is enabled (the default
since load_defaults 7.1): a prepended callback now really runs first. So
the metadata hook ran before the file was uploaded, and creating an asset
raised ActiveStorage::FileNotFoundError.

Only prepend the callback when the legacy order is in use, so it runs
after the upload whatever the Rails version and configuration.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant