Module: Glib::SnapshotV2

Extended by:
ActiveSupport::Concern
Defined in:
app/models/concerns/glib/snapshot_v2.rb

Constant Summary collapse

KNOWN_ACTIONS =

The CRUD backbone covers most flows; the approval-gate admin actions are distinct audit events (request_changes / approve / undo_approve) that the timeline UI labels off the action string, so they earn their own slots here rather than being collapsed into :update (which would lose the "what happened" signal in the audit trail).

[:create, :update, :destroy, :request_changes, :approve, :undo_approve].freeze

Instance Method Summary collapse

Instance Method Details

#associations_for_snapshotObject



223
224
225
# File 'app/models/concerns/glib/snapshot_v2.rb', line 223

def associations_for_snapshot
  children_to_snapshot.keys.filter { |key| respond_to?(key) }
end

#check_snapshot_changedObject



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'app/models/concerns/glib/snapshot_v2.rb', line 69

def check_snapshot_changed
  return true if changed?

  associations_for_snapshot.each do |association_name|
    association = self.class.reflect_on_association(association_name)
    association_value = public_send(association_name)

    # ActiveStorage associations (has_one_attached / has_many_attached) are not
    # reflected as standard AR macros; handle them before the case block.
    if active_storage_association?(association, association_value)
      active_storage_records(association_value).each do |record|
        return true if record.changed?
      end
      next
    end

    raise "Invalid association: #{association_name}" if association.nil?

    case association.macro
    when :has_many
      records = association_value
      records.each do |record|
        return true if record.changed?
      end
      if new_record? && records.count > 0
        return true
      end
    when :has_one, :belongs_to
      return true if association_value&.changed?
    else
      raise "Unexpected association macro: #{association.macro}"
    end
  end

  false
end

#content_retention_daysObject

Return number of days to retain snapshot content, or nil for unlimited.



232
233
234
# File 'app/models/concerns/glib/snapshot_v2.rb', line 232

def content_retention_days
  nil
end

#diff(snapshot = snapshot_prev) ⇒ Object



169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'app/models/concerns/glib/snapshot_v2.rb', line 169

def diff(snapshot = snapshot_prev)
  default_ignored_keys = ['updated_at', 'created_at']
  ignore_keys = build_ignore_keys(default_ignored_keys)

  item, associations = fetch_snapshot_items(snapshot)

  {
    'item' => ::Hashdiff.diff(
      normalize_attributes_for_diff(item.attributes.except(*ignore_keys)),
      normalize_attributes_for_diff(attributes.except(*ignore_keys))
    ),
    'associations' => diff_associations(associations, default_ignored_keys)
  }
end

#glib_create_snapshot!(action, source, user: nil) ⇒ Object

information need to be store:

  • action: create, update, destroy
  • track changes


109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'app/models/concerns/glib/snapshot_v2.rb', line 109

def glib_create_snapshot!(action, source, user: nil)
  action_sym = action.to_sym
  raise "unknown action: #{action}" unless KNOWN_ACTIONS.include?(action_sym)
  raise 'source must be present' if source.blank?
  raise 'user must be present when source is "user"' if source == 'user' && user.nil?

  # Lock is required to prevent race conditions when calculating version number.
  if (result =
        with_lock do
          version = last_version + 1
          calculated_diff = diff

          snapshot_obj = {
            identifier: snapshot_identifier(version),
            user: user,
            metadata: {} # Keep for potential future use, but main data in columns
          }

          # Don't create version if same as before. Reuses `calculated_diff` instead of
          # recomputing it inside `same_as_before?`.
          unless same_as_before?(calculated_diff)
            # No nil guard: active_snapshot's `create_snapshot!` raises on failure and
            # always returns the snapshot.
            snapshot = create_snapshot!(**snapshot_obj)
            # update_columns is the second half of the insert, not a domain update: the
            # gem's create_snapshot! signature can't set these V2-promoted columns, and
            # no validation/callback (gem or initializer) concerns them. Runs inside
            # with_lock's transaction, so no half-written row ever commits.
            snapshot.update_columns( # rubocop:disable DevDoc/Rails/AvoidBypassingValidation
              action: action.to_s,
              version: version,
              diff: calculated_diff,
              source: source
            )
            record_blob_references(snapshot, calculated_diff)
            snapshot
          end
        end)
    # Cleanup operations - run outside lock and transaction
    remove_old_snapshot
  end

  result
end

#glib_revert_snapshot!(version) ⇒ Object



154
155
156
157
# File 'app/models/concerns/glib/snapshot_v2.rb', line 154

def glib_revert_snapshot!(version)
  snapshot = snapshots.find_by!(identifier: snapshot_identifier(version))
  snapshot.restore!
end

#interval_from_prev_versionObject



163
164
165
166
167
# File 'app/models/concerns/glib/snapshot_v2.rb', line 163

def interval_from_prev_version
  return nil if snapshot_prev.nil?

  updated_at - snapshot_prev.created_at
end

#last_versionObject



203
204
205
206
207
208
# File 'app/models/concerns/glib/snapshot_v2.rb', line 203

def last_version
  max_version = snapshots.maximum(:version)
  return 0 if max_version.blank?

  max_version
end

#max_snapshotsObject



227
228
229
# File 'app/models/concerns/glib/snapshot_v2.rb', line 227

def max_snapshots
  nil
end

#remove_old_snapshotObject



210
211
212
213
214
215
216
217
# File 'app/models/concerns/glib/snapshot_v2.rb', line 210

def remove_old_snapshot
  return if max_snapshots.nil?

  newest_ids = snapshots.order(version: :desc, id: :desc).limit(max_snapshots).ids
  return unless newest_ids.size >= max_snapshots

  snapshots.where.not(id: newest_ids).destroy_all
end

#same_as_before?(computed_diff = diff) ⇒ Boolean

Decides whether glib_create_snapshot! should skip the version write. Derived from the computed diff (persisted state), never from the instance-local snapshot_changed flag: the flag dies with its instance, and an owner's snapshot replaces association targets with fresh instances (with_lock's reload clears the association cache, then the diff walk re-reads the targets), so flag-gating used to silently drop a target's follow-up snapshot taken through the association (issue #481). For a first snapshot (no previous version) the diff runs current state against attributes_before_save || {}.



195
196
197
198
199
200
201
# File 'app/models/concerns/glib/snapshot_v2.rb', line 195

def same_as_before?(computed_diff = diff)
  item_unchanged = computed_diff['item'].blank?
  assoc_diff = computed_diff['associations']
  associations_unchanged = assoc_diff.nil? || assoc_diff.values.all?(&:blank?)

  item_unchanged && associations_unchanged
end

#snapshot_identifier(version) ⇒ Object



159
160
161
# File 'app/models/concerns/glib/snapshot_v2.rb', line 159

def snapshot_identifier(version)
  "#{self.class.to_s.underscore}_#{id}_version_#{version}"
end

#snapshot_prevObject



184
185
186
# File 'app/models/concerns/glib/snapshot_v2.rb', line 184

def snapshot_prev
  snapshots.order(version: :desc).first
end

#watched_keys_for_snapshotObject

Raises:

  • (NotImplementedError)


219
220
221
# File 'app/models/concerns/glib/snapshot_v2.rb', line 219

def watched_keys_for_snapshot
  raise NotImplementedError, "please add method 'watched_keys_for_snapshot' to #{self.class}"
end