mirror of
https://github.com/hanzoai/jube-fork.git
synced 2026-10-30 18:33:33 +00:00
* Added `Cache` flag to `EntityAnalysisRequestXPath`, updating POCOs, DTOs, and synchronisation mappings. Included migrations and updated pages and JS for new fields. * Updated the Completions Endpoint to only return values if Cache is enabled in the EntityAnalysisModelRequestXPath for EntityAnalysisModelAbstractionRule configuration. * Updated the parser to ignore fields if the parse processing type is Abstraction Rule, so to ensure that an Abstraction Rule does not compile anywhere, in the controller or syncronisation, if it trys to use a key that exists but is marked as Cache. * Created migrations for the cache flag and added indexes to cache key columns. * Implemented a new serialisation pattern for message pack payloads to reduce byte storage of names, replacing them with a `CacheIndexId` serialised as a single byte. * Implemented indexing logic for `CacheIndexId`, which increments within a transaction per `EntityAnalysisModel`. Created `CacheIndexId` values for legacy data. * Created migrations for legacy Redis cache payload data to adopt the new `CacheIndexId` format. Added a unique composite index to enforce sequencing and eliminate conflict risks. * Implemented a new LRU cache warming strategy that populates the LRU cache based on journal usage. During warming, cache entries are populated in order of most recently used journals, exiting when byte limits are reached. This replaces a full cursor scan of payload data, reducing container startup time and mitigating Redis herd-stampede risks. Each journal recall writes to a sorted set (`LruJournals`) that maintains an ordered activity list for cache population. On payload entry removal, the corresponding journal is checked and the `LruJournal` key is removed if no further data exists. Added a `SortedSetLruJournalRemove` enum for task tracking. Implemented an `IsFull` method on the local LRU cache to exit warming once full. * Updated TTL Counters to process `double` values instead of `int` to support summing of integer and float payload types, making Volume and Velocity rules available to TTL Counters and long-term state. Updated POCOs, DTOs, and synchronisation mappings, applied logic in invocation processes, and included migrations. Updated pages and JS for new fields. * Updated TTL Counters to specify date resolution for TTL Counter entries, reducing memory footprint by allowing aggregation at broader date roundings (e.g. for long-term state, a daily entry expiry is sufficient). Updated VB.NET code wrappers for the new generic. * Updated TTL Counters to support an `EnableSum` flag, which uses a `TtlCounterDataValue` field to specify the value to sum. Implemented a dropdown in the page and JS that returns only integer and float data types for selection. * Updated the efficient no-boxing dictionary to instantiate on the basis of generic type, enabling use with both `int` (message pack) and `string` (core processing and legacy payload migrations). This touched a large number of files and is the primary reason for the size of this commit. Updated the dictionary to support addition of internal values via the interface for serialisation and mapping. Updated JSON serialisers to support the generic. * Implemented invocation mapping logic for insert and recall between the indexed Redis payload and the string-keyed payload required for processing. * Bumped the message pack envelope version flag to version 2 to reflect the new payload formats (noting that all data has been migrated and version 1 no longer exists in Redis). * Updated documentation to cover `LruJournals` in the Redis section, the `Cache` field on the `EntityAnalysisModelsRequestXPath` page, and the `ResolutionInterval` and `TtlCounterDataValue` fields on the `EntityAnalysisTtlCounters` page.
218 lines
13 KiB
C#
218 lines
13 KiB
C#
/* Copyright (C) 2022-present Jube Holdings Limited.
|
|
*
|
|
* This file is part of Jube™ software.
|
|
*
|
|
* Jube™ is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License
|
|
* as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
|
* Jube™ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
|
|
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
|
|
|
|
* You should have received a copy of the GNU Affero General Public License along with Jube™. If not,
|
|
* see <https://www.gnu.org/licenses/>.
|
|
*/
|
|
|
|
namespace Jube.Engine.EntityAnalysisModelManager.BackgroundTasks.TaskStarters.AbstractionRuleCaching
|
|
{
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Threading.Tasks;
|
|
using Cache.Redis;
|
|
using Dictionary;
|
|
using EntityAnalysisModel;
|
|
using EntityAnalysisModel.Models.Models;
|
|
|
|
public class AbstractionRuleCachingCacheService(EntityAnalysisModel entityAnalysisModel)
|
|
{
|
|
public async Task<List<string>> CacheServiceGetExpiredCacheKeysAsync(DistinctSearchKey distinctSearchKey)
|
|
{
|
|
List<string> values = null;
|
|
|
|
try
|
|
{
|
|
if (!entityAnalysisModel.Dependencies.LastAbstractionRuleCache.TryGetValue(distinctSearchKey.SearchKey, out var value))
|
|
{
|
|
return [];
|
|
}
|
|
|
|
if (entityAnalysisModel.Services.Log.IsInfoEnabled)
|
|
{
|
|
entityAnalysisModel.Services.Log.Info(
|
|
$"Abstraction Rule Caching: For model {entityAnalysisModel.Instance.Id} and grouping key {distinctSearchKey.SearchKey} has a interval value of {distinctSearchKey.SearchKeyCacheTtlValue} and an interval of {distinctSearchKey.SearchKeyCacheInterval}. Calculating the threshold for grouping keys that have expired.");
|
|
}
|
|
|
|
var deleteLineCacheKeys = distinctSearchKey.SearchKeyCacheTtlInterval switch
|
|
{
|
|
"s" => value.AddSeconds(distinctSearchKey.SearchKeyCacheTtlValue * -1),
|
|
"n" => value.AddMinutes(distinctSearchKey.SearchKeyCacheTtlValue * -1),
|
|
"h" => value.AddHours(distinctSearchKey.SearchKeyCacheTtlValue * -1),
|
|
_ => value.AddDays(distinctSearchKey.SearchKeyCacheTtlValue * -1)
|
|
};
|
|
|
|
if (entityAnalysisModel.Services.Log.IsInfoEnabled)
|
|
{
|
|
entityAnalysisModel.Services.Log.Info(
|
|
$"Abstraction Rule Caching: For model {entityAnalysisModel.Instance.Id} and grouping key {distinctSearchKey.SearchKey} the date threshold for cache keys that have expired is {deleteLineCacheKeys}.");
|
|
}
|
|
|
|
values = await entityAnalysisModel.Services.CacheService.CachePayloadLatestRepository.GetDistinctKeysAsync(entityAnalysisModel.Instance.TenantRegistryId, entityAnalysisModel.Instance.Guid,
|
|
distinctSearchKey.SearchKey,
|
|
deleteLineCacheKeys).ConfigureAwait(false);
|
|
}
|
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
|
{
|
|
entityAnalysisModel.Services.Log.Error($"CacheServiceGetExpiredCacheKeysAsync: has produced an error {ex}");
|
|
}
|
|
|
|
return values;
|
|
}
|
|
|
|
public async Task CacheServiceUpsertOrDeleteSearchKeyValueAsync(DistinctSearchKey distinctSearchKey,
|
|
string groupingValue,
|
|
KeyValuePair<int, List<DictionaryNoBoxing<string>>> abstractionRuleMatch,
|
|
EntityAnalysisModelAbstractionRule abstractionRule,
|
|
double abstractionValue)
|
|
{
|
|
try
|
|
{
|
|
var value = await CacheServiceFindCacheKeyValueEntryAsync(entityAnalysisModel.Services.CacheService.CacheAbstractionRepository,
|
|
distinctSearchKey, groupingValue, abstractionRuleMatch, abstractionRule,
|
|
abstractionValue).ConfigureAwait(false);
|
|
|
|
if (value == null)
|
|
{
|
|
if (abstractionValue > 0)
|
|
{
|
|
await CacheServiceInsertSearchKeyValueAsync(entityAnalysisModel.Services.CacheService.CacheAbstractionRepository,
|
|
distinctSearchKey, groupingValue,
|
|
abstractionRuleMatch, abstractionRule,
|
|
abstractionValue).ConfigureAwait(false);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
await CacheServiceUpdateOrDeleteSearchKeyValueAsync(entityAnalysisModel.Services.CacheService.CacheAbstractionRepository, distinctSearchKey, groupingValue,
|
|
abstractionRule,
|
|
abstractionValue).ConfigureAwait(false);
|
|
}
|
|
}
|
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
|
{
|
|
entityAnalysisModel.Services.Log.Error($"CacheServiceUpsertOrDeleteSearchKeyValueAsync: has produced an error {ex}");
|
|
}
|
|
}
|
|
|
|
private async Task<double?> CacheServiceFindCacheKeyValueEntryAsync(CacheAbstractionRepository cacheAbstractionRepository,
|
|
DistinctSearchKey distinctSearchKey, string groupingValue,
|
|
KeyValuePair<int, List<DictionaryNoBoxing<string>>> abstractionRuleMatch,
|
|
EntityAnalysisModelAbstractionRule abstractionRule,
|
|
double abstractionValue)
|
|
{
|
|
double? value = null;
|
|
try
|
|
{
|
|
value = await cacheAbstractionRepository.GetAsync(
|
|
entityAnalysisModel.Instance.TenantRegistryId, entityAnalysisModel.Instance.Guid, abstractionRule.Name, distinctSearchKey.SearchKey, groupingValue).ConfigureAwait(false);
|
|
|
|
if (entityAnalysisModel.Services.Log.IsInfoEnabled)
|
|
{
|
|
entityAnalysisModel.Services.Log.Info(
|
|
$"Abstraction Rule Caching: For model {entityAnalysisModel.Instance.Id} and for Grouping Value {groupingValue} and Grouping Key {distinctSearchKey.SearchKey} for abstraction rule {abstractionRuleMatch.Key} has returned aggregated value of {abstractionValue}. The cache has returned for rule name {abstractionRule.Name} with {value == null} null document. An upsert will now take place.");
|
|
}
|
|
|
|
return value;
|
|
}
|
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
|
{
|
|
entityAnalysisModel.Services.Log.Error($"CacheServiceFindCacheKeyValueEntryAsync: has produced an error {ex}");
|
|
}
|
|
|
|
return value;
|
|
}
|
|
|
|
private async Task CacheServiceInsertSearchKeyValueAsync(CacheAbstractionRepository cacheAbstractionRepository,
|
|
DistinctSearchKey distinctSearchKey, string groupingValue,
|
|
KeyValuePair<int, List<DictionaryNoBoxing<string>>> abstractionRuleMatch,
|
|
EntityAnalysisModelAbstractionRule abstractionRule,
|
|
double abstractionValue)
|
|
{
|
|
try
|
|
{
|
|
var (key, _) = abstractionRuleMatch;
|
|
|
|
if (entityAnalysisModel.Services.Log.IsInfoEnabled)
|
|
{
|
|
entityAnalysisModel.Services.Log.Info(
|
|
$"Abstraction Rule Caching: For model {entityAnalysisModel.Instance.Id} and for Grouping Value {groupingValue} and Grouping Key {distinctSearchKey.SearchKey} for abstraction rule {key} has returned aggregated value of {abstractionValue}. The cache will be searched with the rule name {abstractionRule.Name}. As there are no existing cache values, it will be inserted.");
|
|
}
|
|
|
|
await cacheAbstractionRepository.UpsertAsync(entityAnalysisModel.Instance.TenantRegistryId, entityAnalysisModel.Instance.Guid, distinctSearchKey.SearchKey,
|
|
groupingValue, abstractionRule.Name, abstractionValue).ConfigureAwait(false);
|
|
|
|
if (entityAnalysisModel.Services.Log.IsInfoEnabled)
|
|
{
|
|
entityAnalysisModel.Services.Log.Info(
|
|
$"Abstraction Rule Caching: For model {entityAnalysisModel.Instance.Id} and for Grouping Value {groupingValue} and Grouping Key {distinctSearchKey.SearchKey} for abstraction rule {key} has returned aggregated value of {abstractionValue}. The cache will be searched with the rule name {abstractionRule.Name}. As there are no existing cache values, it has been updated.");
|
|
}
|
|
}
|
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
|
{
|
|
entityAnalysisModel.Services.Log.Error($"CacheServiceInsertSearchKeyValueAsync: has produced an error {ex}");
|
|
}
|
|
}
|
|
|
|
private async Task CacheServiceUpdateOrDeleteSearchKeyValueAsync(CacheAbstractionRepository cacheAbstractionRepository,
|
|
DistinctSearchKey distinctSearchKey, string groupingValue,
|
|
EntityAnalysisModelAbstractionRule abstractionRule,
|
|
double abstractionValue)
|
|
{
|
|
try
|
|
{
|
|
if (entityAnalysisModel.Services.Log.IsInfoEnabled)
|
|
{
|
|
entityAnalysisModel.Services.Log.Info(
|
|
$"Abstraction Rule Caching: For model {entityAnalysisModel.Instance.Id} and for Grouping Value {groupingValue} and Grouping Key {distinctSearchKey.SearchKey} for abstraction rule {abstractionRule.Name} has returned aggregated value of {abstractionValue}. The cache will be searched with the rule name {abstractionRule.Name}. As there are no existing cache values, it will be updated or deleted.");
|
|
}
|
|
|
|
if (abstractionValue == 0)
|
|
{
|
|
if (entityAnalysisModel.Services.Log.IsInfoEnabled)
|
|
{
|
|
entityAnalysisModel.Services.Log.Info(
|
|
$"Abstraction Rule Caching: For model {entityAnalysisModel.Instance.Id} and for Grouping Value {groupingValue} and Grouping Key {distinctSearchKey.SearchKey} for abstraction rule {abstractionRule.Name} has returned aggregated value of {abstractionValue}. The cache will be searched with the rule name {abstractionRule.Name}. As the abstraction value is zero, it will be deleted to save storage.");
|
|
}
|
|
|
|
await cacheAbstractionRepository.DeleteAsync(entityAnalysisModel.Instance.TenantRegistryId, entityAnalysisModel.Instance.Guid, distinctSearchKey.SearchKey,
|
|
groupingValue, abstractionRule.Name).ConfigureAwait(false);
|
|
|
|
if (entityAnalysisModel.Services.Log.IsInfoEnabled)
|
|
{
|
|
entityAnalysisModel.Services.Log.Info(
|
|
$"Abstraction Rule Caching: For model {entityAnalysisModel.Instance.Id} and for Grouping Value {groupingValue} and Grouping Key {distinctSearchKey.SearchKey} for abstraction rule {abstractionRule.Name} has returned aggregated value of {abstractionValue}. The cache will be searched with the rule name {abstractionRule.Name}. As the abstraction value is zero, it has been deleted to save storage.");
|
|
}
|
|
}
|
|
else
|
|
{
|
|
if (entityAnalysisModel.Services.Log.IsInfoEnabled)
|
|
{
|
|
entityAnalysisModel.Services.Log.Info(
|
|
$"Abstraction Rule Caching: For model {entityAnalysisModel.Instance.Id} and for Grouping Value {groupingValue} and Grouping Key {distinctSearchKey.SearchKey} for abstraction rule {abstractionRule.Name} has returned aggregated value of {abstractionValue}. The cache will be searched with the rule name {abstractionRule.Name}. As the abstraction value is not zero, it will be updated.");
|
|
}
|
|
|
|
await cacheAbstractionRepository.UpsertAsync(entityAnalysisModel.Instance.TenantRegistryId, entityAnalysisModel.Instance.Guid, distinctSearchKey.SearchKey,
|
|
groupingValue, abstractionRule.Name, abstractionValue).ConfigureAwait(false);
|
|
|
|
if (entityAnalysisModel.Services.Log.IsInfoEnabled)
|
|
{
|
|
entityAnalysisModel.Services.Log.Info(
|
|
$"Abstraction Rule Caching: For model {entityAnalysisModel.Instance.Id} and for Grouping Value {groupingValue} and Grouping Key {distinctSearchKey.SearchKey} for abstraction rule {abstractionRule.Name} has returned aggregated value of {abstractionValue}. The cache will be searched with the rule name {abstractionRule.Name}. As the abstraction value is not zero, it has been updated.");
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
|
{
|
|
entityAnalysisModel.Services.Log.Error($"CacheServiceUpdateOrDeleteSearchKeyValueAsync: has produced an error {ex}");
|
|
}
|
|
}
|
|
}
|
|
}
|