summaryrefslogtreecommitdiff
path: root/spec/initializers/database_config_spec.rb
blob: 29d499efcd3b178820eab0dff5b0c4be72bdf7f5 (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
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Database config initializer' do
  subject do
    load Rails.root.join('config/initializers/database_config.rb')
  end

  before do
    allow(ActiveRecord::Base).to receive(:establish_connection)
  end

  context "when using multi-threaded runtime" do
    let(:max_threads) { 8 }

    before do
      allow(Gitlab::Runtime).to receive(:multi_threaded?).and_return(true)
      allow(Gitlab::Runtime).to receive(:max_threads).and_return(max_threads)
    end

    context "and no existing pool size is set" do
      before do
        stub_database_config(pool_size: nil)
      end

      it "sets it to the max number of worker threads" do
        expect { subject }.to change { Gitlab::Database.config['pool'] }.from(nil).to(max_threads)
      end
    end

    context "and the existing pool size is smaller than the max number of worker threads" do
      before do
        stub_database_config(pool_size: max_threads - 1)
      end

      it "sets it to the max number of worker threads" do
        expect { subject }.to change { Gitlab::Database.config['pool'] }.by(1)
      end
    end

    context "and the existing pool size is larger than the max number of worker threads" do
      before do
        stub_database_config(pool_size: max_threads + 1)
      end

      it "keeps the configured pool size" do
        expect { subject }.not_to change { Gitlab::Database.config['pool'] }
      end
    end

    context "when specifying headroom through an ENV variable" do
      let(:headroom) { 10 }

      before do
        stub_database_config(pool_size: 1)
        stub_env("DB_POOL_HEADROOM", headroom)
      end

      it "adds headroom on top of the calculated size" do
        expect { subject }.to change { Gitlab::Database.config['pool'] }
                                .from(1)
                                .to(max_threads + headroom)
      end
    end
  end

  context "when using single-threaded runtime" do
    it "does nothing" do
      expect { subject }.not_to change { Gitlab::Database.config['pool'] }
    end
  end

  def stub_database_config(pool_size:)
    config = {
      'adapter' => 'postgresql',
      'host' => 'db.host.com',
      'pool' => pool_size
    }.compact

    allow(Gitlab::Database).to receive(:config).and_return(config)
  end
end