summaryrefslogtreecommitdiff
path: root/spec/lib/gitlab/metrics/subscribers/active_record_spec.rb
blob: edcd5b319415f97fd7a1aa6b84b41ce0c2915d56 (plain)
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
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Gitlab::Metrics::Subscribers::ActiveRecord do
  let(:env) { {} }
  let(:transaction) { Gitlab::Metrics::WebTransaction.new(env) }
  let(:subscriber)  { described_class.new }
  let(:payload) { { sql: 'SELECT * FROM users WHERE id = 10' } }

  let(:event) do
    double(
      :event,
      name: 'sql.active_record',
      duration: 2,
      payload:  payload
    )
  end

  describe '#sql' do
    shared_examples 'track query in metrics' do
      before do
        allow(subscriber).to receive(:current_transaction)
                               .at_least(:once)
                               .and_return(transaction)
      end

      it 'increments only db count value' do
        described_class::DB_COUNTERS.each do |counter|
          prometheus_counter = "gitlab_transaction_#{counter}_total".to_sym
          if expected_counters[counter] > 0
            expect(transaction).to receive(:increment).with(prometheus_counter, 1)
          else
            expect(transaction).not_to receive(:increment).with(prometheus_counter, 1)
          end
        end

        subscriber.sql(event)
      end
    end

    shared_examples 'track query in RequestStore' do
      context 'when RequestStore is enabled' do
        it 'caches db count value', :request_store, :aggregate_failures do
          subscriber.sql(event)

          described_class::DB_COUNTERS.each do |counter|
            expect(Gitlab::SafeRequestStore[counter].to_i).to eq expected_counters[counter]
          end
        end

        it 'prevents db counters from leaking to the next transaction' do
          2.times do
            Gitlab::WithRequestStore.with_request_store do
              subscriber.sql(event)

              described_class::DB_COUNTERS.each do |counter|
                expect(Gitlab::SafeRequestStore[counter].to_i).to eq expected_counters[counter]
              end
            end
          end
        end
      end
    end

    describe 'without a current transaction' do
      it 'does not track any metrics' do
        expect_any_instance_of(Gitlab::Metrics::Transaction)
          .not_to receive(:increment)

        subscriber.sql(event)
      end

      context 'with read query' do
        let(:expected_counters) do
          {
            db_count: 1,
            db_write_count: 0,
            db_cached_count: 0
          }
        end

        it_behaves_like 'track query in RequestStore'
      end
    end

    describe 'with a current transaction' do
      it 'observes sql_duration metric' do
        expect(subscriber).to receive(:current_transaction)
                                .at_least(:once)
                                .and_return(transaction)
        expect(transaction).to receive(:observe).with(:gitlab_sql_duration_seconds, 0.002)

        subscriber.sql(event)
      end

      it 'marks the current thread as using the database' do
        # since it would already have been toggled by other specs
        Thread.current[:uses_db_connection] = nil

        expect { subscriber.sql(event) }.to change { Thread.current[:uses_db_connection] }.from(nil).to(true)
      end

      context 'with read query' do
        let(:expected_counters) do
          {
            db_count: 1,
            db_write_count: 0,
            db_cached_count: 0
          }
        end

        it_behaves_like 'track query in metrics'
        it_behaves_like 'track query in RequestStore'

        context 'with only select' do
          let(:payload) { { sql: 'WITH active_milestones AS (SELECT COUNT(*), state FROM milestones GROUP BY state) SELECT * FROM active_milestones' } }

          it_behaves_like 'track query in metrics'
          it_behaves_like 'track query in RequestStore'
        end
      end

      context 'write query' do
        let(:expected_counters) do
          {
            db_count: 1,
            db_write_count: 1,
            db_cached_count: 0
          }
        end

        context 'with select for update sql event' do
          let(:payload) { { sql: 'SELECT * FROM users WHERE id = 10 FOR UPDATE' } }

          it_behaves_like 'track query in metrics'
          it_behaves_like 'track query in RequestStore'
        end

        context 'with common table expression' do
          context 'with insert' do
            let(:payload) { { sql: 'WITH archived_rows AS (SELECT * FROM users WHERE archived = true) INSERT INTO products_log SELECT * FROM archived_rows' } }

            it_behaves_like 'track query in metrics'
            it_behaves_like 'track query in RequestStore'
          end
        end

        context 'with delete sql event' do
          let(:payload) { { sql: 'DELETE FROM users where id = 10' } }

          it_behaves_like 'track query in metrics'
          it_behaves_like 'track query in RequestStore'
        end

        context 'with insert sql event' do
          let(:payload) { { sql: 'INSERT INTO project_ci_cd_settings (project_id) SELECT id FROM projects' } }

          it_behaves_like 'track query in metrics'
          it_behaves_like 'track query in RequestStore'
        end

        context 'with update sql event' do
          let(:payload) { { sql: 'UPDATE users SET admin = true WHERE id = 10' } }

          it_behaves_like 'track query in metrics'
          it_behaves_like 'track query in RequestStore'
        end
      end

      context 'with cached query' do
        let(:expected_counters) do
          {
            db_count: 1,
            db_write_count: 0,
            db_cached_count: 1
          }
        end

        context 'with cached payload ' do
          let(:payload) do
            {
              sql: 'SELECT * FROM users WHERE id = 10',
              cached: true
            }
          end

          it_behaves_like 'track query in metrics'
          it_behaves_like 'track query in RequestStore'
        end

        context 'with cached payload name' do
          let(:payload) do
            {
              sql: 'SELECT * FROM users WHERE id = 10',
              name: 'CACHE'
            }
          end

          it_behaves_like 'track query in metrics'
          it_behaves_like 'track query in RequestStore'
        end
      end

      context 'events are internal to Rails or irrelevant' do
        let(:schema_event) do
          double(
            :event,
            name: 'sql.active_record',
            payload: {
              sql: "SELECT attr.attname FROM pg_attribute attr INNER JOIN pg_constraint cons ON attr.attrelid = cons.conrelid AND attr.attnum = any(cons.conkey) WHERE cons.contype = 'p' AND cons.conrelid = '\"projects\"'::regclass",
              name: 'SCHEMA',
              connection_id: 135,
              statement_name: nil,
              binds: []
            },
            duration: 0.7
          )
        end

        let(:begin_event) do
          double(
            :event,
            name: 'sql.active_record',
            payload: {
              sql: "BEGIN",
              name: nil,
              connection_id: 231,
              statement_name: nil,
              binds: []
            },
            duration: 1.1
          )
        end

        let(:commit_event) do
          double(
            :event,
            name: 'sql.active_record',
            payload: {
              sql: "COMMIT",
              name: nil,
              connection_id: 212,
              statement_name: nil,
              binds: []
            },
            duration: 1.6
          )
        end

        it 'skips schema/begin/commit sql commands' do
          allow(subscriber).to receive(:current_transaction)
                                 .at_least(:once)
                                 .and_return(transaction)

          expect(transaction).not_to receive(:increment)

          subscriber.sql(schema_event)
          subscriber.sql(begin_event)
          subscriber.sql(commit_event)
        end
      end
    end
  end

  describe 'self.db_counter_payload' do
    before do
      allow(subscriber).to receive(:current_transaction)
                             .at_least(:once)
                             .and_return(transaction)
    end

    context 'when RequestStore is enabled', :request_store do
      context 'when query is executed' do
        let(:expected_payload) do
          {
            db_count: 1,
            db_cached_count: 0,
            db_write_count: 0
          }
        end

        it 'returns correct payload' do
          subscriber.sql(event)

          expect(described_class.db_counter_payload).to eq(expected_payload)
        end
      end

      context 'when query is not executed' do
        let(:expected_payload) do
          {
            db_count: 0,
            db_cached_count: 0,
            db_write_count: 0
          }
        end

        it 'returns correct payload' do
          expect(described_class.db_counter_payload).to eq(expected_payload)
        end
      end
    end

    context 'when RequestStore is disabled' do
      let(:expected_payload) { {} }

      it 'returns empty payload' do
        subscriber.sql(event)

        expect(described_class.db_counter_payload).to eq(expected_payload)
      end
    end
  end
end