Skip to content

Commit

Permalink
Refactor to async methods and remove RabbitMQ (#567)
Browse files Browse the repository at this point in the history
  • Loading branch information
KrzysztofPajak authored Feb 7, 2025
1 parent 138c2e3 commit 462db62
Show file tree
Hide file tree
Showing 38 changed files with 216 additions and 433 deletions.
2 changes: 0 additions & 2 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@
<PackageVersion Include="DotLiquid" Version="2.3.18" />
<PackageVersion Include="FluentValidation.DependencyInjectionExtensions" Version="11.11.0" />
<PackageVersion Include="GoogleAuthenticator" Version="3.2.0" />
<PackageVersion Include="MassTransit" Version="8.3.5" />
<PackageVersion Include="MassTransit.RabbitMQ" Version="8.3.5" />
<PackageVersion Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.22.0" />
<PackageVersion Include="Microsoft.Azure.AppConfiguration.AspNetCore" Version="8.0.0" />
<PackageVersion Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.1" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,12 @@ public GetPriceByCustomerProductQueryHandler(ICacheBase cacheBase,
public async Task<double?> Handle(GetPriceByCustomerProductQuery request, CancellationToken cancellationToken)
{
var key = string.Format(CacheKey.CUSTOMER_PRODUCT_PRICE_KEY_ID, request.CustomerId, request.ProductId);
var productPrice = _cacheBase.Get(key, () =>
var productPrice = await _cacheBase.GetAsync(key, async () =>
{
var pp = _customerProductPriceRepository.Table
.FirstOrDefault(x => x.CustomerId == request.CustomerId && x.ProductId == request.ProductId);
return pp == null ? (null, false) : (pp, true);
var pp = _customerProductPriceRepository.Table.FirstOrDefault(x => x.CustomerId == request.CustomerId && x.ProductId == request.ProductId);
return await Task.FromResult(pp);
});

if (!productPrice.Item2)
return await Task.FromResult(default(double?));
return await Task.FromResult(productPrice.pp.Price);
return productPrice?.Price;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public PaymentService(PaymentSettings paymentSettings,
public virtual async Task<IList<IPaymentProvider>> LoadActivePaymentMethods(Customer customer = null,
string storeId = "", string filterByCountryId = "")
{
var pm = LoadAllPaymentMethods(customer, storeId, filterByCountryId)
var pm = (await LoadAllPaymentMethods(customer, storeId, filterByCountryId))
.Where(provider =>
_paymentSettings.ActivePaymentProviderSystemNames.Contains(provider.SystemName,
StringComparer.OrdinalIgnoreCase))
Expand All @@ -69,7 +69,7 @@ public virtual async Task<IList<IPaymentProvider>> LoadActivePaymentMethods(Cust
if (selectedShippingOption == null) return await Task.FromResult(pm);
for (var i = pm.Count - 1; i >= 0; i--)
{
var restrictedGroupIds = GetRestrictedShippingIds(pm[i]);
var restrictedGroupIds =await GetRestrictedShippingIds(pm[i]);
if (restrictedGroupIds.Contains(selectedShippingOption.Name)) pm.Remove(pm[i]);
}

Expand All @@ -94,35 +94,41 @@ public virtual IPaymentProvider LoadPaymentMethodBySystemName(string systemName)
/// <param name="customer">Customer</param>
/// <param name="filterByCountryId">Load records allowed only in a specified country; pass "" to load all records</param>
/// <returns>Payment providers</returns>
public virtual IList<IPaymentProvider> LoadAllPaymentMethods(Customer customer = null, string storeId = "",
public virtual async Task<IList<IPaymentProvider>> LoadAllPaymentMethods(Customer customer = null, string storeId = "",
string filterByCountryId = "")
{
var paymentMethods = _paymentProviders
.Where(x =>
x.IsAuthenticateStore(storeId) &&
x.IsAuthenticateGroup(customer))
.OrderBy(x => x.Priority).ToList();
return string.IsNullOrEmpty(filterByCountryId)
? paymentMethods
:
//filter by country
(from pm in paymentMethods
let restrictedCountryIds = GetRestrictedCountryIds(pm)
where !restrictedCountryIds.Contains(filterByCountryId)
select pm).ToList();

if (string.IsNullOrEmpty(filterByCountryId))
return paymentMethods;

var filteredPaymentMethods = new List<IPaymentProvider>();
foreach (var pm in paymentMethods)
{
var restrictedCountryIds = await GetRestrictedCountryIds(pm);
if (!restrictedCountryIds.Contains(filterByCountryId))
{
filteredPaymentMethods.Add(pm);
}
}
return filteredPaymentMethods;
}

/// <summary>
/// Gets a list of country identifiers in which a certain payment method is now allowed
/// </summary>
/// <param name="paymentMethod">Payment method</param>
/// <returns>A list of country identifiers</returns>
public virtual IList<string> GetRestrictedCountryIds(IPaymentProvider paymentMethod)
public virtual async Task<IList<string>> GetRestrictedCountryIds(IPaymentProvider paymentMethod)
{
ArgumentNullException.ThrowIfNull(paymentMethod);

var settingKey = $"PaymentMethodRestictions.{paymentMethod.SystemName}";
var restrictedCountryIds = _settingService.GetSettingByKey<PaymentRestrictedSettings>(settingKey);
var restrictedCountryIds = await _settingService.GetSettingByKey<PaymentRestrictedSettings>(settingKey);
return restrictedCountryIds == null ? new List<string>() : restrictedCountryIds.Ids;
}

Expand All @@ -131,12 +137,12 @@ public virtual IList<string> GetRestrictedCountryIds(IPaymentProvider paymentMet
/// </summary>
/// <param name="paymentMethod">Payment method</param>
/// <returns>A list of role identifiers</returns>
public virtual IList<string> GetRestrictedShippingIds(IPaymentProvider paymentMethod)
public virtual async Task<IList<string>> GetRestrictedShippingIds(IPaymentProvider paymentMethod)
{
ArgumentNullException.ThrowIfNull(paymentMethod);

var settingKey = $"PaymentMethodRestictionsShipping.{paymentMethod.SystemName}";
var restrictedShippingIds = _settingService.GetSettingByKey<PaymentRestrictedSettings>(settingKey);
var restrictedShippingIds = await _settingService.GetSettingByKey<PaymentRestrictedSettings>(settingKey);
return restrictedShippingIds == null ? new List<string>() : restrictedShippingIds.Ids;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,31 +59,29 @@ private IList<Setting> GetSettingsByName(string name)
/// </summary>
/// <param name="setting">Setting</param>
/// <param name="clearCache">A value indicating whether to clear cache after setting update</param>
public virtual async Task InsertSetting(Setting setting, bool clearCache = true)
public virtual async Task InsertSetting(Setting setting)
{
ArgumentNullException.ThrowIfNull(setting);

await _settingRepository.InsertAsync(setting);

//cache
if (clearCache)
await _cacheBase.Clear();
await _cacheBase.Clear();
}

/// <summary>
/// Updates a setting
/// </summary>
/// <param name="setting">Setting</param>
/// <param name="clearCache">A value indicating whether to clear cache after setting update</param>
public virtual async Task UpdateSetting(Setting setting, bool clearCache = true)
public virtual async Task UpdateSetting(Setting setting)
{
ArgumentNullException.ThrowIfNull(setting);

await _settingRepository.UpdateAsync(setting);

//cache
if (clearCache)
await _cacheBase.Clear();
await _cacheBase.Clear();
}

/// <summary>
Expand Down Expand Up @@ -119,21 +117,21 @@ public virtual Task<Setting> GetSettingById(string settingId)
/// <param name="defaultValue">Default value</param>
/// <param name="storeId">Store identifier</param>
/// <returns>Setting value</returns>
public virtual T GetSettingByKey<T>(string key, T defaultValue = default, string storeId = "")
public virtual async Task<T> GetSettingByKey<T>(string key, T defaultValue = default, string storeId = "")
{
if (string.IsNullOrEmpty(key))
return defaultValue;

var keyCache = string.Format(CacheKey.SETTINGS_BY_KEY, key, storeId);
return _cacheBase.Get(keyCache, () =>
return await _cacheBase.GetAsync<T>(keyCache, () =>
{
var settings = GetSettingsByName(key);
key = key.Trim().ToLowerInvariant();
if (!settings.Any()) return defaultValue;
if (!settings.Any()) return Task.FromResult(defaultValue);

var setting = settings.FirstOrDefault(x => x.StoreId == storeId) ??
settings.FirstOrDefault(x => string.IsNullOrEmpty(x.StoreId));
return setting != null ? JsonSerializer.Deserialize<T>(setting.Metadata) : defaultValue;
return setting != null ? Task.FromResult(JsonSerializer.Deserialize<T>(setting.Metadata)) : Task.FromResult(defaultValue);
});
}

Expand All @@ -145,7 +143,7 @@ public virtual T GetSettingByKey<T>(string key, T defaultValue = default, string
/// <param name="value">Value</param>
/// <param name="storeId">Store identifier</param>
/// <param name="clearCache">A value indicating whether to clear cache after setting update</param>
public virtual async Task SetSetting<T>(string key, T value, string storeId = "", bool clearCache = true)
public virtual async Task SetSetting<T>(string key, T value, string storeId = "")
{
ArgumentNullException.ThrowIfNull(key);

Expand All @@ -157,7 +155,7 @@ public virtual async Task SetSetting<T>(string key, T value, string storeId = ""
{
//update
setting.Metadata = JsonSerializer.Serialize(value);
await UpdateSetting(setting, clearCache);
await UpdateSetting(setting);
}
else
{
Expand All @@ -168,7 +166,7 @@ public virtual async Task SetSetting<T>(string key, T value, string storeId = ""
Metadata = metadata,
StoreId = storeId
};
await InsertSetting(setting, clearCache);
await InsertSetting(setting);
}
}

Expand All @@ -186,9 +184,9 @@ public virtual IList<Setting> GetAllSettings()
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="storeId">Store identifier for which settings should be loaded</param>
public virtual T LoadSetting<T>(string storeId = "") where T : ISettings, new()
public virtual Task<T> LoadSetting<T>(string storeId = "") where T : ISettings, new()
{
return (T)LoadSetting(typeof(T), storeId);
return Task.FromResult((T)LoadSetting(typeof(T), storeId));
}

/// <summary>
Expand All @@ -208,7 +206,9 @@ public virtual ISettings LoadSetting(Type type, string storeId = "")
if (setting == null && !string.IsNullOrEmpty(storeId))
setting = settings.FirstOrDefault(x => string.IsNullOrEmpty(x.StoreId));

if (setting != null) return JsonSerializer.Deserialize(setting.Metadata, type) as ISettings;
if (setting != null)
return JsonSerializer.Deserialize(setting.Metadata, type) as ISettings;

return Activator.CreateInstance(type) as ISettings;
});
}
Expand Down Expand Up @@ -239,9 +239,6 @@ public virtual ISettings LoadSetting(Type type, string storeId = "")
};
await InsertSetting(setting);
}

//and now clear cache
await ClearCache();
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,22 +35,22 @@ Task<IList<IPaymentProvider>> LoadActivePaymentMethods(Customer customer = null,
/// <param name="customer">Customer</param>
/// <param name="filterByCountryId">Specified country</param>
/// <returns>Payment providers</returns>
IList<IPaymentProvider> LoadAllPaymentMethods(Customer customer = null, string storeId = "",
Task<IList<IPaymentProvider>> LoadAllPaymentMethods(Customer customer = null, string storeId = "",
string filterByCountryId = "");

/// <summary>
/// Gets a list of country identifiers in which a certain payment method is now allowed
/// </summary>
/// <param name="paymentMethod">Payment method</param>
/// <returns>A list of country identifiers</returns>
IList<string> GetRestrictedCountryIds(IPaymentProvider paymentMethod);
Task<IList<string>> GetRestrictedCountryIds(IPaymentProvider paymentMethod);

/// <summary>
/// Gets a list of shipping identifiers in which a certain payment method is now allowed
/// </summary>
/// <param name="paymentMethod">Payment method</param>
/// <returns>A list of role identifiers</returns>
IList<string> GetRestrictedShippingIds(IPaymentProvider paymentMethod);
Task<IList<string>> GetRestrictedShippingIds(IPaymentProvider paymentMethod);

/// <summary>
/// Saves a list of country identifiers in which a certain payment method is now allowed
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,14 @@ public interface ISettingService
/// Adds a setting
/// </summary>
/// <param name="setting">Setting</param>
/// <param name="clearCache">A value indicating whether to clear cache after setting update</param>
Task InsertSetting(Setting setting, bool clearCache = true);
Task InsertSetting(Setting setting);

/// <summary>
/// Update setting
/// </summary>
/// <param name="setting"></param>
/// <param name="clearCache"></param>
/// <returns></returns>
Task UpdateSetting(Setting setting, bool clearCache = true);
Task UpdateSetting(Setting setting);

/// <summary>
/// Deletes a setting
Expand All @@ -43,7 +41,7 @@ public interface ISettingService
/// <param name="storeId">Store identifier</param>
/// <param name="defaultValue">Default value</param>
/// <returns>Setting value</returns>
T GetSettingByKey<T>(string key, T defaultValue = default, string storeId = "");
Task<T> GetSettingByKey<T>(string key, T defaultValue = default, string storeId = "");

/// <summary>
/// Set setting value
Expand All @@ -52,8 +50,7 @@ public interface ISettingService
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="storeId">Store identifier</param>
/// <param name="clearCache">A value indicating whether to clear cache after setting update</param>
Task SetSetting<T>(string key, T value, string storeId = "", bool clearCache = true);
Task SetSetting<T>(string key, T value, string storeId = "");

/// <summary>
/// Gets all settings
Expand All @@ -66,7 +63,7 @@ public interface ISettingService
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="storeId">Store identifier for which settings should be loaded</param>
T LoadSetting<T>(string storeId = "") where T : ISettings, new();
Task<T> LoadSetting<T>(string storeId = "") where T : ISettings, new();

/// <summary>
/// Load settings
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,19 +155,18 @@ protected override async Task<string> GetThumbPhysicalPath(string thumbFileName)
/// </summary>
/// <param name="thumbFileName">Thumb file name</param>
/// <returns>Result</returns>
private Task<bool> GeneratedThumbExists(string thumbFileName)
private async Task<bool> GeneratedThumbExists(string thumbFileName)
{
try
{
var getObjectResponse = _s3Client.GetObjectAsync(_bucketName, thumbFileName).GetAwaiter().GetResult();
var getObjectResponse = await _s3Client.GetObjectAsync(_bucketName, thumbFileName);
EnsureValidResponse(getObjectResponse, HttpStatusCode.OK);

return Task.FromResult(
getObjectResponse.BucketName == _bucketName || getObjectResponse.Key == thumbFileName);
return getObjectResponse.BucketName == _bucketName || getObjectResponse.Key == thumbFileName;
}
catch
{
return Task.FromResult(false);
return false;
}
}

Expand Down
6 changes: 3 additions & 3 deletions src/Core/Grand.Infrastructure/Caching/ICacheBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ namespace Grand.Infrastructure.Caching;
/// <summary>
/// Cache manager interface
/// </summary>
public interface ICacheBase : IDisposable
public interface ICacheBase
{
T Get<T>(string key, Func<T> acquire);
T Get<T>(string key, Func<T> acquire, int cacheTime);
Task<T> GetAsync<T>(string key, Func<Task<T>> acquire);
Task<T> GetAsync<T>(string key, Func<Task<T>> acquire, int cacheTime);
Task<T> SetAsync<T>(string key, Func<Task<T>> acquire);
Task<T> SetAsync<T>(string key, Func<Task<T>> acquire, int cacheTime);
T Get<T>(string key, Func<T> acquire);
T Get<T>(string key, Func<T> acquire, int cacheTime);
Task RemoveAsync(string key, bool publisher = true);
Task RemoveByPrefix(string prefix, bool publisher = true);
Task Clear(bool publisher = true);
Expand Down
Loading

0 comments on commit 462db62

Please sign in to comment.