Files
jube-fork/Jube.App/Controllers/Invoke/InvokeController.cs
T
richard-churchman 62f33221b6 Resiliency, Database Security, Bug Fixes and Observability:
* 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.
2026-03-08 18:31:03 +02:00

459 lines
19 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.App.Controllers.Invoke
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Cache.Redis.Callback;
using Data.Extension;
using Dto;
using DynamicEnvironment;
using Engine;
using Engine.BackgroundTasks.TaskStarters.Models;
using Engine.EntityAnalysisModelInvoke;
using Engine.EntityAnalysisModelInvoke.Exceptions;
using Engine.EntityAnalysisModelManager.EntityAnalysisModel;
using Engine.Exhaustive.Extensions;
using Engine.Sanctions;
using FluentValidation.Results;
using log4net;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using SanctionEntryDto=Dto.SanctionEntryDto;
[Route("api/[controller]")]
[Produces("application/json")]
public class InvokeController : Controller
{
private readonly DynamicEnvironment dynamicEnvironment;
private readonly Engine engine;
private readonly ILog log;
public InvokeController(ILog log, DynamicEnvironment dynamicEnvironment,
Engine engine = null)
{
this.engine = engine;
this.log = log;
this.dynamicEnvironment = dynamicEnvironment;
if (this.engine != null)
{
Interlocked.Increment(ref this.engine.Context.Counters.HttpCounterAllRequests);
}
}
[HttpGet("EntityAnalysisModel/Callback/{guid:Guid}")]
[ProducesResponseType(typeof(ValidationResult), (int)HttpStatusCode.BadRequest)]
public async Task<ActionResult> EntityAnalysisModelCallbackAsync(Guid guid, int? timeout, CancellationToken token = default)
{
try
{
if (!dynamicEnvironment.AppSettings("EnablePublicInvokeController")
.Equals("True", StringComparison.OrdinalIgnoreCase))
{
return await Task.FromResult<ActionResult>(Forbid()).ConfigureAwait(false);
}
Interlocked.Increment(ref engine.Context.Counters.HttpCounterCallback);
var tcs = engine.Context.Services.CacheService.CacheCallbackPublishSubscribe.Callbacks.GetOrAdd(guid, _ => new TaskCompletionSource<Callback>(TaskCreationOptions.RunContinuationsAsynchronously));
var callback = await tcs.Task.WaitAsync(TimeSpan.FromSeconds(timeout ?? 30000), token);
await engine.Context.Services.CacheService
.CacheCallbackPublishSubscribe
.DeleteAsync(guid, token).ConfigureAwait(false);
return File(callback.Payload, "application/json");
}
catch (TimeoutException)
{
return StatusCode(408);
}
catch (Exception ex)
{
log.Error($"Callback Fetch: Has seen an error as {ex}. Returning 500.");
Interlocked.Increment(ref engine.Context.Counters.HttpCounterCallback);
return await Task.FromResult<ActionResult>(StatusCode(500)).ConfigureAwait(false);
}
}
[HttpGet("Sanction")]
[ProducesResponseType(typeof(ValidationResult), (int)HttpStatusCode.BadRequest)]
public Task<ActionResult<List<SanctionEntryDto>>> SanctionAsync(string multiPartString, int distance)
{
try
{
if (!dynamicEnvironment.AppSettings("EnablePublicInvokeController")
.Equals("True", StringComparison.OrdinalIgnoreCase))
{
return Task.FromResult<ActionResult<List<SanctionEntryDto>>>(Forbid());
}
if (!engine.Context.Ready)
{
return Task.FromResult<ActionResult<List<SanctionEntryDto>>>(StatusCode(503));
}
Interlocked.Increment(ref engine.Context.Counters.HttpCounterSanction);
if (log.IsInfoEnabled)
{
log.Info(
$"Sanction Fetch: Reached Sanction Get controller with distance of {distance} and string of {multiPartString}.");
}
return Task.FromResult<ActionResult<List<SanctionEntryDto>>>(
LevenshteinDistance.CheckMultipartString(multiPartString, distance, engine.Context.Sanctions.SanctionsEntries)
.Select(sanctionEntryReturn => new SanctionEntryDto
{
Reference = sanctionEntryReturn.SanctionEntry.SanctionEntryReference,
Value = String.Join(' ', sanctionEntryReturn.SanctionEntry.SanctionElementValue),
Source = engine.Context.Sanctions.SanctionsSources.TryGetValue(sanctionEntryReturn.SanctionEntry
.SanctionEntrySourceId, out var source)
? source.Name
: "Missing",
Distance = sanctionEntryReturn.LevenshteinDistance,
Id = sanctionEntryReturn.SanctionEntry.SanctionEntryId
})
.ToList());
}
catch (Exception ex)
{
log.Error($"Sanction Fetch: Has seen an error as {ex}. Returning 500.");
Interlocked.Increment(ref engine.Context.Counters.HttpCounterAllError);
return Task.FromResult<ActionResult<List<SanctionEntryDto>>>(StatusCode(500));
}
}
[HttpPut("Archive/Tag")]
[ProducesResponseType(typeof(ValidationResult), (int)HttpStatusCode.BadRequest)]
public Task<ActionResult> EntityAnalysisModelInstanceEntryGuidAsync([FromBody] TagRequestDto model)
{
try
{
if (!dynamicEnvironment.AppSettings("EnablePublicInvokeController")
.Equals("True", StringComparison.OrdinalIgnoreCase))
{
return Task.FromResult<ActionResult>(Forbid());
}
if (!engine.Context.Ready)
{
return Task.FromResult<ActionResult>(StatusCode(503));
}
if (log.IsInfoEnabled)
{
log.Info(
$"Tagging: Controller has Put request with guid {model.EntityAnalysisModelInstanceEntryGuid}," +
$" name {model.Name} and value {model.Value}.");
}
Interlocked.Increment(ref engine.Context.Counters.HttpCounterTag);
var entityAnalysisModelGuid = Guid.Parse(model.EntityAnalysisModelGuid);
foreach (var (_, value) in
from modelKvp in engine.Context.Tasks.EntityAnalysisModelManager.Context.EntityAnalysisModels.ActiveEntityAnalysisModels
where entityAnalysisModelGuid == modelKvp.Value.Instance.Guid
select modelKvp)
{
if (value.Collections.EntityAnalysisModelTags.Find(w => w.Name == model.Name) == null)
{
return Task.FromResult<ActionResult>(BadRequest());
}
var tag = new Tag
{
Name = model.Name,
Value = model.Value,
EntityAnalysisModelInstanceEntryGuid = Guid.Parse(model.EntityAnalysisModelInstanceEntryGuid),
EntityAnalysisModelId = value.Instance.Id
};
if (log.IsInfoEnabled)
{
log.Info(
"HTTP Handler Entity: GUID matched for Requested Model GUID " +
$"{tag.EntityAnalysisModelInstanceEntryGuid} and model {tag.EntityAnalysisModelId}.");
}
engine.Context.ConcurrentQueues.PendingTagging.Enqueue(tag);
if (log.IsInfoEnabled)
{
log.Info(
"Tagging: Controller has put tag in queue with guid " +
$"{tag.EntityAnalysisModelInstanceEntryGuid}, model {tag.EntityAnalysisModelId}, " +
$"name {model.Name} and value {model.Value}. Returning Ok.");
}
return Task.FromResult<ActionResult>(Ok());
}
return Task.FromResult<ActionResult>(NotFound());
}
catch (Exception ex)
{
log.Error(
"Tagging: An error has been created while tagging guid " +
$"{model.EntityAnalysisModelInstanceEntryGuid} " +
$"and model {model.EntityAnalysisModelGuid} as {ex}.");
engine.Context.Counters.HttpCounterAllError += 1;
return Task.FromResult<ActionResult>(StatusCode(500));
}
}
#pragma warning disable ASP0018
// ReSharper disable once RouteTemplates.RouteParameterIsNotPassedToMethod
[HttpPost("EntityAnalysisModel/{guid}")]
// ReSharper disable once RouteTemplates.RouteParameterIsNotPassedToMethod
[HttpPost("EntityAnalysisModel/{guid}/{async}")]
#pragma warning restore ASP0018
[ProducesResponseType(typeof(ValidationResult), (int)HttpStatusCode.BadRequest)]
// ReSharper disable once RouteTemplates.MethodMissingRouteParameters
public async Task<ActionResult> EntityAnalysisModelGuidAsync()
{
try
{
if (!dynamicEnvironment.AppSettings("EnablePublicInvokeController")
.Equals("True", StringComparison.OrdinalIgnoreCase))
{
return Forbid();
}
if (engine.Context is not { Ready: true })
{
return StatusCode(503);
}
Interlocked.Increment(ref engine.Context.Counters.HttpCounterModel);
var ms = new MemoryStream();
await Request.Body.CopyToAsync(ms).ConfigureAwait(false);
try
{
var guid = Guid.Parse(Request.RouteValues["guid"].AsString());
var async = false;
if (Request.RouteValues.ContainsKey("async"))
{
async = Request.RouteValues["async"].AsString()
.Equals("Async", StringComparison.OrdinalIgnoreCase);
Interlocked.Increment(ref engine.Context.Counters.HttpCounterModelAsync);
}
EntityAnalysisModel entityAnalysisModel = null;
foreach (var (_, value) in
from modelKvp in engine.Context.Tasks.EntityAnalysisModelManager.Context.EntityAnalysisModels.ActiveEntityAnalysisModels
where guid == modelKvp.Value.Instance.Guid
select modelKvp)
{
entityAnalysisModel = value;
if (log.IsInfoEnabled)
{
log.Info(
$"HTTP Handler Entity: GUID matched for Requested Model GUID {guid}. Model id is {entityAnalysisModel.Instance.Id}.");
}
break;
}
if (entityAnalysisModel != null)
{
if (log.IsInfoEnabled)
{
log.Info(
$"HTTP Handler Entity: GUID payload {guid} model id is {entityAnalysisModel.Instance.Id} will now begin payload parsing.");
}
if (Request.ContentLength != null)
{
try
{
var context = await EntityAnalysisModelInvoke.InvokeAsync(
entityAnalysisModel,
ms, Int32.Parse(dynamicEnvironment.AppSettings("MaxInvokeControllerRequestBytes")),
async).ConfigureAwait(false);
var bytes = context.EntityAnalysisModelInstanceEntryPayload.ResponseJson.Length > 0 ? context.EntityAnalysisModelInstanceEntryPayload.ResponseJson : context.EntityAnalysisModelInstanceEntryPayload.ArchiveJson;
Response.ContentType = "application/json";
Response.ContentLength = bytes.Length;
await Response.Body.WriteAsync(bytes);
}
catch (ExceededBytesException)
{
return BadRequest("Exceeded the maximum allowed bytes in POST body.");
}
catch (ExceededQueueLengthException)
{
return StatusCode(429, "Too many asynchronous requests in the queue.");
}
catch (ReferenceDateInFutureException)
{
return BadRequest("Reference Date can't be in the future.");
}
catch (ZeroBytesException)
{
return BadRequest("Empty POST body.");
}
}
if (log.IsInfoEnabled)
{
log.Info(
"HTTP Handler Entity: Json content body is zero.");
}
return BadRequest("Content body is zero length.");
}
if (log.IsInfoEnabled)
{
log.Info(
$"HTTP Handler Entity: Could not locate the model for Guid {guid}.");
}
return NotFound();
}
catch (Exception)
{
return NotFound();
}
}
catch (Exception ex)
{
log.Error(
$"HTTP Handler Entity: Error as {ex}. Returning 500.");
if (engine != null)
{
engine.Context.Counters.HttpCounterAllError += 1;
}
return StatusCode(500);
}
}
#pragma warning disable ASP0018
[HttpPost("ExhaustiveSearchInstance/{guid}")]
#pragma warning restore ASP0018
// ReSharper disable once RouteTemplates.MethodMissingRouteParameters
[ProducesResponseType(typeof(ValidationResult), (int)HttpStatusCode.BadRequest)]
public async Task<ActionResult<double>> ExhaustiveSearchInstanceAsync()
{
try
{
if (!dynamicEnvironment.AppSettings("EnablePublicInvokeController")
.Equals("True", StringComparison.OrdinalIgnoreCase))
{
return Forbid();
}
if (!engine.Context.Ready)
{
return StatusCode(503);
}
Interlocked.Increment(ref engine.Context.Counters.HttpCounterExhaustive);
var ms = new MemoryStream();
await Request.Body.CopyToAsync(ms).ConfigureAwait(false);
var guid = Request.RouteValues["guid"].AsString();
if (log.IsInfoEnabled)
{
log.Info($"Exhaustive Recall: Recall received for {guid}. Invoking handler.");
}
var value = Math.Round(engine.Context.RecallExhaustive(
Guid.Parse(guid),
JObject.Parse(Encoding.UTF8.GetString(ms.ToArray()))), 2);
if (log.IsInfoEnabled)
{
log.Info($"Exhaustive Recall: Has invoked the handler and returned a value of {value}. Returning.");
}
return value;
}
catch (Exception ex)
{
log.Error($"Exhaustive Recall: An error has been raised as {ex}. Returning 500.");
engine.Context.Counters.HttpCounterAllError += 1;
return StatusCode(500);
}
}
[HttpPost("ExampleFraudScoreLocalEndpoint")]
[ProducesResponseType(typeof(ValidationResult), (int)HttpStatusCode.BadRequest)]
public async Task<ActionResult<double>> ExampleFraudScoreLocalEndpointAsync()
{
try
{
if (!dynamicEnvironment.AppSettings("EnablePublicInvokeController")
.Equals("True", StringComparison.OrdinalIgnoreCase))
{
return Forbid();
}
var ms = new MemoryStream();
await Request.Body.CopyToAsync(ms).ConfigureAwait(false);
if (log.IsInfoEnabled)
{
log.Info("Example FraudScore Local Endpoint Recall: Recall received.");
}
var jObject = JObject.Parse(Encoding.UTF8.GetString(ms.ToArray()));
var responseCodeVolumeRatio = jObject.SelectToken("$.ResponseCodeEqual0Volume");
if (log.IsInfoEnabled)
{
log.Info($"Example FraudScore Local Endpoint Recall: Json parsed as {jObject}. " +
"This endpoint will just echo back the sqrt of the ResponseCodeVolumeRatio element." +
" More typically this would be an R endpoint and it would recall a variety of models.");
}
if (responseCodeVolumeRatio != null)
{
return Math.Sqrt(responseCodeVolumeRatio.ToObject<double>());
}
return 0;
}
catch (Exception ex)
{
log.Error(
$"Example FraudScore Local Endpoint Recall: An error has been raised as {ex}. Returning 500.");
return StatusCode(500);
}
}
}
}