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.
244 lines
14 KiB
C#
244 lines
14 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
|
|
{
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using Cache.Redis.Models;
|
|
using Context;
|
|
using Data.Context;
|
|
using Data.Poco;
|
|
using Data.Repository;
|
|
using Extensions;
|
|
using TaskCancellation.TaskHelper;
|
|
using TtlCounterAdministration;
|
|
using EntityAnalysisModel=EntityAnalysisModel.EntityAnalysisModel;
|
|
using EntityAnalysisModelTtlCounter=EntityAnalysisModel.Models.Models.EntityAnalysisModelTtlCounter;
|
|
|
|
public class TtlCounterAdministrationTaskStarter(Context context)
|
|
{
|
|
public async Task StartAsync()
|
|
{
|
|
try
|
|
{
|
|
while (!context.Services.TaskCoordinator.CancellationToken.IsCancellationRequested)
|
|
{
|
|
try
|
|
{
|
|
var activeModelsForLoopWithoutEnumError = context.EntityAnalysisModels.ActiveEntityAnalysisModels.ToList();
|
|
foreach (var (key, value) in
|
|
from modelEntityKvp in activeModelsForLoopWithoutEnumError
|
|
where modelEntityKvp.Value.Started
|
|
select modelEntityKvp)
|
|
{
|
|
context.Services.TaskCoordinator.CancellationToken.ThrowIfCancellationRequested();
|
|
|
|
if (context.Services.Log.IsDebugEnabled)
|
|
{
|
|
context.Services.Log.Debug(
|
|
$"Entity TTL Counter Administration: Entity Model {key} is being started.");
|
|
}
|
|
|
|
await ProcessAsync(context, value).ConfigureAwait(false);
|
|
|
|
if (context.Services.Log.IsDebugEnabled)
|
|
{
|
|
context.Services.Log.Debug(
|
|
$"Entity TTL Counter Administration: Entity Model {key} has finished will wait for {context.Services.DynamicEnvironment.AppSettings("WaitTtlCounterDecrement")} milliseconds.");
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
|
{
|
|
context.Services.Log.Error(ex.ToString());
|
|
}
|
|
finally
|
|
{
|
|
await Task.Delay(Int32.Parse(context.Services.DynamicEnvironment.AppSettings("WaitTtlCounterDecrement")), context.Services.TaskCoordinator.CancellationToken).ConfigureAwait(false);
|
|
}
|
|
}
|
|
}
|
|
catch (OperationCanceledException ex)
|
|
{
|
|
context.Services.Log.Info($"Graceful Cancellation TtlCounterAdministrationAsync: has produced an error {ex}");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
context.Services.Log.Error($"TtlCounterAdministrationAsync: has produced an error {ex}");
|
|
}
|
|
}
|
|
|
|
private static async Task ProcessAsync(Context context, EntityAnalysisModel entityAnalysisModel)
|
|
{
|
|
try
|
|
{
|
|
if (entityAnalysisModel.Services.Log.IsInfoEnabled)
|
|
{
|
|
entityAnalysisModel.Services.Log.Info(
|
|
$"TTL Counter Administration: has started for {entityAnalysisModel.Instance.Id}. Is about to loop around all TTL Counters.");
|
|
}
|
|
|
|
foreach (var ttlCounterWithinLoop in entityAnalysisModel.Collections.ModelTtlCounters)
|
|
{
|
|
context.Services.TaskCoordinator.CancellationToken.ThrowIfCancellationRequested();
|
|
|
|
try
|
|
{
|
|
if (entityAnalysisModel.Services.Log.IsInfoEnabled)
|
|
{
|
|
entityAnalysisModel.Services.Log.Info(
|
|
$"TTL Counter Administration: has started for {entityAnalysisModel.Instance.Id} is about to process TTL Counter {ttlCounterWithinLoop.Name} and data name {ttlCounterWithinLoop.TtlCounterDataName}.");
|
|
}
|
|
|
|
var ttlCounterAdministrationCacheService = new TtlCounterAdministrationCacheService(entityAnalysisModel);
|
|
|
|
var referenceDate = await ttlCounterAdministrationCacheService.CacheServiceGetReferenceDateAsync().ConfigureAwait(false);
|
|
|
|
if (referenceDate.HasValue)
|
|
{
|
|
if (entityAnalysisModel.Services.Log.IsInfoEnabled)
|
|
{
|
|
entityAnalysisModel.Services.Log.Info(
|
|
$"TTL Counter Administration: has started for {entityAnalysisModel.Instance.Id} is about to process TTL Counter {ttlCounterWithinLoop.Name} obtained reference date of {referenceDate}.");
|
|
}
|
|
|
|
var adjustedTtlCounterDate =
|
|
ttlCounterAdministrationCacheService.GetAdjustedTtlCounterDate(ttlCounterWithinLoop, referenceDate.Value);
|
|
|
|
var expiredTtlCounterEntries = await ttlCounterAdministrationCacheService.GetAllExpiredByTtlCounterAsync(
|
|
entityAnalysisModel.Services.CacheService.CacheTtlCounterEntryRepository, ttlCounterWithinLoop,
|
|
adjustedTtlCounterDate).ConfigureAwait(false);
|
|
|
|
if (!expiredTtlCounterEntries.Any())
|
|
{
|
|
continue;
|
|
}
|
|
|
|
var dbContext = DataConnectionDbContext.GetDbContextDataConnection(
|
|
context.Services.DynamicEnvironment.AppSettings("ConnectionString"));
|
|
|
|
try
|
|
{
|
|
var sortedSetExpiredCount = expiredTtlCounterEntries.Count;
|
|
var expiredSortedSetMinTimestamp = expiredTtlCounterEntries.FirstOrDefault().ReferenceDate.ToUnixTimeMilliSeconds();
|
|
var expiredSortedSetMaxTimestamp = expiredTtlCounterEntries.LastOrDefault().ReferenceDate.ToUnixTimeMilliSeconds();
|
|
|
|
var cacheTtlCounterEntryRemovalBatchRepository = new CacheTtlCounterEntryRemovalBatchRepository(dbContext);
|
|
var cacheTtlCounterEntryRemovalBatch = await cacheTtlCounterEntryRemovalBatchRepository.InsertAsync(new CacheTtlCounterEntryRemovalBatch
|
|
{
|
|
EntityAnalysisModelTtlCounterGuid = ttlCounterWithinLoop.Guid,
|
|
ReferenceDate = referenceDate,
|
|
ExpiredHashSetCount = sortedSetExpiredCount,
|
|
FirstExpiredHashSetReferenceDate = expiredSortedSetMinTimestamp.FromUnixTimeMilliSeconds(),
|
|
LastExpiredHashSetReferenceDate = expiredSortedSetMaxTimestamp.FromUnixTimeMilliSeconds()
|
|
}, context.Services.TaskCoordinator.CancellationToken).ConfigureAwait(false);
|
|
|
|
var cacheTtlCounterEntryRemovalBatchEntryList = new List<CacheTtlCounterEntryRemovalBatchEntry>();
|
|
var tasks = new List<Task<TimedTaskResult>>();
|
|
foreach (var expiredTtlCounterEntry in expiredTtlCounterEntries)
|
|
{
|
|
context.Services.TaskCoordinator.CancellationToken.ThrowIfCancellationRequested();
|
|
|
|
tasks.Add(TaskHelper.MeasureTaskTimeAndMemoryAllocatedAsync(TaskType.ProcessTtlCounterDeprecation, async () => await ProcessTtlCounterDeprecationAsync(entityAnalysisModel,
|
|
ttlCounterAdministrationCacheService, ttlCounterWithinLoop, expiredTtlCounterEntry,
|
|
cacheTtlCounterEntryRemovalBatchEntryList, cacheTtlCounterEntryRemovalBatch).ConfigureAwait(false)));
|
|
}
|
|
|
|
await Task.WhenAll(tasks).ConfigureAwait(false);
|
|
var cacheTtlCounterEntryRemovalBatchEntryRepository = new CacheTtlCounterEntryRemovalBatchEntryRepository(dbContext);
|
|
await cacheTtlCounterEntryRemovalBatchEntryRepository.BulkCopyAsync(cacheTtlCounterEntryRemovalBatchEntryList).ConfigureAwait(false);
|
|
|
|
var completedTasks = await Task.WhenAll(tasks).ConfigureAwait(false);
|
|
var cacheTtlCounterEntryRemovalBatchResponseTimeRepository = new CacheTtlCounterEntryRemovalBatchResponseTimeRepository(dbContext);
|
|
// ReSharper disable once MethodSupportsCancellation
|
|
await TaskHelper.MeasureTaskTimeAndMemoryAllocatedAsync(TaskType.BulkInsertTtlCounterEntryRemovalBatchResponseTime, async () => await cacheTtlCounterEntryRemovalBatchResponseTimeRepository.BulkCopyAsync(AggregateResponseTimesForBulkInsert(completedTasks, cacheTtlCounterEntryRemovalBatch)).ConfigureAwait(false));
|
|
await cacheTtlCounterEntryRemovalBatchRepository.FinishAsync(cacheTtlCounterEntryRemovalBatch.Id).ConfigureAwait(false);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
entityAnalysisModel.Services.Log.Error(
|
|
$"TTL Counter Administration: has started for {entityAnalysisModel.Instance.Id}. Has created an error {ex}.");
|
|
}
|
|
finally
|
|
{
|
|
await dbContext.CloseAsync();
|
|
await dbContext.DisposeAsync();
|
|
}
|
|
}
|
|
else
|
|
{
|
|
if (entityAnalysisModel.Services.Log.IsInfoEnabled)
|
|
{
|
|
entityAnalysisModel.Services.Log.Info(
|
|
$"TTL Counter Administration: Reference Date returned for {entityAnalysisModel.Instance.Id} and {ttlCounterWithinLoop.Name} as null.");
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
|
{
|
|
entityAnalysisModel.Services.Log.Error(
|
|
$"TTL Counter Administration: has produced an error for {ttlCounterWithinLoop.Name} and Data Name {ttlCounterWithinLoop.TtlCounterDataName} as {ex}.");
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
|
{
|
|
entityAnalysisModel.Services.Log.Error($"TTL Counter Administration: has produced an error as {ex}");
|
|
}
|
|
finally
|
|
{
|
|
if (entityAnalysisModel.Services.Log.IsInfoEnabled)
|
|
{
|
|
entityAnalysisModel.Services.Log.Info(
|
|
$"TTL Counter Administration: Model TTL Counter processing for model id {entityAnalysisModel.Instance.Id} has finished.");
|
|
}
|
|
}
|
|
}
|
|
private static async Task ProcessTtlCounterDeprecationAsync(EntityAnalysisModel entityAnalysisModel, TtlCounterAdministrationCacheService ttlCounterAdministrationCacheService,
|
|
EntityAnalysisModelTtlCounter ttlCounterWithinLoop, ExpiredTtlCounterEntry expiredTtlCounterEntry,
|
|
List<CacheTtlCounterEntryRemovalBatchEntry> cacheTtlCounterEntryRemovalBatchEntryList,
|
|
CacheTtlCounterEntryRemovalBatch cacheTtlCounterEntryRemovalBatch)
|
|
{
|
|
|
|
var revisedCount = await ttlCounterAdministrationCacheService.CacheServiceDecrementTtlCounterAsync(ttlCounterWithinLoop, expiredTtlCounterEntry.DataName, expiredTtlCounterEntry.Value).ConfigureAwait(false);
|
|
|
|
await ttlCounterAdministrationCacheService.CacheServiceDeleteTtlCounterEntryAsync(entityAnalysisModel.Services.CacheService.CacheTtlCounterEntryRepository, ttlCounterWithinLoop,
|
|
expiredTtlCounterEntry.DataName,
|
|
expiredTtlCounterEntry.ReferenceDate).ConfigureAwait(false);
|
|
|
|
cacheTtlCounterEntryRemovalBatchEntryList.Add(new CacheTtlCounterEntryRemovalBatchEntry
|
|
{
|
|
CacheTtlCounterEntryRemovalBatchId = cacheTtlCounterEntryRemovalBatch.Id,
|
|
Value = expiredTtlCounterEntry.DataName,
|
|
DecrementCount = expiredTtlCounterEntry.Value,
|
|
RevisedCount = revisedCount,
|
|
ReferenceDate = expiredTtlCounterEntry.ReferenceDate
|
|
});
|
|
}
|
|
|
|
private static List<CacheTtlCounterEntryRemovalBatchResponseTime> AggregateResponseTimesForBulkInsert(TimedTaskResult[] tasks, CacheTtlCounterEntryRemovalBatch cacheTtlCounterEntryRemovalBatch)
|
|
{
|
|
var groupByComputeTime = tasks.GroupBy(g => g.TaskType).Select(s => new CacheTtlCounterEntryRemovalBatchResponseTime
|
|
{
|
|
TaskTypeId = (int)s.Key,
|
|
ResponseTime = s.Sum(a => a.ComputeTime),
|
|
CacheTtlCounterEntryRemovalBatchId = cacheTtlCounterEntryRemovalBatch.Id
|
|
}).ToList();
|
|
return groupByComputeTime;
|
|
}
|
|
}
|
|
}
|