-
Notifications
You must be signed in to change notification settings - Fork 171
MAGE-1109: Add Batching Optimizer feature #1797
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
damcou
wants to merge
18
commits into
release/3.17.0-dev
Choose a base branch
from
feat/MAGE-1109-batching-optimizer
base: release/3.17.0-dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+545
−0
Open
Changes from 13 commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
b25428a
MAGE-1109: Add Batching Optimizer CLI
damcou 013ec7b
MAGE-1109: Codacy bullying
damcou 678c7ee
MAGE-1109: review feedback + prompt
damcou 01e64e4
MAGE-1109: fix value save
damcou eed8bd9
MAGE-1109: added batching scan CLI command
damcou 6df50cd
MAGE-1109: move trait in right directory
damcou 8df9483
MAGE-1109: add large sample size option
damcou 9d80d01
MAGE-1109: remove old class
damcou f8fc6d2
MAGE-1109: remove unnecessary trait
damcou 2a5ab0a
MAGE-1109: address feedback
damcou 4097119
MAGE-1109: added warning
damcou e37e13e
Merge branch 'release/3.17.0-dev' into feat/MAGE-1109-batching-optimizer
cammonro 4d06c8c
MAGE-1109 Add sample size as configurable option
cammonro 31d4cb3
MAGE-1109: added margin and sample size options
damcou 5688e3c
MAGE-1109: address feedback
damcou d064761
MAGE-1109: added math helper
damcou 6a8d1e5
MAGE-1109: added helper tests
damcou 97f7f54
MAGE-1109: rework safety margin
damcou File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,393 @@ | ||
<?php | ||
|
||
namespace Algolia\AlgoliaSearch\Console\Command; | ||
|
||
use Algolia\AlgoliaSearch\Exception\DiagnosticsException; | ||
use Algolia\AlgoliaSearch\Exceptions\AlgoliaException; | ||
use Algolia\AlgoliaSearch\Helper\ConfigHelper; | ||
use Algolia\AlgoliaSearch\Helper\Entity\ProductHelper; | ||
use Algolia\AlgoliaSearch\Service\AlgoliaConnector; | ||
use Algolia\AlgoliaSearch\Service\Product\IndexOptionsBuilder; | ||
use Algolia\AlgoliaSearch\Service\Product\RecordBuilder; | ||
use Algolia\AlgoliaSearch\Service\StoreNameFetcher; | ||
use Magento\Catalog\Model\ResourceModel\Product\Collection; | ||
use Magento\Framework\App\Config\Storage\WriterInterface; | ||
use Magento\Framework\App\State; | ||
use Magento\Framework\Console\Cli; | ||
use Magento\Framework\Exception\LocalizedException; | ||
use Magento\Framework\Exception\NoSuchEntityException; | ||
use Magento\Store\Model\StoreManagerInterface; | ||
use Symfony\Component\Console\Input\InputInterface; | ||
use Symfony\Component\Console\Input\InputOption; | ||
use Symfony\Component\Console\Output\OutputInterface; | ||
|
||
class BatchingOptimizeCommand extends AbstractStoreCommand | ||
{ | ||
/** | ||
* Recommended Max batch size | ||
* https://www.algolia.com/doc/guides/sending-and-managing-data/send-and-update-your-data/how-to/sending-records-in-batches/ | ||
*/ | ||
const MAX_BATCH_SIZE_IN_BYTES = 10_000_000; //10MB | ||
|
||
/** | ||
* Arbitrary default margin to ensure not to exceed recommended batch size | ||
*/ | ||
const DEFAULT_MARGIN = 25; | ||
|
||
/** | ||
* Arbitrary increased margin to ensure not to exceed recommended batch size when catalog is a mix between complex and other product types | ||
* (i.e. with a lot of record sizes variations) | ||
*/ | ||
const INCREASED_MARGIN = 50; | ||
|
||
const DEFAULT_SAMPLE_SIZE = 20; | ||
|
||
protected const OPTION_SAMPLE_SIZE = 'sample-size'; | ||
protected const OPTION_SAMPLE_SIZE_SHORTCUT = 's'; | ||
|
||
const PRODUCTS_SIMPLE_TYPES = [ | ||
'simple', | ||
'downloadable', | ||
'virtual', | ||
'giftcard' | ||
]; | ||
|
||
const PRODUCTS_COMPLEX_TYPES = [ | ||
'configurable', | ||
'grouped', | ||
'bundle' | ||
]; | ||
|
||
/** | ||
* @var array|null | ||
*/ | ||
protected ?array $storeCounts = []; | ||
|
||
public function __construct( | ||
protected AlgoliaConnector $algoliaConnector, | ||
protected State $state, | ||
protected StoreNameFetcher $storeNameFetcher, | ||
protected StoreManagerInterface $storeManager, | ||
protected IndexOptionsBuilder $indexOptionsBuilder, | ||
protected ProductHelper $productHelper, | ||
protected ConfigHelper $configHelper, | ||
protected RecordBuilder $recordBuilder, | ||
protected WriterInterface $configWriter, | ||
?string $name = null | ||
) { | ||
parent::__construct($state, $storeNameFetcher, $name); | ||
} | ||
|
||
protected function getCommandPrefix(): string | ||
{ | ||
return parent::getCommandPrefix() . 'batching:'; | ||
} | ||
|
||
protected function getCommandName(): string | ||
{ | ||
return 'optimize'; | ||
} | ||
|
||
protected function getCommandDescription(): string | ||
{ | ||
return "Scans some products to determine the average product record size."; | ||
} | ||
|
||
protected function getStoreArgumentDescription(): string | ||
{ | ||
return 'ID(s) for store(s) to optimize (optional), if no store is specified, all stores will be taken into account.'; | ||
} | ||
|
||
protected function getAdditionalDefinition(): array | ||
{ | ||
return [ | ||
new InputOption( | ||
self::OPTION_SAMPLE_SIZE, | ||
'-' . self::OPTION_SAMPLE_SIZE_SHORTCUT, | ||
InputOption::VALUE_REQUIRED, | ||
'Sample size (number of products) - DEFAULT: ' . static::DEFAULT_SAMPLE_SIZE, | ||
) | ||
]; | ||
} | ||
|
||
/** | ||
* @throws NoSuchEntityException|LocalizedException | ||
*/ | ||
protected function execute(InputInterface $input, OutputInterface $output): int | ||
{ | ||
$this->input = $input; | ||
$this->output = $output; | ||
$this->setAreaCode(); | ||
|
||
$storeIds = $this->getStoreIds($input); | ||
|
||
try { | ||
$this->scanProductRecords($storeIds); | ||
} catch (\Exception $e) { | ||
$this->output->writeln('<error>' . $e->getMessage() . '</error>'); | ||
return CLI::RETURN_FAILURE; | ||
} | ||
|
||
return Cli::RETURN_SUCCESS; | ||
} | ||
|
||
/** | ||
* @param array $storeIds | ||
* @return void | ||
* @throws AlgoliaException | ||
* @throws DiagnosticsException | ||
* @throws LocalizedException | ||
* @throws NoSuchEntityException | ||
*/ | ||
protected function scanProductRecords(array $storeIds = []): void | ||
{ | ||
if (count($storeIds)) { | ||
foreach ($storeIds as $storeId) { | ||
$this->scanProductRecordsForStore($storeId); | ||
} | ||
} else { | ||
$this->scanProductRecordsForAllStores(); | ||
} | ||
} | ||
|
||
/** | ||
* @return void | ||
* @throws AlgoliaException | ||
* @throws DiagnosticsException | ||
* @throws LocalizedException | ||
* @throws NoSuchEntityException | ||
*/ | ||
protected function scanProductRecordsForAllStores(): void | ||
{ | ||
$storeIds = array_keys($this->storeManager->getStores()); | ||
|
||
foreach ($storeIds as $storeId) { | ||
$this->scanProductRecordsForStore($storeId); | ||
} | ||
} | ||
|
||
/** | ||
* @param int $storeId | ||
* @return void | ||
* @throws AlgoliaException | ||
* @throws DiagnosticsException | ||
* @throws LocalizedException | ||
* @throws NoSuchEntityException | ||
*/ | ||
protected function scanProductRecordsForStore(int $storeId): void | ||
{ | ||
$storeName = $this->storeNameFetcher->getStoreName($storeId); | ||
|
||
if (!$this->configHelper->isIndexingEnabled($storeId)) { | ||
$this->output->writeln('<info>Indexing is disabled for store ' . $storeName . '</info>'); | ||
return; | ||
} | ||
|
||
if (!isset($this->storeCounts[$storeId])) { | ||
$this->setStoreCounts($storeId); | ||
damcou marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
$this->output->writeln(' '); | ||
$this->output->writeln('<info> ====== Products for store ' . $storeName . ' ====== </info>'); | ||
$this->output->writeln('<comment>Simple Products</comment>: ' . $this->storeCounts[$storeId]['simple'] . ' (' . round($this->storeCounts[$storeId]['simple_percentage'], 2) . '% of total)'); | ||
$this->output->writeln('<comment>Complex Products</comment>: ' . $this->storeCounts[$storeId]['complex'] . ' (' . round($this->storeCounts[$storeId]['complex_percentage'], 2) . '% of total)'); | ||
|
||
$this->output->writeln('<info> ============ </info>'); | ||
$this->output->writeln('<comment>Total</comment>: ' . $this->storeCounts[$storeId]['total'] . ' products'); | ||
|
||
$this->output->writeln('<info> ============ </info>'); | ||
|
||
$sample = $this->storeCounts[$storeId]['sample']; | ||
|
||
if (count($sample) > 0) { | ||
$this->output->writeln('<comment>Sample (' . count($sample) . ' products):</comment>'); | ||
foreach ($sample as $sku => $size) { | ||
$this->output->writeln(' - ' . $size . 'B (sku: ' . $sku . ')'); | ||
} | ||
} | ||
|
||
$this->output->writeln('<info> ============ </info>'); | ||
$sizeAverage = $this->getSizeAverage($sample); | ||
$this->output->writeln('<comment>Min record size</comment> : ' . $this->storeCounts[$storeId]['sample_min'] . 'B'); | ||
$this->output->writeln('<comment>Max record size</comment> : ' . $this->storeCounts[$storeId]['sample_max'] . 'B'); | ||
$this->output->writeln('<comment>Average record size</comment> : ' . $sizeAverage . 'B'); | ||
|
||
$estimatedBatchCount = $this->getEstimatedMaxBatchCount($sizeAverage); | ||
$this->output->writeln('<comment>Estimated Max batch count</comment> : ' . $estimatedBatchCount . ' records'); | ||
|
||
$standardDeviation = $this->getStandardDeviation($sample, $sizeAverage); | ||
$this->output->writeln('<comment>Standard Deviation</comment> : ' . $standardDeviation); | ||
|
||
$recommendedBatchCountLow = $this->getRecommendedBatchCount($sizeAverage, $standardDeviation, self::INCREASED_MARGIN); | ||
damcou marked this conversation as resolved.
Show resolved
Hide resolved
|
||
$recommendedBatchCountHigh = $this->getRecommendedBatchCount($sizeAverage, $standardDeviation); | ||
$this->output->writeln('<info> ============ </info>'); | ||
$this->output->writeln('<info>Recommended batch count (low)</info> : ' . $recommendedBatchCountLow . ' records'); | ||
$this->output->writeln('<info>Recommended batch count (high)</info> : ' . $recommendedBatchCountHigh . ' records'); | ||
$this->output->writeln(' '); | ||
$this->output->writeln('<fg=red>Important:</fg=red> Those numbers are estimates only. Indexing activity should be monitored after making changes to ensure batches are not exceeding the recommended size of 10 MB.'); | ||
$this->output->writeln('<info> ============ </info>'); | ||
$this->output->writeln( | ||
'This will override your "Maximum number of records processed per indexing job" configuration to <info>' . $recommendedBatchCountLow . '</info> for store "' . $storeName . '".'); | ||
$this->output->writeln(' '); | ||
|
||
if ($this->confirmOperation()) { | ||
$this->configWriter->save( | ||
ConfigHelper::NUMBER_OF_ELEMENT_BY_PAGE, | ||
$recommendedBatchCountLow, | ||
'stores', | ||
$storeId | ||
); | ||
} | ||
} | ||
|
||
/** | ||
* @param int $storeId | ||
* @return void | ||
* @throws AlgoliaException | ||
* @throws DiagnosticsException | ||
* @throws LocalizedException | ||
* @throws NoSuchEntityException | ||
*/ | ||
protected function setStoreCounts(int $storeId): void | ||
{ | ||
$simpleProducts = $this->getProductsCollectionForStore($storeId, self::PRODUCTS_SIMPLE_TYPES); | ||
$complexProducts = $this->getProductsCollectionForStore($storeId, self::PRODUCTS_COMPLEX_TYPES); | ||
|
||
$this->storeCounts[$storeId] = [ | ||
'simple' => $simpleProducts->count(), | ||
'complex' => $complexProducts->count() | ||
]; | ||
|
||
$this->storeCounts[$storeId]['total'] = | ||
(int) $this->storeCounts[$storeId]['simple'] + (int) $this->storeCounts[$storeId]['complex']; | ||
|
||
$this->storeCounts[$storeId]['simple_percentage'] = $this->storeCounts[$storeId]['total'] > 0 ? | ||
($this->storeCounts[$storeId]['simple'] * 100) / $this->storeCounts[$storeId]['total'] : | ||
0; | ||
|
||
$this->storeCounts[$storeId]['complex_percentage'] = $this->storeCounts[$storeId]['total'] > 0 ? | ||
($this->storeCounts[$storeId]['complex'] * 100) / $this->storeCounts[$storeId]['total']: | ||
0; | ||
|
||
|
||
$sampleSize = $this->input->getOption(self::OPTION_SAMPLE_SIZE) ?? self::DEFAULT_SAMPLE_SIZE; | ||
$simpleSampleSize = (int)round($sampleSize * ($this->storeCounts[$storeId]['simple_percentage'] / 100)); | ||
$complexSampleSize = (int)round($sampleSize * ($this->storeCounts[$storeId]['complex_percentage'] / 100)); | ||
|
||
$this->storeCounts[$storeId]['simple_sample_size'] = $simpleSampleSize; | ||
$this->storeCounts[$storeId]['complex_sample_size'] = $complexSampleSize; | ||
|
||
$this->storeCounts[$storeId]['sample'] = array_merge( | ||
$this->getProductsSizes($simpleProducts, $simpleSampleSize), | ||
$this->getProductsSizes($complexProducts, $complexSampleSize) | ||
); | ||
damcou marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
$this->storeCounts[$storeId]['sample_min'] = min($this->storeCounts[$storeId]['sample']); | ||
$this->storeCounts[$storeId]['sample_max'] = max($this->storeCounts[$storeId]['sample']); | ||
} | ||
|
||
/** | ||
* @param int $storeId | ||
* @param array $productTypes | ||
* @return Collection | ||
*/ | ||
protected function getProductsCollectionForStore(int $storeId, array $productTypes = []): Collection | ||
{ | ||
$onlyVisible = !$this->configHelper->includeNonVisibleProductsInIndex(); | ||
$collection = $this->productHelper->getProductCollectionQuery($storeId, null, $onlyVisible); | ||
if (count($productTypes) > 0) { | ||
$collection->addAttributeToFilter('type_id', ['in' => $productTypes]); | ||
} | ||
|
||
// Randomize the results to get a more "diverse" sample | ||
$collection->getSelect()->orderRand(); | ||
|
||
return $collection; | ||
} | ||
|
||
/** | ||
* @param Collection $products | ||
* @param int $sampleSize | ||
* @return array | ||
* @throws LocalizedException | ||
* @throws NoSuchEntityException | ||
* @throws DiagnosticsException | ||
* @throws AlgoliaException | ||
*/ | ||
protected function getProductsSizes(Collection $products, int $sampleSize): array | ||
{ | ||
$stats = []; | ||
$limit = 0; | ||
|
||
foreach ($products as $product) { | ||
if ($limit >= $sampleSize) { | ||
break; | ||
} | ||
|
||
$serializedRecord = json_encode($this->recordBuilder->buildRecord($product)); | ||
|
||
if (function_exists('mb_strlen')) { | ||
$size = mb_strlen($serializedRecord, '8bit'); | ||
} else { | ||
$size = strlen($serializedRecord); | ||
} | ||
|
||
$stats[$product->getSku()] = $size; | ||
$limit++; | ||
} | ||
|
||
return $stats; | ||
} | ||
|
||
/** | ||
* @param array $sizes | ||
* @return int | ||
*/ | ||
protected function getSizeAverage(array $sizes): int | ||
{ | ||
if (count($sizes) <= 1) { | ||
damcou marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return 0.0; | ||
} | ||
|
||
return (int) round(array_sum(array_values($sizes)) / count($sizes)); | ||
damcou marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
/** | ||
* @param int $averageSize | ||
* @return int | ||
*/ | ||
protected function getEstimatedMaxBatchCount(int $averageSize): int | ||
{ | ||
return (int) round(self::MAX_BATCH_SIZE_IN_BYTES / $averageSize); | ||
} | ||
|
||
/** | ||
* @param array $sizes | ||
* @param int $averageSize | ||
* @return float | ||
*/ | ||
protected function getStandardDeviation(array $sizes, int $averageSize): float | ||
{ | ||
damcou marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if (count($sizes) <= 1) { | ||
return 0.0; | ||
} | ||
|
||
$sum = 0; | ||
foreach ($sizes as $size) { | ||
$sum += pow($size - $averageSize, 2); | ||
} | ||
|
||
return round(sqrt($sum / (count($sizes) - 1)), 2); | ||
} | ||
|
||
/** | ||
* @param int $averageSize | ||
* @param float $standardDeviation | ||
* @param int $margin | ||
* @return int | ||
*/ | ||
protected function getRecommendedBatchCount(int $averageSize, float $standardDeviation, int $margin = self::DEFAULT_MARGIN): int | ||
{ | ||
return (int) (self::MAX_BATCH_SIZE_IN_BYTES / ($averageSize + ($margin/100) * $standardDeviation)); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.