Files
jube-fork/Jube.Engine/EntityAnalysisModelInvoke/EntityAnalysisModelInvoke.cs
richard-churchman a6bbd81271 Features to exercise greater control over cache burden and improve cache warming:
* 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.
2026-02-27 15:40:15 +02:00

192 lines
10 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.EntityAnalysisModelInvoke
{
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using Context.Extensions;
using Dictionary;
using Exceptions;
using Extraction;
using Models.Payload.AsyncInvocationCallbackToken;
using Models.Payload.EntityAnalysisModelInstanceEntryPayload;
using TaskCancellation.TaskHelper;
using EntityAnalysisModel=EntityAnalysisModelManager.EntityAnalysisModel.EntityAnalysisModel;
public static class EntityAnalysisModelInvoke
{
public static async Task<Context.Context> InvokeAsync(EntityAnalysisModel entityAnalysisModel,
MemoryStream inputStream, int? maxBytes = null,
bool async = false)
{
if (maxBytes.HasValue)
{
CheckLengthGuardsForExceptions(inputStream, maxBytes.Value);
}
var extractor = new EntityAnalysisModelJsonExtractor(entityAnalysisModel, entityAnalysisModel.Dependencies.ActiveEntityAnalysisModels, entityAnalysisModel.Services.JubeEnvironment, entityAnalysisModel.Services.Log);
var context = extractor.CreateContext(inputStream);
context.EntityAnalysisModelInstanceEntryPayload.InvokeTaskPerformance.ComputeTimes.Parse = (int)(context.Stopwatch.ElapsedTicks * 1000000 / Stopwatch.Frequency);
await CheckAsyncAndInvokeContextAsync(async, context).ConfigureAwait(false);
return context;
}
public static Task InvokeAsync(EntityAnalysisModel entityAnalysisModel, DictionaryNoBoxing<string> dictionaryNoBoxing, int entityAnalysisModelReprocessingRuleInstanceId)
{
var extractor = new EntityAnalysisModelDictionaryNoBoxingExtractor(entityAnalysisModel, entityAnalysisModel.Dependencies.ActiveEntityAnalysisModels, entityAnalysisModel.Services.JubeEnvironment, entityAnalysisModel.Services.Log);
var context = extractor.CreateContext(dictionaryNoBoxing, entityAnalysisModelReprocessingRuleInstanceId);
context.EntityAnalysisModelInstanceEntryPayload.InvokeTaskPerformance.ComputeTimes.Parse = (int)(context.Stopwatch.ElapsedTicks * 1000000 / Stopwatch.Frequency);
return InvokeAsync(context);
}
private static async Task CheckAsyncAndInvokeContextAsync(bool async, Context.Context context)
{
if (async && context.EntityAnalysisModel.ConcurrentQueues.PendingEntityInvoke != null)
{
context.EntityAnalysisModel.Services.Log.Info(
$"HTTP Handler Entity: GUID payload {context.EntityAnalysisModelInstanceEntryPayload.EntityAnalysisModelInstanceEntryGuid} model id is {context.EntityAnalysisModel.Instance.Id} will start asynchronous invocation.");
EnqueueForAsyncInvocationOfContext(context, context.EntityAnalysisModel.ConcurrentQueues.PendingEntityInvoke);
}
else
{
if (context.EntityAnalysisModel.Services.Log.IsInfoEnabled)
{
context.EntityAnalysisModel.Services.Log.Info(
$"HTTP Handler Entity: GUID payload {context.EntityAnalysisModelInstanceEntryPayload.EntityAnalysisModelInstanceEntryGuid} model id is {context.EntityAnalysisModel.Instance.Id} will start synchronous invocation.");
}
await InvokeAsync(context).ConfigureAwait(false);
}
if (context.EntityAnalysisModel.Services.Log.IsInfoEnabled)
{
context.EntityAnalysisModel.Services.Log.Info(
$"HTTP Handler Entity: GUID payload {context.EntityAnalysisModelInstanceEntryPayload.EntityAnalysisModelInstanceEntryGuid} model id is {context.EntityAnalysisModel.Instance.Id} has finished model invocation.");
}
}
private static void CheckLengthGuardsForExceptions(MemoryStream inputStream, int maxBytes)
{
if (inputStream.Length == 0)
{
throw new ZeroBytesException();
}
if (inputStream.Length > maxBytes)
{
throw new ExceededBytesException();
}
}
private static void EnqueueForAsyncInvocationOfContext(Context.Context context, ConcurrentQueue<Context.Context> pendingEntityInvoke)
{
if (pendingEntityInvoke.Count >=
Int32.Parse(context.EntityAnalysisModel.Services.JubeEnvironment.AppSettings("MaximumModelInvokeAsyncQueue")))
{
throw new ExceededQueueLengthException();
}
context.Async = true;
pendingEntityInvoke.Enqueue(context);
var asyncInvocationCallbackToken = new AsyncInvocationCallbackToken
{
EntityAnalysisModelInstanceEntryGuid = context.EntityAnalysisModelInstanceEntryPayload.EntityAnalysisModelInstanceEntryGuid
};
context.JsonResult = BuildJsonResponses.BuildFullJson(asyncInvocationCallbackToken, context.EntityAnalysisModel.JsonSerializationHelper.ArchiveJsonSerializer);
}
public static async Task InvokeAsync(Context.Context context)
{
try
{
if (context.Log.IsInfoEnabled)
{
context.Log.Info(
$"Entity Invoke: GUID {context.EntityAnalysisModelInstanceEntryPayload.EntityAnalysisModelInstanceEntryGuid} has started invocation timer. " +
$"Will now update the reference date and check that it is not older than the latest stored, else exception.");
}
IncrementModelInvokeCounter(context);
await context.CheckIntegrityAndUpsertAsync(context.EntityAnalysisModel.Services.CacheService).ConfigureAwait(false);
if (context.Log.IsInfoEnabled)
{
context.Log.Info(
$"Entity Invoke: GUID {context.EntityAnalysisModelInstanceEntryPayload.EntityAnalysisModelInstanceEntryGuid} " +
$"has configured startup options. The model invocation counter is {context.EntityAnalysisModel.Counters.ModelInvokeCounter} and " +
$"reprocessing is set to {context.EntityAnalysisModelInstanceEntryPayload.EntityAnalysisModelReprocessingRuleInstanceId.HasValue}. Will now proceed" +
$" create the Invoke Context and execute Inline Functions. " +
$"Has updated reference date for model {context.EntityAnalysisModel.Instance.Id} to {context.EntityAnalysisModelInstanceEntryPayload.ReferenceDate}");
}
context.ExecuteInlineFunctions();
await context.ExecuteInlineScriptsAsync();
context.ExecuteGatewayRules();
if (context.EntityAnalysisModelInstanceEntryPayload.MatchedGatewayRule)
{
context.ExecuteCacheDbStorage(context.EntityAnalysisModel.Services.CacheService, context.EntityAnalysisModel.Collections.DistinctSearchKeys);
context.PendingReadTasks.Add(TaskHelper.MeasureTaskTimeAndMemoryAllocatedAsync(TaskType.SanctionsAsync, async () => await context.ExecuteSanctionsAsync().ConfigureAwait(false)));
context.PendingReadTasks.Add(TaskHelper.MeasureTaskTimeAndMemoryAllocatedAsync(TaskType.DictionaryKvPsAsync, async () => await context.ExecuteDictionaryKvPsAsync().ConfigureAwait(false)));
context.PendingReadTasks.Add(TaskHelper.MeasureTaskTimeAndMemoryAllocatedAsync(TaskType.TtlCountersAsync, async () => await context.ExecuteTtlCountersAsync().ConfigureAwait(false)));
context.PendingReadTasks.Add(TaskHelper.MeasureTaskTimeAndMemoryAllocatedAsync(TaskType.AbstractionRulesWithSearchKeysAsync, async () => await context.ExecuteAbstractionRulesWithSearchKeysAsync().ConfigureAwait(false)));
await context.WaitReadTasksAsync().ConfigureAwait(false);
context.ExecuteAbstractionRulesWithoutSearchKeys();
context.ExecuteAbstractionCalculations();
context.ExecuteExhaustiveAdaptation();
await context.ExecuteHttpAdaptationsAsync().ConfigureAwait(false);
await context.ExecuteActivationsAsync().ConfigureAwait(false);
}
await context.WaitWriteTasksAsync().ConfigureAwait(false);
await context.WriteResponseJsonAndQueueAsynchronousResponseMessageAsync(context.EntityAnalysisModel.Services.RabbitMqChannel).ConfigureAwait(false);
await context.ActivationRuleBuildArchivePayloadAsync().ConfigureAwait(false);
if (context.Log.IsInfoEnabled)
{
context.Log.Info(
$"Entity Invoke: GUID {context.EntityAnalysisModelInstanceEntryPayload.EntityAnalysisModelInstanceEntryGuid} and model {context.EntityAnalysisModel.Instance.Id} all model invocation processing has completed.");
}
}
catch (Exception ex) when (ex is not OperationCanceledException
&& ex is not ReferenceDateInFutureException
&& ex is not ExceededQueueLengthException
&& ex is not ZeroBytesException
&& ex is not ExceededBytesException)
{
context.Log.Error(
$"Entity Invoke: {context.EntityAnalysisModel.Instance.Id} has created a general error as {ex}.");
}
}
private static void IncrementModelInvokeCounter(Context.Context context)
{
context.EntityAnalysisModel.Counters.ModelInvokeCounter += 1;
}
}
}