Class: MergeRequestDiff

Inherits:
ApplicationRecord show all
Includes:
BulkInsertableAssociations, EachBatch, Gitlab::Utils::StrongMemoize, Importable, ManualInverseAssociation, ShaAttribute, Sortable
Defined in:
app/models/merge_request_diff.rb

Constant Summary collapse

COMMITS_SAFE_SIZE =

Don’t display more than 100 commits at once

100
BATCH_SIZE =
1000
EXTERNAL_DIFF_CUTOFF =

Applies to closed or merged MRs when determining whether to migrate their diffs to external storage

7.days.freeze
FILES_COUNT_SENTINEL =

The files_count column is a 2-byte signed integer. Look up the true value from the database if this sentinel is seen

(2**15) - 1
EXTERNAL_DIFFS_CACHE_TMPDIR =

External diff cache key used by diffs export

'project-%{project_id}-external-mr-%{mr_id}-diff-%{id}-cache'
EXTERNAL_DIFF_CACHE_CHUNK_SIZE =
8.megabytes

Constants inherited from ApplicationRecord

ApplicationRecord::MAX_PLUCK

Constants included from HasCheckConstraints

HasCheckConstraints::NOT_NULL_CHECK_PATTERN

Constants included from ResetOnColumnErrors

ResetOnColumnErrors::MAX_RESET_PERIOD

Instance Attribute Summary

Attributes included from Importable

#importing, #user_contributions

Class Method Summary collapse

Instance Method Summary collapse

Methods included from BulkInsertableAssociations

#bulk_insert_associations!, bulk_inserts_enabled?, with_bulk_insert

Methods inherited from ApplicationRecord

===, cached_column_list, #create_or_load_association, declarative_enum, default_select_columns, id_in, id_not_in, iid_in, nullable_column?, pluck_primary_key, primary_key_in, #readable_by?, safe_ensure_unique, safe_find_or_create_by, safe_find_or_create_by!, #to_ability_name, underscore, where_exists, where_not_exists, with_fast_read_statement_timeout, without_order

Methods included from ResetOnColumnErrors

#reset_on_union_error, #reset_on_unknown_attribute_error

Methods included from Gitlab::SensitiveSerializableHash

#serializable_hash

Class Method Details

.find_by_diff_refs(diff_refs) ⇒ Object



214
215
216
# File 'app/models/merge_request_diff.rb', line 214

def self.find_by_diff_refs(diff_refs)
  find_by(start_commit_sha: diff_refs.start_sha, head_commit_sha: diff_refs.head_sha, base_commit_sha: diff_refs.base_sha)
end

.ids_for_external_storage_migration(limit:) ⇒ Object



159
160
161
162
163
164
165
166
167
168
169
170
# File 'app/models/merge_request_diff.rb', line 159

def ids_for_external_storage_migration(limit:)
  return [] unless Gitlab.config.external_diffs.enabled

  case Gitlab.config.external_diffs.when
  when 'always'
    ids_for_external_storage_migration_strategy_always(limit: limit)
  when 'outdated'
    ids_for_external_storage_migration_strategy_outdated(limit: limit)
  else
    []
  end
end

.ids_for_external_storage_migration_strategy_always(limit:) ⇒ Object



172
173
174
# File 'app/models/merge_request_diff.rb', line 172

def ids_for_external_storage_migration_strategy_always(limit:)
  files_in_database.limit(limit).pluck(:id)
end

.ids_for_external_storage_migration_strategy_outdated(limit:) ⇒ Object



176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'app/models/merge_request_diff.rb', line 176

def ids_for_external_storage_migration_strategy_outdated(limit:)
  # Outdated is too complex to be a single SQL query, so split into three
  before = EXTERNAL_DIFF_CUTOFF.ago

  ids = files_in_database
    .old_merged_diffs(before)
    .limit(limit)
    .pluck(:id)

  return ids if ids.size >= limit

  ids += files_in_database
    .old_closed_diffs(before)
    .limit(limit - ids.size)
    .pluck(:id)

  return ids if ids.size >= limit

  ids + files_in_database
    .not_latest_diffs
    .limit(limit - ids.size)
    .pluck(:id)
end

Instance Method Details

#base_commitObject



355
356
357
358
359
# File 'app/models/merge_request_diff.rb', line 355

def base_commit
  return unless base_commit_sha

  project.commit_by(oid: base_commit_sha)
