Files
fizzy/app/models/storage/entry.rb
T
Jeremy Daer bd6c1cf34f Storage: harden reconcile for concurrent writes and fix board transfer (#2096)
* Storage: harden reconcile for concurrent writes and fix board transfer

Reconcile now uses two-cursor approach: captures cursor before and after
the storage scan, aborting if they differ (entries added during scan).
Job retries 3x with 1-minute waits and limits concurrency to 1 per owner.

Board transfer now correctly moves storage for card description embeds
and comment embeds, not just direct attachments. Uses batched queries
to handle cards with thousands of comments efficiently.

Also fixes N+1 queries in attachment grouping via lookup maps.

* Storage: fix per-attachment reconcile and enforce no blob reuse

The storage ledger tracks per-attachment (not per-blob) as a business
abstraction for quotas. This fixes reconcile to match that model and
adds enforcement to prevent blob reuse in tracked contexts.

* Reconcile now uses joins(:blob).sum() for per-attachment counting
* New validation prevents reusing blobs across tracked attachments
* Race-safe storage_total creation with create_or_find_by
* Job efficiency: skip find_by when object already available
* Backfill script checks per-attachment, not just per-blob
2025-12-19 13:07:32 -08:00

32 lines
1.0 KiB
Ruby

class Storage::Entry < ApplicationRecord
belongs_to :account
belongs_to :board, optional: true
belongs_to :recordable, polymorphic: true, optional: true
scope :pending, ->(last_entry_id) { where.not(id: ..last_entry_id) if last_entry_id }
# Records may be destroyed (during cascading deletes) but .id still works.
# Skip entirely if account is destroyed - no need to track storage for deleted accounts.
# Skip materialize jobs for destroyed boards since there's nothing to update.
def self.record(delta:, operation:, account:, board: nil, recordable: nil, blob: nil)
return if delta.zero?
return if account.destroyed?
entry = create! \
account_id: account.id,
board_id: board&.id,
recordable_type: recordable&.class&.name,
recordable_id: recordable&.id,
blob_id: blob&.id,
delta: delta,
operation: operation,
user_id: Current.user&.id,
request_id: Current.request_id
account.materialize_storage_later
board&.materialize_storage_later unless board&.destroyed?
entry
end
end