From c0fd57370ece59f956c1dcf2ea9d0cee67419e60 Mon Sep 17 00:00:00 2001
From: Michael Trainor <mtrainor@gitlab.com>
Date: Wed, 24 Apr 2024 22:33:35 +0000
Subject: [PATCH] Ensure daily limit can't be zero

The daily limit is currently not validated, so it
can be any value within the underlying datatype for
the column. This can be a number larger than 1440.

When a number is greater than 1440 is configured for
the daily limit, the integer provided in the natural
expression to Fugit contains zero. This results in a
ZeroDivisionError from Fugit.

This commit ensures that the expression provided to
Fugit can't contain a zero. If the result of the
expression is less than 1, it will be treated like
a 1, eg 'every 1 minutes'.
---
 .../ci/pipeline_schedules/calculate_next_run_service.rb   | 8 +++++++-
 .../pipeline_schedules/calculate_next_run_service_spec.rb | 2 ++
 2 files changed, 9 insertions(+), 1 deletion(-)

diff --git a/app/services/ci/pipeline_schedules/calculate_next_run_service.rb b/app/services/ci/pipeline_schedules/calculate_next_run_service.rb
index a1b9ab5f82ed9..064b004a5b822 100644
--- a/app/services/ci/pipeline_schedules/calculate_next_run_service.rb
+++ b/app/services/ci/pipeline_schedules/calculate_next_run_service.rb
@@ -47,7 +47,13 @@ def plan_cron
 
           every_x_minutes = (1.day.in_minutes / daily_limit).to_i
 
-          Gitlab::Ci::CronParser.parse_natural("every #{every_x_minutes} minutes", Time.zone.name)
+          begin
+            Gitlab::Ci::CronParser.parse_natural("every #{every_x_minutes} minutes", Time.zone.name)
+          rescue ZeroDivisionError
+            # Fugit returns ZeroDivision Error if provided a number
+            # less than 1 in the expression.
+            nil
+          end
         end
       end
     end
diff --git a/spec/services/ci/pipeline_schedules/calculate_next_run_service_spec.rb b/spec/services/ci/pipeline_schedules/calculate_next_run_service_spec.rb
index 182c5bebbc1fa..b3bdfdee95622 100644
--- a/spec/services/ci/pipeline_schedules/calculate_next_run_service_spec.rb
+++ b/spec/services/ci/pipeline_schedules/calculate_next_run_service_spec.rb
@@ -30,6 +30,8 @@
         # 1.day / 2.hours => 12 times a day and it is invalid because there is a minimum for plan limits.
         # See: https://docs.gitlab.com/ee/administration/instance_limits.html#limit-the-number-of-pipelines-created-by-a-pipeline-schedule-per-day
         '*/5 * * * *' | '0 * * * *'   | 1.day / 2.hours | Time.zone.local(2021, 5, 27, 11, 0) | Time.zone.local(2021, 5, 27, 12, 5)
+        '*/5 * * * *' | '0 * * * *'   | 2000            | Time.zone.local(2021, 5, 27, 11, 0) | Time.zone.local(2021, 5, 27, 12, 5)
+        '*/5 * * * *' | '0 * * * *'   | -24             | Time.zone.local(2021, 5, 27, 11, 0) | Time.zone.local(2021, 5, 27, 12, 5)
       end
 
       with_them do
-- 
GitLab