end

#cached_external_diffObject

Yields locally cached external diff if it’s externally stored. Used during Project Export to speed up externally stored merge request diffs export



630
631
632
633
634
635
636
637
638
# File 'app/models/merge_request_diff.rb', line 630

def cached_external_diff
  return yield(nil) unless stored_externally?

  cache_external_diff unless File.exist?(external_diff_cache_filepath)

  File.open(external_diff_cache_filepath) do |file|
    yield(file)
  end
end

#commit_shas(limit: nil) ⇒ Object



373
374
375
376
377
378
379
380
381
# File 'app/models/merge_request_diff.rb', line 373

def commit_shas(limit: nil)
  if association(:merge_request_diff_commits).loaded?
    sorted_diff_commits = merge_request_diff_commits.sort_by { |diff_commit| [diff_commit.id, diff_commit.relative_order] }
    sorted_diff_commits = sorted_diff_commits.take(limit) if limit
    sorted_diff_commits.map(&:sha)
  else
    merge_request_diff_commits.limit(limit).pluck(:sha)
  end
end

#commits(limit: nil, load_from_gitaly: false, page: nil) ⇒ Object



337
338
339
340
341
# File 'app/models/merge_request_diff.rb', line 337

def commits(limit: nil, load_from_gitaly: false, page: nil)
  strong_memoize(:"commits_#{limit || 'all'}_#{load_from_gitaly}_page_#{page}") do
    load_commits(limit: limit, load_from_gitaly: load_from_gitaly, page: page)
  end
end

#compareObject



518
519
520
521
522
523
524
525
# File 'app/models/merge_request_diff.rb', line 518

def compare
  @compare ||=
    Gitlab::Git::Compare.new(
      repository.raw_repository,
      safe_start_commit_sha,
      head_commit_sha
    )
end

#compare_with(sha) ⇒ Object

rubocop: disable CodeReuse/ServiceClass



532
533
534
535
536
537
# File 'app/models/merge_request_diff.rb', line 532

def compare_with(sha)
  # When compare merge request versions we want diff A..B instead of A...B
  # so we handle cases when user does squash and rebase of the commits between versions.
  # For this reason we set straight to true by default.
  CompareService.new(project, head_commit_sha).execute(project, sha, straight: true)
end

#diff_refsObject



399
400
401
402
403
404
405
406
407
# File 'app/models/merge_request_diff.rb', line 399

def diff_refs
  return unless start_commit_sha || base_commit_sha

  Gitlab::Diff::DiffRefs.new(
    base_sha: base_commit_sha,
    start_sha: start_commit_sha,
    head_sha: head_commit_sha
  )
end

#diff_refs=(new_diff_refs) ⇒ Object



393
394
395
396
397
# File 'app/models/merge_request_diff.rb', line 393

def diff_refs=(new_diff_refs)
  self.base_commit_sha = new_diff_refs&.base_sha
  self.start_commit_sha = new_diff_refs&.start_sha
  self.head_commit_sha = new_diff_refs&.head_sha
end

#diff_refs_by_sha?Boolean

Returns:

  • (Boolean)


432
433
434
# File 'app/models/merge_request_diff.rb', line 432

def diff_refs_by_sha?
  base_commit_sha? && head_commit_sha? && start_commit_sha?
end

#diffs(diff_options = nil) ⇒ Object



492
493
494
495
496
497
498
499
500
501
502
503
504
# File 'app/models/merge_request_diff.rb', line 492

def diffs(diff_options = nil)
  fetching_repository_diffs(diff_options) do |comparison|
    # It should fetch the repository when diffs are cleaned by the system.
    # We don't keep these for storage overload purposes.
    # See https://gitlab.com/gitlab-org/gitlab-foss/issues/37639
    if comparison
      comparison.diffs(diff_options)
    else
      reorder_diff_files!
      diffs_collection(diff_options)
    end
  end
end

#diffs_collection(diff_options = nil) ⇒ Object

