-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
batch_with_throttling.rb
108 lines (96 loc) · 2.75 KB
/
batch_with_throttling.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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
105
106
107
108
# frozen_string_literal: true
module RuboCop
module Cop
module Migration
# Use throttling in batch processing.
#
# @safety
# There are some cases where we should not do throttling,
# or the throttling might be already done in a way that we cannot detect.
#
# @example
# # bad
# class BackfillSomeColumn < ActiveRecord::Migration[7.0]
# disable_ddl_transaction!
#
# def change
# User.in_batches do |relation|
# relation.update_all(some_column: 'some value')
# end
# end
# end
#
# # good
# class BackfillSomeColumnToUsers < ActiveRecord::Migration[7.0]
# disable_ddl_transaction!
#
# def up
# User.in_batches do |relation|
# relation.update_all(some_column: 'some value')
# sleep(0.01)
# end
# end
# end
class BatchWithThrottling < RuboCop::Cop::Base
extend AutoCorrector
include ::RuboCop::Migration::CopConcerns::BatchProcessing
MSG = 'Use throttling in batch processing.'
RESTRICT_ON_SEND = %i[
delete_all
update_all
].freeze
# @param node [RuboCop::AST::SendNode]
# @return [void]
def on_send(node)
return unless wrong?(node)
add_offense(node) do |corrector|
autocorrect(corrector, node)
end
end
private
# @!method sleep?(node)
# @param node [RuboCop::AST::Node]
# @return [Boolean]
def_node_matcher :sleep?, <<~PATTERN
(send
nil?
:sleep
...
)
PATTERN
# @param corrector [RuboCop::Cop::Corrector]
# @param node [RuboCop::AST::SendNode]
# @return [void]
def autocorrect(
corrector,
node
)
corrector.insert_after(
node,
"\n#{' ' * node.location.column}sleep(0.01)"
)
end
# @param node [RuboCop::AST::Node]
# @return [Boolean]
def in_block?(node)
node.parent&.block_type? ||
(node.parent&.begin_type? && node.parent.parent&.block_type?)
end
# @param node [RuboCop::AST::SendNode]
# @return [Boolean]
def with_throttling?(node)
(node.left_siblings + node.right_siblings).any? do |sibling|
sleep?(sibling)
end
end
# @param node [RuboCop::AST::SendNode]
# @return [Boolean]
def wrong?(node)
batch_processing?(node) &&
in_block?(node) &&
!with_throttling?(node)
end
end
end
end
end