Skip to content

Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.

perf(catalog): cache the storefront catalog by customer group, not by customer (#768)

Krzysztof Pajak557dded22abd
diff --git a/src/Business/Grand.Business.Catalog/Services/Categories/CategoryService.cs b/src/Business/Grand.Business.Catalog/Services/Categories/CategoryService.cs
index 906ed4e53..59f3b4f20 100644
--- a/src/Business/Grand.Business.Catalog/Services/Categories/CategoryService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Categories/CategoryService.cs
@@ -1,4 +1,4 @@
-using Grand.Business.Core.Extensions;
+using Grand.Business.Core.Extensions;
using Grand.Business.Core.Interfaces.Catalog.Categories;
using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Data;
@@ -160,7 +160,7 @@ public class CategoryService : ICategoryService
bool showHidden = false, bool includeAllLevels = false)
{
var key = string.Format(CacheKey.CATEGORIES_BY_PARENT_CATEGORY_ID_KEY, parentCategoryId, showHidden,
- CurrentCustomer.Id, CurrentStore.Id, includeAllLevels);
+ string.Join(",", CurrentCustomer.GetCustomerGroupIds()), CurrentStore.Id, includeAllLevels);
return await _cacheBase.GetAsync(key, async () =>
{
var query = _categoryRepository.Table.Where(c => c.ParentCategoryId == parentCategoryId);
diff --git a/src/Business/Grand.Business.Catalog/Services/Categories/ProductCategoryService.cs b/src/Business/Grand.Business.Catalog/Services/Categories/ProductCategoryService.cs
index b1f751e9f..5411f405c 100644
--- a/src/Business/Grand.Business.Catalog/Services/Categories/ProductCategoryService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Categories/ProductCategoryService.cs
@@ -49,7 +49,8 @@ public class ProductCategoryService : IProductCategoryService
return new PagedList<ProductsCategory>(new List<ProductsCategory>(), pageIndex, pageSize);
var key = string.Format(CacheKey.PRODUCTCATEGORIES_ALLBYCATEGORYID_KEY, showHidden, categoryId, pageIndex,
- pageSize, _contextAccessor.WorkContext.CurrentCustomer.Id, _contextAccessor.StoreContext.CurrentStore.Id);
+ pageSize, string.Join(",", _contextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds()),
+ _contextAccessor.StoreContext.CurrentStore.Id);
return await _cacheBase.GetAsync(key, () =>
{
var query = _productRepository.Table.Where(x => x.ProductCategories.Any(y => y.CategoryId == categoryId));
diff --git a/src/Business/Grand.Business.Catalog/Services/Collections/ProductCollectionService.cs b/src/Business/Grand.Business.Catalog/Services/Collections/ProductCollectionService.cs
index 7f12a6ebd..528fe3310 100644
--- a/src/Business/Grand.Business.Catalog/Services/Collections/ProductCollectionService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Collections/ProductCollectionService.cs
@@ -45,7 +45,7 @@ public class ProductCollectionService : IProductCollectionService
int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false)
{
var key = string.Format(CacheKey.PRODUCTCOLLECTIONS_ALLBYCOLLECTIONID_KEY, showHidden, collectionId, pageIndex,
- pageSize, _contextAccessor.WorkContext.CurrentCustomer.Id, storeId);
+ pageSize, string.Join(",", _contextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds()), storeId);
return await _cacheBase.GetAsync(key, () =>
{
var query = _productRepository.Table.Where(x =>
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/CategoryServiceCacheKeyTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/CategoryServiceCacheKeyTests.cs
new file mode 100644
index 000000000..8a8ab6ecf
--- /dev/null
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/CategoryServiceCacheKeyTests.cs
@@ -0,0 +1,83 @@
+using Grand.Business.Catalog.Services.Categories;
+using Grand.Business.Common.Services.Security;
+using Grand.Data;
+using Grand.Data.Tests.MongoDb;
+using Grand.Domain.Catalog;
+using Grand.Domain.Customers;
+using Grand.Domain.Stores;
+using Grand.Infrastructure;
+using Grand.Infrastructure.Caching;
+using Grand.Infrastructure.Configuration;
+using Grand.Infrastructure.Tests.Caching;
+using Grand.Mediator;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Moq;
+
+namespace Grand.Business.Catalog.Tests.Services.Categories;
+
+/// <summary>
+/// The category tree a visitor may see depends on the customer's groups, never on which customer
+/// they are - the ACL filter inside the service reads GetCustomerGroupIds(). Keying the cache by
+/// customer identity therefore gives every guest a private copy of the same data.
+/// Reference equality is the assertion here: the memory cache hands back the very instance it
+/// stored, so sharing an instance proves the two lookups produced the same key.
+/// </summary>
+[TestClass]
+public class CategoryServiceCacheKeyTests
+{
+ private MemoryCacheBase _cacheBase;
+ private IRepository<Category> _categoryRepository;
+ private CategoryService _categoryService;
+ private Customer _currentCustomer;
+
+ [TestInitialize]
+ public void InitializeTests()
+ {
+ _categoryRepository = new MongoDBRepositoryTest<Category>();
+ _currentCustomer = new Customer();
+ var contextAccessor = new Mock<IContextAccessor>();
+ contextAccessor.Setup(c => c.StoreContext.CurrentStore).Returns(() => new Store { Id = "store" });
+ contextAccessor.Setup(c => c.WorkContext.CurrentCustomer).Returns(() => _currentCustomer);
+ var mediator = new Mock<IMediator>();
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), mediator.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ _categoryService = new CategoryService(_cacheBase, _categoryRepository, contextAccessor.Object,
+ mediator.Object, new AclService(new AccessControlConfig()), new AccessControlConfig());
+ }
+
+ private static Customer WithGroups(string id, params string[] groups)
+ {
+ var customer = new Customer { Id = id };
+ foreach (var group in groups)
+ customer.Groups.Add(group);
+ return customer;
+ }
+
+ [TestMethod]
+ public async Task TwoCustomersOfTheSameGroup_ShareTheCachedTree()
+ {
+ await _categoryService.InsertCategory(new Category { ParentCategoryId = "root", Published = true });
+
+ _currentCustomer = WithGroups("customer-1", "group-a");
+ var first = await _categoryService.GetAllCategoriesByParentCategoryId("root");
+
+ _currentCustomer = WithGroups("customer-2", "group-a");
+ var second = await _categoryService.GetAllCategoriesByParentCategoryId("root");
+
+ Assert.AreSame(first, second, "same groups must resolve to the same cache entry");
+ }
+
+ [TestMethod]
+ public async Task CustomersOfDifferentGroups_DoNotShareTheCachedTree()
+ {
+ await _categoryService.InsertCategory(new Category { ParentCategoryId = "root", Published = true });
+
+ _currentCustomer = WithGroups("customer-1", "group-a");
+ var first = await _categoryService.GetAllCategoriesByParentCategoryId("root");
+
+ _currentCustomer = WithGroups("customer-2", "group-b");
+ var second = await _categoryService.GetAllCategoriesByParentCategoryId("root");
+
+ Assert.AreNotSame(first, second, "the ACL filter differs per group, so the entries must differ");
+ }
+}