mirror of
https://github.com/hanzoai/jube-fork.git
synced 2026-10-30 18:33:33 +00:00
* Implemented a wrapper library for Redis and Postgres clients using Polly retry to enhance durability during failover. Removed all direct client references across projects, replacing them with the new resilient libraries. Bulk changes were largely confined to the database context constructor, given the application's broad use of the Repository pattern and LINQ2DB. * Implemented a WAL log in Redis that stores JSON payloads pending commit to the Archive table as part of an asynchronous process. The WAL entry is removed once the commit completes. During graceful drain on SIGTERM, this provides an observability and recovery mechanism for transactions lost due to host failure or fatal termination. * Implemented a read-only reporting connection for all case management query functions and other backend functions with significant read overhead or security implications, enabling targeting of read replicas under read-only database users. Dynamic query functions have been handled carefully to ensure parameterised variables are always used. * Implemented a `MigrationConnectionString` environment variable to support a dedicated migration user, allowing the application and reporting to run under minimal permissions while still supporting the online upgrade process used in Jube Herd (Docker Swarm). * Added evaluation counters to Gateway and Activation Rule Counters, and ensured they are displayed in the Gateway Rules, Activation Rules, and Activation Rules pages — an important missing observability feature for gradual rule rollout assessment prior to taking decline or case creation steps. Also introduced model total response time counters throughout the invocation pipeline and updated the administration page accordingly. Made all response times throughout the system record in microseconds for consistency. * Updated `CookieOptions` to include the `Secure` flag having been flagged on CodeQL. * Fixed major bugs in fan-out queries across all Case Management entities caused by the recently released permissions functionality, where entities were duplicated when more than one user was present. * Fixed a long-standing issue with performance counter increments to use `Interlocked`, or custom locks in the case of date-based counters. * Fixed a bug in preservation import introduced during the `CacheIndexId` functionality, which failed due to a nested transaction. The import now bypasses `CacheIndexId` rekeying and reads it directly from the `.jemp` file, which was itself the correct original behaviour. * Fixed Payload Responses not being included in the response payload when response payload was selected in Request XPath. * Fixed the Report Table switch in Request XPath having no effect and not writing to the `ArchiveKeys` table. * Fixed the inability to edit Case Workflows in the user interface because of a minor JS typo in the key name. * Refactored notification dispatch to use async methods for all database calls. * Refactored the Postgres Query class to make better use of `using`/dispose patterns, moved connection creation to the constructor, and ensured consistent disposal. Extended the use of `using` dispose throughout all LINQ2DB queries outside the Repository pattern. * Some refactoring to use byte arrays rather than `MemoryStream` in serialisation of JSON Archive and response payloads. Eliminated duplication in Archive payload creation for case creation, given the payload now also exists in the WAL, and is created during invocation (not asynchronously as was the case). * Updated the composite index for `AddArchiveKeyTableIndex` in Baseline to use covering indexes ONLY, avoiding Postgres page lookups (noting this table exists solely as an access path to the Archive table via predication and join on `EntityAnalysisModelInstanceEntryGuid`). IMPORTANT NOTE: No migration provided for existing data. Any such index will need to be rebuilt manually to obtain this benefit. * Updated the completions controller and query to order fields by name ascending, with new repository methods to apply ordering server-side. * Updated the date format for Created Dates in the user interface to a more verbose and readable format, consistent with the rest of the system. * Removed legacy billing aggregation counter for response elevation, which is no longer a relevant concept. Renamed remaining billing-related counter fields for clarity. * Updated Dockerfile for the new resilience projects. * Fixed typo in TTL Counter Resolution page where hours was duplicated instead of minutes. * Implemented RedisBackplane environment variable to support SignalR with Redis in clustered environments. * Fixed loss of password, password expiry, and password created date during User Administration updates; added empty password check in authentication controller to raise an exception treated as user not found; fixed inability to change password on expiry; fixed password expiry date evaluation bug; moved increment password failure to capture all code paths. * Updated ExhaustiveSearchInstanceTrialInstanceVariable repository to use logical deletes instead of physical deletes, which are unsupported by the database user; updated MockArchive loading to occur only once since the data is static. * Updated default Log4NetLogLevel environment variable to WARN and updated documentation accordingly. * Fixed missing reference for Archive Keys during payload creation, as while they were being populated, the reference to it was missing, so they did not get stored.
328 lines
16 KiB
C#
328 lines
16 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.Extraction
|
|
{
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Diagnostics;
|
|
using System.IO;
|
|
using System.Text;
|
|
using Context;
|
|
using Data.Poco;
|
|
using Dictionary;
|
|
using DynamicEnvironment;
|
|
using EntityAnalysisModelManager.EntityAnalysisModel.Models.Models;
|
|
using Extensions.YourNamespace.Extensions;
|
|
using Helpers;
|
|
using log4net;
|
|
using Models.Payload.EntityAnalysisModelInstanceEntryPayload;
|
|
using Newtonsoft.Json.Linq;
|
|
using EntityAnalysisModel=EntityAnalysisModelManager.EntityAnalysisModel.EntityAnalysisModel;
|
|
|
|
public class EntityAnalysisModelJsonExtractor(
|
|
EntityAnalysisModel entityAnalysisModel,
|
|
Dictionary<int, EntityAnalysisModel> availableModels,
|
|
DynamicEnvironment environment,
|
|
ILog log)
|
|
{
|
|
public Context CreateContext(
|
|
MemoryStream inputStream)
|
|
{
|
|
var stopwatch = new Stopwatch();
|
|
stopwatch.Start();
|
|
|
|
var entityAnalysisModelInstanceEntryPayload = EntityAnalysisModelInstanceEntryPayloadHelpers.Create(entityAnalysisModel);
|
|
entityAnalysisModelInstanceEntryPayload.Payload = new DictionaryNoBoxing<string>(entityAnalysisModel.References.PayloadInitialSize);
|
|
|
|
var reportDatabaseValues = new List<ArchiveKey>();
|
|
entityAnalysisModelInstanceEntryPayload.ArchiveKeys = reportDatabaseValues;
|
|
|
|
var json = ParseJson(inputStream, entityAnalysisModel, entityAnalysisModelInstanceEntryPayload);
|
|
|
|
var (entryId, referenceDate) = ExtractEntryAndReferenceDate(json, entityAnalysisModel, entityAnalysisModelInstanceEntryPayload.Payload);
|
|
|
|
entityAnalysisModelInstanceEntryPayload.EntityInstanceEntryId = entryId;
|
|
entityAnalysisModelInstanceEntryPayload.ReferenceDate = referenceDate;
|
|
|
|
ProcessRequestXPaths(json, entityAnalysisModel, entityAnalysisModelInstanceEntryPayload, entityAnalysisModelInstanceEntryPayload.Payload, reportDatabaseValues, false, log);
|
|
|
|
return new Context
|
|
{
|
|
StartBytesUsed = GC.GetAllocatedBytesForCurrentThread(),
|
|
EntityAnalysisModel = entityAnalysisModel,
|
|
AvailableEntityAnalysisModels = availableModels,
|
|
EntityAnalysisModelInstanceEntryPayload = entityAnalysisModelInstanceEntryPayload,
|
|
Stopwatch = stopwatch,
|
|
Log = log,
|
|
Random = new Random(Environment.TickCount ^ Guid.NewGuid().GetHashCode()),
|
|
Environment = environment,
|
|
Async = false
|
|
};
|
|
}
|
|
|
|
private JObject ParseJson(MemoryStream inputStream, EntityAnalysisModel model,
|
|
EntityAnalysisModelInstanceEntryPayload payload)
|
|
{
|
|
if (inputStream.Length == 0)
|
|
{
|
|
log.Info($"Json to Context Extractor: GUID payload {payload.EntityAnalysisModelInstanceEntryGuid} model id is {model.Instance.Id} has zero content length.");
|
|
return null;
|
|
}
|
|
|
|
var json = JObject.Parse(Encoding.UTF8.GetString(inputStream.ToArray()));
|
|
|
|
log.Info($"Json to Context Extractor: GUID payload {payload.EntityAnalysisModelInstanceEntryGuid} model id is {model.Instance.Id} JSON parsed successfully.");
|
|
return json;
|
|
}
|
|
|
|
private (string entryId, DateTime referenceDate) ExtractEntryAndReferenceDate(
|
|
JObject json,
|
|
EntityAnalysisModel model,
|
|
DictionaryNoBoxing<string> payload)
|
|
{
|
|
var modelEntryValue = "";
|
|
var referenceDateValue = DateTime.Now;
|
|
JToken jToken;
|
|
|
|
try
|
|
{
|
|
jToken = json?.SelectToken(model.References.EntryXPath);
|
|
if (jToken != null)
|
|
{
|
|
modelEntryValue = jToken.ToString();
|
|
}
|
|
|
|
log.Info($"Json to Context Extractor: Entity {model.Instance.Id}: extracted entry via {model.References.EntryXPath} value {modelEntryValue}");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
log.Error($"Json to Context Extractor: Could not extract entry path {model.References.EntryXPath}: {ex.Message}");
|
|
}
|
|
|
|
try
|
|
{
|
|
switch (model.References.ReferenceDatePayloadLocationTypeId)
|
|
{
|
|
case 3:
|
|
referenceDateValue = DateTime.Now;
|
|
break;
|
|
|
|
default:
|
|
jToken = json?.SelectToken(model.References.ReferenceDateXpath);
|
|
if (jToken is { Type: JTokenType.Date })
|
|
{
|
|
referenceDateValue = Convert.ToDateTime(jToken);
|
|
}
|
|
else if (jToken != null && !DateTime.TryParse(jToken.ToString(), out referenceDateValue))
|
|
{
|
|
referenceDateValue = DateTime.Now;
|
|
}
|
|
break;
|
|
}
|
|
|
|
log.Info($"Json to Context Extractor: Entity {model.Instance.Id}: extracted reference date {referenceDateValue}");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
log.Error($"Json to Context Extractor: Could not extract reference date: {ex.Message}");
|
|
}
|
|
|
|
payload.TryAdd(model.References.ReferenceDateName, referenceDateValue);
|
|
payload.TryAdd(model.References.EntryName, modelEntryValue);
|
|
|
|
return (modelEntryValue, referenceDateValue);
|
|
}
|
|
|
|
private static void ProcessRequestXPaths(
|
|
JObject json,
|
|
EntityAnalysisModel entityAnalysisModel,
|
|
EntityAnalysisModelInstanceEntryPayload entityInstanceEntryPayloadStore,
|
|
DictionaryNoBoxing<string> payload,
|
|
List<ArchiveKey> reportDatabaseValues,
|
|
bool isReprocess,
|
|
ILog log)
|
|
{
|
|
if (entityAnalysisModel.Collections?.EntityAnalysisModelRequestXPaths == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
if (log.IsInfoEnabled)
|
|
{
|
|
log.Info($"Json to Context Extractor: GUID payload {entityInstanceEntryPayloadStore.EntityAnalysisModelInstanceEntryGuid} model id {entityAnalysisModel.Instance.Id} beginning request XPath extraction.");
|
|
}
|
|
|
|
foreach (var xPath in entityAnalysisModel.Collections.EntityAnalysisModelRequestXPaths)
|
|
{
|
|
try
|
|
{
|
|
if (payload.ContainsKey(xPath.Name))
|
|
{
|
|
if (log.IsInfoEnabled)
|
|
{
|
|
log.Info($"Json to Context Extractor: GUID payload {entityInstanceEntryPayloadStore.EntityAnalysisModelInstanceEntryGuid} duplicate key {xPath.Name} detected, skipping extraction.");
|
|
}
|
|
continue;
|
|
}
|
|
|
|
if (log.IsInfoEnabled)
|
|
{
|
|
log.Info($"Json to Context Extractor: GUID payload {entityInstanceEntryPayloadStore.EntityAnalysisModelInstanceEntryGuid} evaluating {xPath.Name} with path {xPath.XPath}.");
|
|
}
|
|
|
|
string value;
|
|
var defaultFallback = false;
|
|
|
|
try
|
|
{
|
|
value = json.SelectToken(xPath.XPath)?.ToString();
|
|
if (value == null)
|
|
{
|
|
value = xPath.DefaultValue;
|
|
defaultFallback = true;
|
|
}
|
|
}
|
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
|
{
|
|
value = xPath.DefaultValue;
|
|
defaultFallback = true;
|
|
|
|
if (log.IsInfoEnabled)
|
|
{
|
|
log.Info($"Json to Context Extractor: GUID payload {entityInstanceEntryPayloadStore.EntityAnalysisModelInstanceEntryGuid} XPath {xPath.XPath} failed: {ex.Message}. Using default {xPath.DefaultValue}.");
|
|
}
|
|
}
|
|
|
|
if (value == null)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
ProcessTypedInsertion(entityInstanceEntryPayloadStore,
|
|
xPath,
|
|
value,
|
|
defaultFallback,
|
|
payload,
|
|
reportDatabaseValues,
|
|
isReprocess,
|
|
log);
|
|
}
|
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
|
{
|
|
log.Error($"Json to Context Extractor: GUID payload {entityInstanceEntryPayloadStore.EntityAnalysisModelInstanceEntryGuid} unhandled error processing {xPath.Name}: {ex}");
|
|
}
|
|
}
|
|
}
|
|
|
|
private static void ProcessTypedInsertion(EntityAnalysisModelInstanceEntryPayload entityAnalysisModelInstanceEntryPayload,
|
|
EntityAnalysisModelRequestXPath xPath,
|
|
string value,
|
|
bool defaultFallback,
|
|
DictionaryNoBoxing<string> payload,
|
|
List<ArchiveKey> reportDatabaseValues,
|
|
bool isReprocess,
|
|
ILog log)
|
|
{
|
|
try
|
|
{
|
|
switch (xPath.DataTypeId)
|
|
{
|
|
case 1:
|
|
payload.TryAdd(xPath.Name, value);
|
|
reportDatabaseValues.AddArchiveKey(xPath, entityAnalysisModelInstanceEntryPayload, value, isReprocess: isReprocess);
|
|
|
|
log.Info($"Json to Context Extractor: GUID payload {entityAnalysisModelInstanceEntryPayload.EntityAnalysisModelInstanceEntryGuid} XPath {xPath.XPath} value {value} as string {(defaultFallback ? "is default" : String.Empty)}.");
|
|
|
|
break;
|
|
case 2:
|
|
if (Int32.TryParse(value, out var intVal))
|
|
{
|
|
payload.TryAdd(xPath.Name, intVal);
|
|
reportDatabaseValues.AddArchiveKey(xPath, entityAnalysisModelInstanceEntryPayload, valueInt: Int32.Parse(value), isReprocess: isReprocess);
|
|
|
|
log.Info($"Json to Context Extractor: GUID payload {entityAnalysisModelInstanceEntryPayload.EntityAnalysisModelInstanceEntryGuid} XPath {xPath.XPath} value {value} as integer {(defaultFallback ? "is default" : String.Empty)}.");
|
|
}
|
|
else
|
|
{
|
|
log.Info($"Json to Context Extractor: GUID payload {entityAnalysisModelInstanceEntryPayload.EntityAnalysisModelInstanceEntryGuid} XPath {xPath.XPath} value {value} as null integer {(defaultFallback ? "is default" : String.Empty)}.");
|
|
}
|
|
|
|
break;
|
|
case 4:
|
|
DateTime dateValue;
|
|
if (defaultFallback && Int32.TryParse(xPath.DefaultValue, out var daysBack))
|
|
{
|
|
dateValue = DateTime.Now.AddDays(-daysBack);
|
|
}
|
|
else if (!DateTime.TryParse(value, out dateValue))
|
|
{
|
|
dateValue = DateTime.Now;
|
|
}
|
|
|
|
payload.TryAdd(xPath.Name, dateValue);
|
|
reportDatabaseValues.AddArchiveKey(xPath, entityAnalysisModelInstanceEntryPayload, valueDate: dateValue, isReprocess: isReprocess);
|
|
|
|
log.Info($"Json to Context Extractor: GUID payload {entityAnalysisModelInstanceEntryPayload.EntityAnalysisModelInstanceEntryGuid} XPath {xPath.XPath} value {value} as datetime {(defaultFallback ? "is default" : String.Empty)}.");
|
|
|
|
break;
|
|
case 5:
|
|
var boolVal = value.Equals("true", StringComparison.OrdinalIgnoreCase) || value == "1";
|
|
payload.TryAdd(xPath.Name, boolVal);
|
|
reportDatabaseValues.AddArchiveKey(xPath, entityAnalysisModelInstanceEntryPayload, valueBool: boolVal, isReprocess: isReprocess);
|
|
|
|
log.Info($"Json to Context Extractor: GUID payload {entityAnalysisModelInstanceEntryPayload.EntityAnalysisModelInstanceEntryGuid} XPath {xPath.XPath} value {value} as boolean {(defaultFallback ? "is default" : String.Empty)}.");
|
|
|
|
break;
|
|
case 6:
|
|
case 7:
|
|
case 3:
|
|
if (Double.TryParse(value, out var dblVal))
|
|
{
|
|
payload.TryAdd(xPath.Name, dblVal);
|
|
reportDatabaseValues.AddArchiveKey(xPath, entityAnalysisModelInstanceEntryPayload, valueFloat: Double.Parse(value), isReprocess: isReprocess);
|
|
|
|
log.Info($"Json to Context Extractor: GUID payload {entityAnalysisModelInstanceEntryPayload.EntityAnalysisModelInstanceEntryGuid} XPath {xPath.XPath} value {value} as double {(defaultFallback ? "is default" : String.Empty)}.");
|
|
}
|
|
else
|
|
{
|
|
log.Info($"Json to Context Extractor: GUID payload {entityAnalysisModelInstanceEntryPayload.EntityAnalysisModelInstanceEntryGuid} XPath {xPath.XPath} value {value} as null double {(defaultFallback ? "is default" : String.Empty)}.");
|
|
}
|
|
break;
|
|
|
|
default:
|
|
payload.TryAdd(xPath.Name, value);
|
|
reportDatabaseValues.AddArchiveKey(xPath, entityAnalysisModelInstanceEntryPayload, value, isReprocess: isReprocess);
|
|
|
|
log.Info($"Json to Context Extractor: GUID payload {entityAnalysisModelInstanceEntryPayload.EntityAnalysisModelInstanceEntryGuid} XPath {xPath.XPath} value {value} as string {(defaultFallback ? "is default" : String.Empty)}.");
|
|
|
|
break;
|
|
}
|
|
|
|
if (log.IsInfoEnabled)
|
|
{
|
|
log.Info($"Json to Context Extractor: {entityAnalysisModelInstanceEntryPayload.EntityAnalysisModelInstanceEntryGuid} processed field {xPath.Name} of type {xPath.DataTypeId} with value {value}");
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
if (log.IsInfoEnabled)
|
|
{
|
|
log.Info($"Json to Context Extractor: {entityAnalysisModelInstanceEntryPayload.EntityAnalysisModelInstanceEntryGuid} error parsing {xPath.Name}: {ex.Message}. Defaulting to string insert.");
|
|
}
|
|
payload.TryAdd(xPath.Name, value);
|
|
}
|
|
}
|
|
}
|
|
}
|