-
Notifications
You must be signed in to change notification settings - Fork 136
[Product AI] Make requests in parallel when saving the product #12770
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
Merged
JorgeMucientes
merged 5 commits into
trunk
from
issue/12664-ai-product-parallel-requests
Oct 16, 2024
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
c99a54c
Add a test for confirming that local image is not re-uploaded on retries
hichamboushaba 795e358
Move the upload image logic to the save product usecase
hichamboushaba cc6a050
Refactor logic to allow keeping track of the uploaded image
hichamboushaba cec2abb
Update logic of saving to handle the preparation requests in parallel
hichamboushaba efb4286
Merge branch 'trunk' into issue/12664-ai-product-parallel-requests
hichamboushaba 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
120 changes: 82 additions & 38 deletions
120
WooCommerce/src/main/kotlin/com/woocommerce/android/ui/products/ai/SaveAiGeneratedProduct.kt
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 |
|---|---|---|
| @@ -1,70 +1,114 @@ | ||
| package com.woocommerce.android.ui.products.ai | ||
|
|
||
| import com.woocommerce.android.model.Image | ||
| import com.woocommerce.android.model.Product | ||
| import com.woocommerce.android.model.ProductCategory | ||
| import com.woocommerce.android.model.ProductTag | ||
| import com.woocommerce.android.ui.products.ProductStatus | ||
| import com.woocommerce.android.ui.products.ai.preview.UploadImage | ||
| import com.woocommerce.android.ui.products.categories.ProductCategoriesRepository | ||
| import com.woocommerce.android.ui.products.details.ProductDetailRepository | ||
| import com.woocommerce.android.ui.products.tags.ProductTagsRepository | ||
| import com.woocommerce.android.util.WooLog | ||
| import kotlinx.coroutines.CoroutineScope | ||
| import kotlinx.coroutines.async | ||
| import kotlinx.coroutines.coroutineScope | ||
| import javax.inject.Inject | ||
|
|
||
| class SaveAiGeneratedProduct @Inject constructor( | ||
| private val productCategoriesRepository: ProductCategoriesRepository, | ||
| private val productTagsRepository: ProductTagsRepository, | ||
| private val productDetailRepository: ProductDetailRepository | ||
| private val productDetailRepository: ProductDetailRepository, | ||
| private val uploadImage: UploadImage | ||
| ) { | ||
| @Suppress("ReturnCount") | ||
| suspend operator fun invoke( | ||
| product: Product, | ||
| selectedImage: Product.Image? | ||
| ): Result<Long> { | ||
| // Create missing categories | ||
| selectedImage: Image? | ||
| ): AiProductSaveResult = coroutineScope { | ||
| // Start uploading the selected image | ||
| val imageTask = selectedImage?.let { selectedImage -> startUploadingImage(selectedImage) } | ||
|
|
||
| val missingCategories = product.categories.filter { it.remoteCategoryId == 0L } | ||
| val createdCategories = missingCategories | ||
| .takeIf { it.isNotEmpty() }?.let { productCategories -> | ||
| WooLog.d( | ||
| tag = WooLog.T.PRODUCTS, | ||
| message = "Create the missing product categories ${productCategories.map { it.name }}" | ||
| ) | ||
| productCategoriesRepository.addProductCategories(productCategories) | ||
| }?.fold( | ||
| onSuccess = { it }, | ||
| onFailure = { | ||
| WooLog.e(WooLog.T.PRODUCTS, "Failed to add product categories", it) | ||
| return Result.failure(it) | ||
| } | ||
| ) | ||
| // Start create missing categories | ||
| val categoriesTask = missingCategories | ||
| .takeIf { it.isNotEmpty() } | ||
| ?.let { productCategories -> startCreatingCategories(productCategories) } | ||
|
|
||
| // Create missing tags | ||
| // Start Create missing tags | ||
| val missingTags = product.tags.filter { it.remoteTagId == 0L } | ||
| val createdTags = missingTags | ||
| .takeIf { it.isNotEmpty() }?.let { productTags -> | ||
| WooLog.d( | ||
| tag = WooLog.T.PRODUCTS, | ||
| message = "Create the missing product tags ${productTags.map { it.name }}" | ||
| ) | ||
| productTagsRepository.addProductTags(productTags.map { it.name }) | ||
| }?.fold( | ||
| onSuccess = { it }, | ||
| onFailure = { | ||
| WooLog.e(WooLog.T.PRODUCTS, "Failed to add product tags", it) | ||
| return Result.failure(it) | ||
| } | ||
| ) | ||
| val tagsTask = missingTags | ||
| .takeIf { it.isNotEmpty() } | ||
| ?.let { productTags -> startCreatingTags(productTags) } | ||
|
|
||
| // Wait for the image to be uploaded | ||
| val image = imageTask?.await()?.getOrElse { | ||
| return@coroutineScope AiProductSaveResult.Failure.UploadImageFailure | ||
| } | ||
|
|
||
| // Wait for the created categories and tags | ||
| val createdCategories = categoriesTask?.await()?.getOrElse { | ||
| return@coroutineScope AiProductSaveResult.Failure.Generic(image?.asWPMediaLibraryImage()) | ||
| } | ||
| val createdTags = tagsTask?.await()?.getOrElse { | ||
| return@coroutineScope AiProductSaveResult.Failure.Generic(image?.asWPMediaLibraryImage()) | ||
| } | ||
|
|
||
| val updatedProduct = product.copy( | ||
| categories = product.categories - missingCategories.toSet() + createdCategories.orEmpty(), | ||
| tags = product.tags - missingTags.toSet() + createdTags.orEmpty(), | ||
| images = listOfNotNull(selectedImage), | ||
| images = listOfNotNull(image), | ||
| status = ProductStatus.DRAFT | ||
| ) | ||
|
|
||
| return productDetailRepository.addProduct(updatedProduct).let { (success, productId) -> | ||
| productDetailRepository.addProduct(updatedProduct).let { (success, productId) -> | ||
| if (success) { | ||
| Result.success(productId) | ||
| WooLog.d( | ||
| tag = WooLog.T.PRODUCTS, | ||
| message = "Successfully saved the AI generated product as draft with id $productId" | ||
| ) | ||
| AiProductSaveResult.Success(productId) | ||
| } else { | ||
| Result.failure(Exception("Failed to save the AI generated product")) | ||
| WooLog.e(WooLog.T.PRODUCTS, "Failed to save the AI generated product as draft") | ||
| AiProductSaveResult.Failure.Generic(image?.asWPMediaLibraryImage()) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private fun CoroutineScope.startUploadingImage(image: Image) = async { | ||
| uploadImage(image).onFailure { | ||
| WooLog.e(WooLog.T.PRODUCTS, "Failed to upload the selected image", it) | ||
| } | ||
| } | ||
|
|
||
| private fun CoroutineScope.startCreatingCategories(categories: List<ProductCategory>) = async { | ||
| WooLog.d( | ||
| tag = WooLog.T.PRODUCTS, | ||
| message = "Create the missing product categories ${categories.map { it.name }}" | ||
| ) | ||
| productCategoriesRepository.addProductCategories(categories) | ||
| .onFailure { | ||
| WooLog.e(WooLog.T.PRODUCTS, "Failed to add product categories", it) | ||
| } | ||
| } | ||
|
|
||
| private fun CoroutineScope.startCreatingTags(tags: List<ProductTag>) = async { | ||
| WooLog.d( | ||
| tag = WooLog.T.PRODUCTS, | ||
| message = "Create the missing product tags ${tags.map { it.name }}" | ||
| ) | ||
| productTagsRepository.addProductTags(tags.map { it.name }) | ||
| .onFailure { | ||
| WooLog.e(WooLog.T.PRODUCTS, "Failed to add product tags", it) | ||
| } | ||
| } | ||
|
|
||
| private fun Product.Image.asWPMediaLibraryImage() = Image.WPMediaLibraryImage(this) | ||
| } | ||
|
|
||
| sealed interface AiProductSaveResult { | ||
| data class Success(val productId: Long) : AiProductSaveResult | ||
| sealed interface Failure : AiProductSaveResult { | ||
| data object UploadImageFailure : Failure | ||
| data class Generic(val uploadedImage: Image.WPMediaLibraryImage? = null) : Failure | ||
| } | ||
| } |
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
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice 💯