Should always return the DB persisted diffs collection (e.g. Gitlab::Diff::FileCollection::MergeRequestDiff. It’s useful when trying to invalidate old caches through FileCollection::MergeRequestDiff#clear_cache!



510
511
512
# File 'app/models/merge_request_diff.rb', line 510

def diffs_collection(diff_options = nil)
  Gitlab::Diff::FileCollection::MergeRequestDiff.new(self, diff_options: diff_options)
end

#diffs_in_batch(batch_page, batch_size, diff_options:) ⇒ Object



436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
# File 'app/models/merge_request_diff.rb', line 436

def diffs_in_batch(batch_page, batch_size, diff_options:)
  fetching_repository_diffs(diff_options) do |comparison|
    Gitlab::Metrics.measure(:diffs_reorder) do
      reorder_diff_files!
    end

    diffs_batch = Gitlab::Metrics.measure(:diffs_collection) do
      diffs_in_batch_collection(batch_page, batch_size, diff_options: diff_options)
    end

    if comparison
      if diff_options[:paths].blank? && !without_files?
        # Return the empty MergeRequestDiffBatch for an out of bound batch request
        break diffs_batch if diffs_batch.diff_paths.blank?

        diff_options.merge!(
          paths: diffs_batch.diff_paths,
          pagination_data: diffs_batch.pagination_data
        )
      end

      diff_options[:generated_files] = comparison.generated_files

      Gitlab::Metrics.measure(:diffs_comparison) do
        comparison.diffs(diff_options)
      end
    else
      diffs_batch
    end
  end
end

#ensure_commit_shasObject



276
277
278
279
280
281
282
283
284
285
286
287
288
# File 'app/models/merge_request_diff.rb', line 276

def ensure_commit_shas
  self.start_commit_sha ||= merge_request.target_branch_sha

  if merge_head? && merge_request.merge_ref_head.present?
    diff_refs = merge_request.merge_ref_head.diff_refs

    self.head_commit_sha  ||= diff_refs.head_sha
    self.base_commit_sha  ||= diff_refs.base_sha
  else
    self.head_commit_sha  ||= merge_request.source_branch_sha
    self.base_commit_sha  ||= find_base_sha
  end
end

#fallback_diff_refsObject

MRs created before 8.4 don’t store their true diff refs (start and base), but we need to get a commit SHA for the “View file @ …” link by a file, so we use an approximation of the diff refs if we can’t get the actual one.

These will not be the actual diff refs if the target branch was merged into the source branch after the merge request was created, but it is good enough for the specific purpose of linking to a commit.

It is not good enough for highlighting diffs, so we can’t simply pass these as ‘diff_refs.`



419
420
421
422
423
424
425
426
427
428
429
430
# File 'app/models/merge_request_diff.rb', line 419

def fallback_diff_refs
  real_refs = diff_refs
  return real_refs if real_refs

  likely_base_commit_sha = (first_commit&.parent || first_commit)&.sha

  Gitlab::Diff::DiffRefs.new(
    base_sha: likely_base_commit_sha,
    start_sha: safe_start_commit_sha,
    head_sha: head_commit_sha
  )
end

#files_countObject



300
301
302
303
304
305
306
307
308
309
# File 'app/models/merge_request_diff.rb', line 300

def files_count
  db_value = read_attribute(:files_count)

  case db_value
  when nil, FILES_COUNT_SENTINEL
    merge_request_diff_files.count
  else
    db_value
  end
end

#first_commitObject



347
348
349
# File 'app/models/merge_request_diff.rb', line 347

def first_commit
  commits.last
end

#get_patch_id_shaObject



251
252
253
254
255
256
257
258
259
260
# File 'app/models/merge_request_diff.rb', line 251

def get_patch_id_sha
  return patch_id_sha if patch_id_sha.present?

  set_patch_id_sha

  return unless patch_id_sha.present?

  save
  patch_id_sha
end

#has_encoded_file_paths?Boolean

Returns:

  • (Boolean)


649
650
651
# File 'app/models/merge_request_diff.rb', line 649

def has_encoded_file_paths?
  merge_request_diff_files.where(encoded_file_path: true).any?
end

#head_commitObject



367
368
369
370
371
# File 'app/models/merge_request_diff.rb', line 367

def head_commit
  return unless head_commit_sha

  project.commit_by(oid: head_commit_sha)
end

#head_commit_shaObject

Override head_commit_sha to keep compatibility with merge request diff created before version 8.4 that does not store head_commit_sha in separate db field.



292
293
294
295
296
297
298
# File 'app/models/merge_request_diff.rb', line 292

def head_commit_sha
  if persisted? && super.nil?
    last_commit_sha
  else
    super
  end
end

#includes_any_commits?(shas) ⇒ Boolean

Returns:

  • (Boolean)


383
384
385
386
387
388
389
390
391
# File 'app/models/merge_request_diff.rb', line 383

def includes_any_commits?(shas)
  return false if shas.blank?

  # when the number of shas is huge (1000+) we don't want
  # to pass them all as an SQL param, let's pass them in batches
  shas.each_slice(BATCH_SIZE).any? do |batched_shas|
    merge_request_diff_commits.where(sha: batched_shas).exists?
  end
end

#last_commitObject



351
352
353
# File 'app/models/merge_request_diff.rb', line 351

def last_commit
  commits.first
end

#last_commit_shaObject



343
344
345
# File 'app/models/merge_request_diff.rb', line 343

def last_commit_sha
  commit_shas(limit: 1).first
end

#latest?Boolean

Returns:

  • (Boolean)


527
528
529
# File 'app/models/merge_request_diff.rb', line 527

def latest?
  self.id == merge_request.latest_merge_request_diff_id
end

#lines_countObject



322
323
324
325
326
# File 'app/models/merge_request_diff.rb', line 322

def lines_count
  strong_memoize(:lines_count) do
    raw_diffs(limits: false).line_count
  end
end

#migrate_files_to_database!Object

Transactionally migrate the current merge_request_diff_files entries from external storage, back to the database. This is the rollback operation for migrate_files_to_external_storage!

If this diff isn’t in external storage, the method is a no-op.



609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
# File 'app/models/merge_request_diff.rb', line 609

def migrate_files_to_database!
  return unless stored_externally?
  return if files_count == 0

  rows = convert_external_diffs_to_database

  transaction do
    MergeRequestDiffFile.where(merge_request_diff_id: id).delete_all
    ApplicationRecord.legacy_bulk_insert('merge_request_diff_files', rows) # rubocop:disable Gitlab/BulkInsert
    update!(stored_externally: false)
  end

  # Only delete the external diff file after the contents have been saved to
  # the database
  remove_external_diff!
  merge_request_diff_files.reset
end

#migrate_files_to_external_storage!Object

Transactionally migrate the current merge_request_diff_files entries to external storage. If external storage isn’t an option for this diff, the method is a no-op.



584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
# File 'app/models/merge_request_diff.rb', line 584

def migrate_files_to_external_storage!
  return if stored_externally? || !use_external_diff? || files_count == 0

  rows = build_merge_request_diff_files(merge_request_diff_files)
  rows = build_external_merge_request_diff_files(rows)

  # Perform carrierwave activity before entering the database transaction.
  # This is safe as until the `external_diff_store` column is changed, we will
  # continue to consult the in-database content.
  self.external_diff.store!

  transaction do
    MergeRequestDiffFile.where(merge_request_diff_id: id).delete_all
    ApplicationRecord.legacy_bulk_insert('merge_request_diff_files', rows) # rubocop:disable Gitlab/BulkInsert
    save!
  end

  merge_request_diff_files.reset
end

#modified_paths(fallback_on_overflow: false) ⇒ Object

rubocop: enable CodeReuse/ServiceClass



540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
# File 'app/models/merge_request_diff.rb', line 540

def modified_paths(fallback_on_overflow: false)
  if fallback_on_overflow && overflow?
    # This is an extremely slow means to find the modified paths for a given
    #   MergeRequestDiff. This should be avoided, except where the limit of
    #   1_000 (as of %12.10) entries returned by the default behavior is an
    #   issue.
    strong_memoize(:overflowed_modified_paths) do
      project.repository.diff_stats(
        base_commit_sha,
        head_commit_sha
      ).paths
    end
  else
    strong_memoize(:modified_paths) do
      merge_request_diff_files.pluck(:new_path, :old_path).flatten.uniq
    end
  end
end

#opening_external_diffObject

If enabled, yields the external file containing the diff. Otherwise, yields nil. This method is not thread-safe, but it is re-entrant, which allows multiple merge_request_diff_files to load their data efficiently



568
569
570
571
572
573
574
575
576
577
578
579
# File 'app/models/merge_request_diff.rb', line 568

def opening_external_diff
  return yield(nil) unless stored_externally?
  return yield(@external_diff_file) if @external_diff_file

  external_diff.open do |file|
    @external_diff_file = file

    yield(@external_diff_file)
  ensure
    @external_diff_file = nil
  end
end

#paginated_diffs(page, per_page) ⇒ Object



468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
# File 'app/models/merge_request_diff.rb', line 468

def paginated_diffs(page, per_page)
  fetching_repository_diffs({}) do |comparison|
    reorder_diff_files!

    collection = Gitlab::Diff::FileCollection::PaginatedMergeRequestDiff.new(
      self,
      page,
      per_page
    )

    if comparison
      comparison.diffs(
        generated_files: comparison.generated_files,
        paths: collection.diff_paths,
        page: collection.current_page,
        per_page: collection.limit_value,
        count: collection.total_count
      )
    else
      collection
    end
  end
end

#projectObject



514
515
516
# File 'app/models/merge_request_diff.rb', line 514

def project
  merge_request.target_project
end

#raw_diffs(options = {}) ⇒ Object



328
329
330
331
332
333
334
335
# File 'app/models/merge_request_diff.rb', line 328

def raw_diffs(options = {})
  if options[:ignore_whitespace_change]
    @diffs_no_whitespace ||= compare.diffs(options)
  else
    @raw_diffs ||= {}
    @raw_diffs[options] ||= load_diffs(options)
  end
end

#remove_cached_external_diffObject



640
641
642
643
644
645
646
647
# File 'app/models/merge_request_diff.rb', line 640

def remove_cached_external_diff
  Gitlab::PathTraversal.check_path_traversal!(external_diff_cache_dir)
  Gitlab::PathTraversal.check_allowed_absolute_path!(external_diff_cache_dir, [Dir.tmpdir])

  return unless Dir.exist?(external_diff_cache_dir)

  FileUtils.rm_rf(external_diff_cache_dir)
end

#safe_start_commit_shaObject

This method will rely on repository branch sha in case start_commit_sha is nil. It’s necessary for old merge request diff created before version 8.4 to work



314
315
316
# File 'app/models/merge_request_diff.rb', line 314

def safe_start_commit_sha
  start_commit_sha || merge_request.target_branch_sha
end

#save_git_contentObject

Collect information about commits and diff from repository and save it to the database as serialized data



224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'app/models/merge_request_diff.rb', line 224

def save_git_content
  ensure_commit_shas
  set_patch_id_sha

  save_commits
  save_diffs

  # Another set of `after_save` hooks will be called here when we update the record
  save
  # We need to reset so that dirty tracking is reset when running the original set
  # of `after_save` hooks that come after this `after_create` hook. Otherwise, the
  # hooks that run when an attribute was changed are run twice.
  reset

  keep_around_commits unless importing?
end

#set_as_latest_diffObject



262
263
264
265
266
267
268
269
270
# File 'app/models/merge_request_diff.rb', line 262

def set_as_latest_diff
  # Don't set merge_head diff as latest so it won't get considered as the
  # MergeRequest#merge_request_diff.
  return if merge_head?

  MergeRequest
    .where('id = ? AND COALESCE(latest_merge_request_diff_id, 0) < ?', self.merge_request_id, self.id)
    .update_all(latest_merge_request_diff_id: self.id)
end

#set_patch_id_shaObject



241
242
243
244
245
246
247
248
249
# File 'app/models/merge_request_diff.rb', line 241

def set_patch_id_sha
  return unless base_commit_sha && head_commit_sha
  return if base_commit_sha == head_commit_sha

  self.patch_id_sha = project.repository&.get_patch_id(
    base_commit_sha,
    head_commit_sha
  )
end

#sizeObject



318
319
320
# File 'app/models/merge_request_diff.rb', line 318

def size
  real_size.presence || raw_diffs.size
end

#start_commitObject



361
362
363
364
365
# File 'app/models/merge_request_diff.rb', line 361

def start_commit
  return unless start_commit_sha

  project.commit_by(oid: start_commit_sha)
end

#trigger_diff_generated_subscriptionObject



272
273
274
# File 'app/models/merge_request_diff.rb', line 272

def trigger_diff_generated_subscription
  GraphqlTriggers.merge_request_diff_generated(merge_request)
end

#update_external_diff_storeObject



559
560
561
562
563
# File 'app/models/merge_request_diff.rb', line 559

def update_external_diff_store
  return unless saved_change_to_external_diff? || saved_change_to_stored_externally?

  update_column(:external_diff_store, external_diff.object_store)
end

#viewable?Boolean

Returns:

  • (Boolean)


218
219
220
# File 'app/models/merge_request_diff.rb', line 218

def viewable?
  collected? || without_files? || overflow?
end