solidusio/solidus

PromotionCodeBatch fails generating million codes

DanielePalombo opened this issue · 0 comments

When a new promotion with 2.5m new promo codes was created, it just generated about 250k promo codes and then stopped.

The PromotionBatch screen this error: Errored: #<ActiveRecord::RecordInvalid: Validation failed: Value has already been taken>
It seems that when the PromotionCode creation fails, it raises an exception that stops the worker.

while created_codes < number_of_codes
max_codes_to_generate = [batch_size, number_of_codes - created_codes].min
new_codes = Array.new(max_codes_to_generate) { generate_random_code }.uniq
codes_for_current_batch = get_unique_codes(new_codes)
codes_for_current_batch.each do |value|
Spree::PromotionCode.create!(
value: value,
promotion: promotion,
promotion_code_batch: promotion_code_batch
)
end
created_codes += codes_for_current_batch.size
end

I would like to propose changing this behavior and rescuing the exception inside the loop, so we can skip the failed code creation and continue to the next one.

Solidus Version:
All solidus version

To Reproduce
Create a promotion with 2.5M code

Current behavior
The Spree::PromotionCode::BatchBuilder worker fails with ActiveRecord::RecordInvalid: Validation failed: Value has already been taken without completing the promotion codes generation.

Expected behavior
The Spree::PromotionCode::BatchBuilder worker generates all the PromotionCodes.