Welcome to mirror list, hosted at ThFree Co, Russian Federation.

duplicate_job_spec.rb « duplicate_jobs « sidekiq_middleware « gitlab « lib « spec - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: abe083f911b56c9fc4fc160b8b11afa9f2f6798f (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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Gitlab::SidekiqMiddleware::DuplicateJobs::DuplicateJob, :clean_gitlab_redis_queues, :clean_gitlab_redis_shared_state do
  using RSpec::Parameterized::TableSyntax

  subject(:duplicate_job) do
    described_class.new(job, queue)
  end

  let(:wal_locations) do
    {
      'main' => '0/D525E3A8',
      'ci' => 'AB/12345'
    }
  end

  let(:job) { { 'class' => 'AuthorizedProjectsWorker', 'args' => [1], 'jid' => '123', 'wal_locations' => wal_locations } }
  let(:queue) { 'authorized_projects' }

  let(:idempotency_key) do
    hash = Digest::SHA256.hexdigest("#{job['class']}:#{Sidekiq.dump_json(job['args'])}")
    "#{Gitlab::Redis::Queues::SIDEKIQ_NAMESPACE}:duplicate:#{queue}:#{hash}"
  end

  describe '#schedule' do
    shared_examples 'scheduling with deduplication class' do |strategy_class|
      it 'calls schedule on the strategy' do
        expect do |block|
          expect_next_instance_of("Gitlab::SidekiqMiddleware::DuplicateJobs::Strategies::#{strategy_class}".constantize) do |strategy|
            expect(strategy).to receive(:schedule).with(job, &block)
          end

          duplicate_job.schedule(&block)
        end.to yield_control
      end
    end

    it_behaves_like 'scheduling with deduplication class', 'UntilExecuting'

    context 'when the deduplication depends on a FF' do
      before do
        skip_feature_flags_yaml_validation
        skip_default_enabled_yaml_check

        allow(AuthorizedProjectsWorker).to receive(:get_deduplication_options).and_return(feature_flag: :my_feature_flag)
      end

      context 'when the feature flag is enabled' do
        before do
          stub_feature_flags(my_feature_flag: true)
        end

        it_behaves_like 'scheduling with deduplication class', 'UntilExecuting'
      end

      context 'when the feature flag is disabled' do
        before do
          stub_feature_flags(my_feature_flag: false)
        end

        it_behaves_like 'scheduling with deduplication class', 'None'
      end
    end
  end

  describe '#perform' do
    it 'calls perform on the strategy' do
      expect do |block|
        expect_next_instance_of(Gitlab::SidekiqMiddleware::DuplicateJobs::Strategies::UntilExecuting) do |strategy|
          expect(strategy).to receive(:perform).with(job, &block)
        end

        duplicate_job.perform(&block)
      end.to yield_control
    end
  end

  shared_examples 'with multiple Redis keys' do
    let(:deduplicated_flag_key) do
      "#{idempotency_key}:deduplicate_flag"
    end

    describe '#check!' do
      context 'when there was no job in the queue yet' do
        it { expect(duplicate_job.check!).to eq('123') }

        shared_examples 'sets Redis keys with correct TTL' do
          it "adds an idempotency key with correct ttl" do
            expect { duplicate_job.check! }
              .to change { read_idempotency_key_with_ttl(idempotency_key) }
                    .from([nil, -2])
                    .to(['123', be_within(1).of(expected_ttl)])
          end

          context 'when wal locations is not empty' do
            it "adds an existing wal locations key with correct ttl" do
              expect { duplicate_job.check! }
                .to change { read_idempotency_key_with_ttl(existing_wal_location_key(idempotency_key, 'main')) }
                      .from([nil, -2])
                      .to([wal_locations['main'], be_within(1).of(expected_ttl)])
                .and change { read_idempotency_key_with_ttl(existing_wal_location_key(idempotency_key, 'ci')) }
                      .from([nil, -2])
                      .to([wal_locations['ci'], be_within(1).of(expected_ttl)])
            end
          end
        end

        context 'when TTL option is not set' do
          let(:expected_ttl) { described_class::DEFAULT_DUPLICATE_KEY_TTL }

          it_behaves_like 'sets Redis keys with correct TTL'
        end

        context 'when TTL option is set' do
          let(:expected_ttl) { 5.minutes }

          before do
            allow(duplicate_job).to receive(:options).and_return({ ttl: expected_ttl })
          end

          it_behaves_like 'sets Redis keys with correct TTL'
        end

        it "adds the idempotency key to the jobs payload" do
          expect { duplicate_job.check! }.to change { job['idempotency_key'] }.from(nil).to(idempotency_key)
        end
      end

      context 'when there was already a job with same arguments in the same queue' do
        before do
          set_idempotency_key(idempotency_key, 'existing-key')
          wal_locations.each do |config_name, location|
            set_idempotency_key(existing_wal_location_key(idempotency_key, config_name), location)
          end
        end

        it { expect(duplicate_job.check!).to eq('existing-key') }

        it "does not change the existing key's TTL" do
          expect { duplicate_job.check! }
            .not_to change { read_idempotency_key_with_ttl(idempotency_key) }
                  .from(['existing-key', -1])
        end

        it "does not change the existing wal locations key's TTL" do
          expect { duplicate_job.check! }
            .to not_change { read_idempotency_key_with_ttl(existing_wal_location_key(idempotency_key, 'main')) }
                  .from([wal_locations['main'], -1])
            .and not_change { read_idempotency_key_with_ttl(existing_wal_location_key(idempotency_key, 'ci')) }
                  .from([wal_locations['ci'], -1])
        end

        it 'sets the existing jid' do
          duplicate_job.check!

          expect(duplicate_job.existing_jid).to eq('existing-key')
        end
      end
    end

    describe '#update_latest_wal_location!' do
      before do
        allow(Gitlab::Database).to receive(:database_base_models).and_return(
          { main: ::ActiveRecord::Base,
            ci: ::ActiveRecord::Base })

        set_idempotency_key(existing_wal_location_key(idempotency_key, 'main'), existing_wal['main'])
        set_idempotency_key(existing_wal_location_key(idempotency_key, 'ci'), existing_wal['ci'])

        # read existing_wal_locations
        duplicate_job.check!
      end

      context "when the key doesn't exists in redis" do
        let(:existing_wal) do
          {
            'main' => '0/D525E3A0',
            'ci' => 'AB/12340'
          }
        end

        let(:new_wal_location_with_offset) do
          {
            # offset is relative to `existing_wal`
            'main' => ['0/D525E3A8', '8'],
            'ci' => ['AB/12345', '5']
          }
        end

        let(:wal_locations) { new_wal_location_with_offset.transform_values(&:first) }

        it 'stores a wal location to redis with an offset relative to existing wal location' do
          expect { duplicate_job.update_latest_wal_location! }
            .to change { read_range_from_redis(wal_location_key(idempotency_key, 'main')) }
                  .from([])
                  .to(new_wal_location_with_offset['main'])
            .and change { read_range_from_redis(wal_location_key(idempotency_key, 'ci')) }
                  .from([])
                  .to(new_wal_location_with_offset['ci'])
        end
      end

      context "when the key exists in redis" do
        before do
          rpush_to_redis_key(wal_location_key(idempotency_key, 'main'), *stored_wal_location_with_offset['main'])
          rpush_to_redis_key(wal_location_key(idempotency_key, 'ci'), *stored_wal_location_with_offset['ci'])
        end

        let(:wal_locations) { new_wal_location_with_offset.transform_values(&:first) }

        context "when the new offset is bigger then the existing one" do
          let(:existing_wal) do
            {
              'main' => '0/D525E3A0',
              'ci' => 'AB/12340'
            }
          end

          let(:stored_wal_location_with_offset) do
            {
              # offset is relative to `existing_wal`
              'main' => ['0/D525E3A3', '3'],
              'ci' => ['AB/12342', '2']
            }
          end

          let(:new_wal_location_with_offset) do
            {
              # offset is relative to `existing_wal`
              'main' => ['0/D525E3A8', '8'],
              'ci' => ['AB/12345', '5']
            }
          end

          it 'updates a wal location to redis with an offset' do
            expect { duplicate_job.update_latest_wal_location! }
              .to change { read_range_from_redis(wal_location_key(idempotency_key, 'main')) }
                    .from(stored_wal_location_with_offset['main'])
                    .to(new_wal_location_with_offset['main'])
              .and change { read_range_from_redis(wal_location_key(idempotency_key, 'ci')) }
                    .from(stored_wal_location_with_offset['ci'])
                    .to(new_wal_location_with_offset['ci'])
          end
        end

        context "when the old offset is not bigger then the existing one" do
          let(:existing_wal) do
            {
              'main' => '0/D525E3A0',
              'ci' => 'AB/12340'
            }
          end

          let(:stored_wal_location_with_offset) do
            {
              # offset is relative to `existing_wal`
              'main' => ['0/D525E3A8', '8'],
              'ci' => ['AB/12345', '5']
            }
          end

          let(:new_wal_location_with_offset) do
            {
              # offset is relative to `existing_wal`
              'main' => ['0/D525E3A2', '2'],
              'ci' => ['AB/12342', '2']
            }
          end

          it "does not update a wal location to redis with an offset" do
            expect { duplicate_job.update_latest_wal_location! }
              .to not_change { read_range_from_redis(wal_location_key(idempotency_key, 'main')) }
                    .from(stored_wal_location_with_offset['main'])
              .and not_change { read_range_from_redis(wal_location_key(idempotency_key, 'ci')) }
                    .from(stored_wal_location_with_offset['ci'])
          end
        end
      end
    end

    describe '#latest_wal_locations' do
      context 'when job was deduplicated and wal locations were already persisted' do
        before do
          rpush_to_redis_key(wal_location_key(idempotency_key, 'main'), wal_locations['main'], 1024)
          rpush_to_redis_key(wal_location_key(idempotency_key, 'ci'), wal_locations['ci'], 1024)
        end

        it { expect(duplicate_job.latest_wal_locations).to eq(wal_locations) }
      end

      context 'when job is not deduplication and wal locations were not persisted' do
        it { expect(duplicate_job.latest_wal_locations).to be_empty }
      end
    end

    describe '#delete!' do
      context "when we didn't track the definition" do
        it { expect { duplicate_job.delete! }.not_to raise_error }
      end

      context 'when the key exists in redis' do
        before do
          set_idempotency_key(idempotency_key, 'existing-jid')
          set_idempotency_key(deduplicated_flag_key, 1)
          wal_locations.each do |config_name, location|
            set_idempotency_key(existing_wal_location_key(idempotency_key, config_name), location)
            set_idempotency_key(wal_location_key(idempotency_key, config_name), location)
          end
        end

        shared_examples 'deleting the duplicate job' do
          shared_examples 'deleting keys from redis' do |key_name|
            it "removes the #{key_name} from redis" do
              expect { duplicate_job.delete! }
                .to change { read_idempotency_key_with_ttl(key) }
                      .from([from_value, -1])
                      .to([nil, -2])
            end
          end

          shared_examples 'does not delete key from redis' do |key_name|
            it "does not remove the #{key_name} from redis" do
              expect { duplicate_job.delete! }
                .to not_change { read_idempotency_key_with_ttl(key) }
                      .from([from_value, -1])
            end
          end

          it_behaves_like 'deleting keys from redis', 'idempotent key' do
            let(:key) { idempotency_key }
            let(:from_value) { 'existing-jid' }
          end

          it_behaves_like 'deleting keys from redis', 'deduplication counter key' do
            let(:key) { deduplicated_flag_key }
            let(:from_value) { '1' }
          end

          it_behaves_like 'deleting keys from redis', 'existing wal location keys for main database' do
            let(:key) { existing_wal_location_key(idempotency_key, 'main') }
            let(:from_value) { wal_locations['main'] }
          end

          it_behaves_like 'deleting keys from redis', 'existing wal location keys for ci database' do
            let(:key) { existing_wal_location_key(idempotency_key, 'ci') }
            let(:from_value) { wal_locations['ci'] }
          end

          it_behaves_like 'deleting keys from redis', 'latest wal location keys for main database' do
            let(:key) { wal_location_key(idempotency_key, 'main') }
            let(:from_value) { wal_locations['main'] }
          end

          it_behaves_like 'deleting keys from redis', 'latest wal location keys for ci database' do
            let(:key) { wal_location_key(idempotency_key, 'ci') }
            let(:from_value) { wal_locations['ci'] }
          end
        end

        context 'when the idempotency key is not part of the job' do
          it_behaves_like 'deleting the duplicate job'

          it 'recalculates the idempotency hash' do
            expect(duplicate_job).to receive(:idempotency_hash).and_call_original

            duplicate_job.delete!
          end
        end

        context 'when the idempotency key is part of the job' do
          let(:idempotency_key) { 'not the same as what we calculate' }
          let(:job) { super().merge('idempotency_key' => idempotency_key) }

          it_behaves_like 'deleting the duplicate job'

          it 'does not recalculate the idempotency hash' do
            expect(duplicate_job).not_to receive(:idempotency_hash)

            duplicate_job.delete!
          end
        end
      end
    end

    describe '#set_deduplicated_flag!' do
      context 'when the job is reschedulable' do
        before do
          allow(duplicate_job).to receive(:reschedulable?) { true }
        end

        it 'sets the key in Redis' do
          duplicate_job.set_deduplicated_flag!

          flag = with_redis { |redis| redis.get(deduplicated_flag_key) }

          expect(flag).to eq(described_class::DEDUPLICATED_FLAG_VALUE.to_s)
        end

        it 'sets, gets and cleans up the deduplicated flag' do
          expect(duplicate_job.should_reschedule?).to eq(false)

          duplicate_job.set_deduplicated_flag!
          expect(duplicate_job.should_reschedule?).to eq(true)

          duplicate_job.delete!
          expect(duplicate_job.should_reschedule?).to eq(false)
        end
      end

      context 'when the job is not reschedulable' do
        before do
          allow(duplicate_job).to receive(:reschedulable?) { false }
        end

        it 'does not set the key in Redis' do
          duplicate_job.set_deduplicated_flag!

          flag = with_redis { |redis| redis.get(deduplicated_flag_key) }

          expect(flag).to be_nil
        end

        it 'does not set the deduplicated flag' do
          expect(duplicate_job.should_reschedule?).to eq(false)

          duplicate_job.set_deduplicated_flag!
          expect(duplicate_job.should_reschedule?).to eq(false)

          duplicate_job.delete!
          expect(duplicate_job.should_reschedule?).to eq(false)
        end
      end
    end

    describe '#duplicate?' do
      it "raises an error if the check wasn't performed" do
        expect { duplicate_job.duplicate? }.to raise_error /Call `#check!` first/
      end

      it 'returns false if the existing jid equals the job jid' do
        duplicate_job.check!

        expect(duplicate_job.duplicate?).to be(false)
      end

      it 'returns false if the existing jid is different from the job jid' do
        set_idempotency_key(idempotency_key, 'a different jid')
        duplicate_job.check!

        expect(duplicate_job.duplicate?).to be(true)
      end
    end

    def existing_wal_location_key(idempotency_key, connection_name)
      "#{idempotency_key}:#{connection_name}:existing_wal_location"
    end

    def wal_location_key(idempotency_key, connection_name)
      "#{idempotency_key}:#{connection_name}:wal_location"
    end

    def set_idempotency_key(key, value = '1')
      with_redis { |r| r.set(key, value) }
    end

    def rpush_to_redis_key(key, wal, offset)
      with_redis { |r| r.rpush(key, [wal, offset]) }
    end

    def read_idempotency_key_with_ttl(key)
      with_redis do |redis|
        redis.pipelined do |p|
          p.get(key)
          p.ttl(key)
        end
      end
    end

    def read_range_from_redis(key)
      with_redis do |redis|
        redis.lrange(key, 0, -1)
      end
    end
  end

  context 'with duplicate_jobs_cookie disabled' do
    before do
      stub_feature_flags(duplicate_jobs_cookie: false)
    end

    context 'with multi-store feature flags turned on' do
      def with_redis(&block)
        Gitlab::Redis::DuplicateJobs.with(&block)
      end

      it 'use Gitlab::Redis::DuplicateJobs.with' do
        expect(Gitlab::Redis::DuplicateJobs).to receive(:with).and_call_original
        expect(Sidekiq).not_to receive(:redis)

        duplicate_job.check!
      end

      it_behaves_like 'with multiple Redis keys'
    end

    context 'when both multi-store feature flags are off' do
      def with_redis(&block)
        Sidekiq.redis(&block)
      end

      before do
        stub_feature_flags(use_primary_and_secondary_stores_for_duplicate_jobs: false)
        stub_feature_flags(use_primary_store_as_default_for_duplicate_jobs: false)
      end

      it 'use Sidekiq.redis' do
        expect(Sidekiq).to receive(:redis).and_call_original
        expect(Gitlab::Redis::DuplicateJobs).not_to receive(:with)

        duplicate_job.check!
      end

      it_behaves_like 'with multiple Redis keys'
    end
  end

  context 'with Redis cookies' do
    let(:cookie_key) do
      "#{idempotency_key}:cookie"
    end

    def with_redis(&block)
      Gitlab::Redis::DuplicateJobs.with(&block)
    end

    describe '#check!' do
      context 'when there was no job in the queue yet' do
        it { expect(duplicate_job.check!).to eq('123') }

        shared_examples 'sets Redis keys with correct TTL' do
          it "adds an idempotency key with correct ttl" do
            expected_cookie = <<~COOKIE
              jid=123
              existing_wal_location:main=#{wal_locations['main']}
              existing_wal_location:ci=#{wal_locations['ci']}
            COOKIE
            expect { duplicate_job.check! }
              .to change { read_idempotency_key_with_ttl(cookie_key) }
                    .from([nil, -2])
                    .to([expected_cookie, be_within(1).of(expected_ttl)])
          end
        end

        context 'when TTL option is not set' do
          let(:expected_ttl) { described_class::DEFAULT_DUPLICATE_KEY_TTL }

          it_behaves_like 'sets Redis keys with correct TTL'
        end

        context 'when TTL option is set' do
          let(:expected_ttl) { 5.minutes }

          before do
            allow(duplicate_job).to receive(:options).and_return({ ttl: expected_ttl })
          end

          it_behaves_like 'sets Redis keys with correct TTL'
        end

        it "adds the idempotency key to the jobs payload" do
          expect { duplicate_job.check! }.to change { job['idempotency_key'] }.from(nil).to(idempotency_key)
        end
      end

      context 'when there was already a job with same arguments in the same queue' do
        before do
          set_idempotency_key(cookie_key, "jid=existing-jid\n")
        end

        it { expect(duplicate_job.check!).to eq('existing-jid') }

        it "does not change the existing key's TTL" do
          expect { duplicate_job.check! }
            .not_to change { read_idempotency_key_with_ttl(cookie_key) }
                  .from(["jid=existing-jid\n", -1])
        end

        it 'sets the existing jid' do
          duplicate_job.check!

          expect(duplicate_job.existing_jid).to eq('existing-jid')
        end
      end
    end

    describe '#update_latest_wal_location!' do
      before do
        allow(Gitlab::Database).to receive(:database_base_models).and_return(
          { main: ::ActiveRecord::Base,
            ci: ::ActiveRecord::Base })

        set_idempotency_key(cookie_key, initial_cookie)

        # read existing_wal_locations
        duplicate_job.check!
      end

      let(:initial_cookie) do
        <<~COOKIE
          jid=foobar
          existing_wal_location:main=0/D525E3A0
          existing_wal_location:ci=AB/12340
        COOKIE
      end

      let(:new_wal) do
        {
          # offset is relative to `existing_wal`
          'main' => { location: '0/D525E3A8', offset: '8' },
          'ci' => { location: 'AB/12345', offset: '5' }
        }
      end

      let(:wal_locations) { new_wal.transform_values { |v| v[:location] } }

      it 'stores a wal location to redis with an offset relative to existing wal location' do
        expected_cookie = initial_cookie + <<~COOKIE
          wal_location:main:#{new_wal['main'][:offset]}=#{new_wal['main'][:location]}
          wal_location:ci:#{new_wal['ci'][:offset]}=#{new_wal['ci'][:location]}
        COOKIE

        expect { duplicate_job.update_latest_wal_location! }
          .to change { read_idempotency_key_with_ttl(cookie_key) }
                .from([initial_cookie, -1])
                .to([expected_cookie, -1])
      end
    end

    describe '#latest_wal_locations' do
      context 'when job was deduplicated and wal locations were already persisted' do
        before do
          cookie = <<~COOKIE
            jid=foobar
            wal_location:main:1=main1
            wal_location:ci:2:=ci2
            wal_location:main:5=main5
            wal_location:ci:6=ci6
            wal_location:main:3=main3
            wal_location:ci:4=ci4
          COOKIE
          set_idempotency_key(cookie_key, cookie)
        end

        it { expect(duplicate_job.latest_wal_locations).to eq({ 'main' => 'main5', 'ci' => 'ci6' }) }
      end

      context 'when job is not deduplication and wal locations were not persisted' do
        it { expect(duplicate_job.latest_wal_locations).to be_empty }
      end
    end

    describe '#delete!' do
      context "when we didn't track the definition" do
        it { expect { duplicate_job.delete! }.not_to raise_error }
      end

      context 'when the key exists in redis' do
        before do
          set_idempotency_key(cookie_key, "jid=existing-jid\n")
        end

        shared_examples 'deleting the duplicate job' do
          shared_examples 'deleting keys from redis' do |key_name|
            it "removes the #{key_name} from redis" do
              expect { duplicate_job.delete! }
                .to change { read_idempotency_key_with_ttl(key) }
                      .from([from_value, -1])
                      .to([nil, -2])
            end
          end

          shared_examples 'does not delete key from redis' do |key_name|
            it "does not remove the #{key_name} from redis" do
              expect { duplicate_job.delete! }
                .to not_change { read_idempotency_key_with_ttl(key) }
                      .from([from_value, -1])
            end
          end

          it_behaves_like 'deleting keys from redis', 'cookie key' do
            let(:key) { cookie_key }
            let(:from_value) { "jid=existing-jid\n" }
          end
        end

        context 'when the idempotency key is not part of the job' do
          it_behaves_like 'deleting the duplicate job'

          it 'recalculates the idempotency hash' do
            expect(duplicate_job).to receive(:idempotency_hash).and_call_original

            duplicate_job.delete!
          end
        end

        context 'when the idempotency key is part of the job' do
          let(:idempotency_key) { 'not the same as what we calculate' }
          let(:job) { super().merge('idempotency_key' => idempotency_key) }

          it_behaves_like 'deleting the duplicate job'

          it 'does not recalculate the idempotency hash' do
            expect(duplicate_job).not_to receive(:idempotency_hash)

            duplicate_job.delete!
          end
        end
      end
    end

    describe '#set_deduplicated_flag!' do
      context 'when the job is reschedulable' do
        before do
          duplicate_job.check! # ensure cookie exists
          allow(duplicate_job).to receive(:reschedulable?) { true }
        end

        it 'sets the key in Redis' do
          duplicate_job.set_deduplicated_flag!

          cookie = with_redis { |redis| redis.get(cookie_key) }
          expect(cookie).to include("\ndeduplicated=1\n")
        end

        it 'sets, gets and cleans up the deduplicated flag' do
          expect(duplicate_job.should_reschedule?).to eq(false)

          duplicate_job.set_deduplicated_flag!
          expect(duplicate_job.should_reschedule?).to eq(true)

          duplicate_job.delete!
          expect(duplicate_job.should_reschedule?).to eq(false)
        end
      end

      context 'when the job is not reschedulable' do
        before do
          allow(duplicate_job).to receive(:reschedulable?) { false }
        end

        it 'does not set the key in Redis' do
          duplicate_job.check!
          duplicate_job.set_deduplicated_flag!

          cookie = with_redis { |redis| redis.get(cookie_key) }

          expect(cookie).not_to include('deduplicated=')
        end

        it 'does not set the deduplicated flag' do
          expect(duplicate_job.should_reschedule?).to eq(false)

          duplicate_job.set_deduplicated_flag!
          expect(duplicate_job.should_reschedule?).to eq(false)

          duplicate_job.delete!
          expect(duplicate_job.should_reschedule?).to eq(false)
        end
      end
    end

    describe '#duplicate?' do
      it "raises an error if the check wasn't performed" do
        expect { duplicate_job.duplicate? }.to raise_error /Call `#check!` first/
      end

      it 'returns false if the existing jid equals the job jid' do
        duplicate_job.check!

        expect(duplicate_job.duplicate?).to be(false)
      end

      it 'returns true if the existing jid is different from the job jid' do
        set_idempotency_key(cookie_key, "jid=a different jid\n")
        duplicate_job.check!

        expect(duplicate_job.duplicate?).to be(true)
      end
    end

    def set_idempotency_key(key, value)
      with_redis { |r| r.set(key, value) }
    end

    def read_idempotency_key_with_ttl(key)
      with_redis do |redis|
        redis.pipelined do |p|
          p.get(key)
          p.ttl(key)
        end
      end
    end
  end

  describe '#scheduled?' do
    it 'returns false for non-scheduled jobs' do
      expect(duplicate_job.scheduled?).to be(false)
    end

    context 'scheduled jobs' do
      let(:job) do
        { 'class' => 'AuthorizedProjectsWorker',
          'args' => [1],
          'jid' => '123',
          'at' => 42 }
      end

      it 'returns true' do
        expect(duplicate_job.scheduled?).to be(true)
      end
    end
  end

  describe '#reschedule' do
    it 'reschedules the current job' do
      fake_logger = instance_double(Gitlab::SidekiqLogging::DeduplicationLogger)
      expect(Gitlab::SidekiqLogging::DeduplicationLogger).to receive(:instance).and_return(fake_logger)
      expect(fake_logger).to receive(:rescheduled_log).with(a_hash_including({ 'jid' => '123' }))
      expect(AuthorizedProjectsWorker).to receive(:perform_async).with(1).once

      duplicate_job.reschedule
    end
  end

  describe '#should_reschedule?' do
    subject { duplicate_job.should_reschedule? }

    context 'when the job is reschedulable' do
      before do
        allow(duplicate_job).to receive(:reschedulable?) { true }
      end

      it { is_expected.to eq(false) }

      context 'with deduplicated flag' do
        before do
          duplicate_job.check! # ensure cookie exists
          duplicate_job.set_deduplicated_flag!
        end

        it { is_expected.to eq(true) }
      end
    end

    context 'when the job is not reschedulable' do
      before do
        allow(duplicate_job).to receive(:reschedulable?) { false }
      end

      it { is_expected.to eq(false) }

      context 'with deduplicated flag' do
        before do
          duplicate_job.check! # ensure cookie exists
          duplicate_job.set_deduplicated_flag!
        end

        it { is_expected.to eq(false) }
      end
    end
  end

  describe '#scheduled_at' do
    let(:scheduled_at) { 42 }
    let(:job) do
      { 'class' => 'AuthorizedProjectsWorker',
        'args' => [1],
        'jid' => '123',
        'at' => scheduled_at }
    end

    it 'returns when the job is scheduled at' do
      expect(duplicate_job.scheduled_at).to eq(scheduled_at)
    end
  end

  describe '#options' do
    let(:worker_options) { { foo: true } }

    it 'returns worker options' do
      allow(AuthorizedProjectsWorker).to(
        receive(:get_deduplication_options).and_return(worker_options))

      expect(duplicate_job.options).to eq(worker_options)
    end
  end

  describe '#idempotent?' do
    context 'when worker class does not exist' do
      let(:job) { { 'class' => '' } }

      it 'returns false' do
        expect(duplicate_job).not_to be_idempotent
      end
    end

    context 'when worker class does not respond to #idempotent?' do
      before do
        stub_const('AuthorizedProjectsWorker', Class.new)
      end

      it 'returns false' do
        expect(duplicate_job).not_to be_idempotent
      end
    end

    context 'when worker class is not idempotent' do
      before do
        allow(AuthorizedProjectsWorker).to receive(:idempotent?).and_return(false)
      end

      it 'returns false' do
        expect(duplicate_job).not_to be_idempotent
      end
    end

    context 'when worker class is idempotent' do
      before do
        allow(AuthorizedProjectsWorker).to receive(:idempotent?).and_return(true)
      end

      it 'returns true' do
        expect(duplicate_job).to be_idempotent
      end
    end

    context 'when worker class is utilizing load balancing capabilities' do
      before do
        allow(AuthorizedProjectsWorker).to receive(:utilizes_load_balancing_capabilities?).and_return(true)
      end

      it 'returns true' do
        expect(duplicate_job).to be_idempotent
      end
    end
  end
end