Files
jube-fork/Jube.App/Controllers/Repository/EntityAnalysisModelRequestXPathController.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

315 lines
11 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.Repository
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using AutoMapper;
using Code;
using Data.Context;
using Data.Poco;
using Data.Repository;
using Dto;
using DynamicEnvironment;
using FluentValidation;
using FluentValidation.Results;
using log4net;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Validators;
[Route("api/[controller]")]
[Produces("application/json")]
[Authorize]
public class EntityAnalysisModelRequestXPathController : Controller
{
private readonly DbContext dbContext;
private readonly ILog log;
private readonly IMapper mapper;
private readonly PermissionValidation permissionValidation;
private readonly EntityAnalysisModelRequestXPathRepository repository;
private readonly string userName;
private readonly IValidator<EntityAnalysisModelRequestXPathDto> validator;
public EntityAnalysisModelRequestXPathController(ILog log,
IHttpContextAccessor httpContextAccessor, DynamicEnvironment dynamicEnvironment)
{
if (httpContextAccessor.HttpContext?.User.Identity != null)
{
userName = httpContextAccessor.HttpContext.User.Identity.Name;
}
this.log = log;
dbContext = DataConnectionDbContext.GetResilientDbContextDataConnection(dynamicEnvironment.AppSettings("ConnectionString"), log);
permissionValidation = new PermissionValidation(dbContext, userName, log);
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<EntityAnalysisModelRequestXPathDto, EntityAnalysisModelRequestXpath>();
cfg.CreateMap<EntityAnalysisModelRequestXpath, EntityAnalysisModelRequestXPathDto>();
});
mapper = new Mapper(config);
repository = new EntityAnalysisModelRequestXPathRepository(dbContext, userName);
validator = new EntityAnalysisModelRequestXPathDtoValidator(repository);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
dbContext.Close();
dbContext.Dispose();
}
base.Dispose(disposing);
}
[HttpGet]
public async Task<ActionResult<List<EntityAnalysisModelRequestXPathDto>>> GetAsync(CancellationToken token = default)
{
try
{
if (!permissionValidation.Validate(new[]
{
7
}))
{
return Forbid();
}
return Ok(mapper.Map<List<EntityAnalysisModelRequestXPathDto>>(await repository.GetAsync(token)));
}
catch (Exception e)
{
log.Error(e);
return StatusCode(500);
}
}
[HttpGet("ByEntityAnalysisModelId/{entityAnalysisModelId:int}")]
public async Task<ActionResult<List<EntityAnalysisModelRequestXPathDto>>> GetByEntityAnalysisModelIdAsync(
int entityAnalysisModelId, CancellationToken token = default)
{
try
{
if (!permissionValidation.Validate(new[]
{
7, 13
}))
{
return Forbid();
}
return Ok(mapper.Map<List<EntityAnalysisModelRequestXPathDto>>(
await repository.GetByEntityAnalysisModelIdOrderByIdAsync(entityAnalysisModelId, token).ConfigureAwait(false)));
}
catch (Exception e)
{
log.Error(e);
return StatusCode(500);
}
}
[HttpGet("ByCasesWorkflowId/{casesWorkflowId:int}")]
public async Task<ActionResult<List<EntityAnalysisModelRequestXPathDto>>> GetByCasesWorkflowIdAsync(int casesWorkflowId, CancellationToken token = default)
{
try
{
if (!permissionValidation.Validate(new[]
{
7
}))
{
return Forbid();
}
return Ok(mapper.Map<List<EntityAnalysisModelRequestXPathDto>>(
await repository.GetByCasesWorkflowIdAsync(casesWorkflowId, token)));
}
catch (Exception e)
{
log.Error(e);
return StatusCode(500);
}
}
[HttpGet("BySuppressionKey")]
public async Task<ActionResult<List<EntityAnalysisModelRequestXPathDto>>> GetBySuppressionKeyAsync(CancellationToken token = default)
{
try
{
if (!permissionValidation.Validate(new[]
{
2
}))
{
return Forbid();
}
return Ok(mapper.Map<List<EntityAnalysisModelRequestXPathDto>>(await repository.GetBySuppressionKeysAsync(token)));
}
catch (Exception e)
{
log.Error(e);
return StatusCode(500);
}
}
[HttpGet("ByEntityAnalysisModelId/{entityAnalysisModelId:int}/ByStringIntegerFloatDataType")]
public async Task<ActionResult<List<EntityAnalysisModelRequestXPathDto>>> GetByEntityAnalysisModelIdByDataTypeAsync(
int entityAnalysisModelId, int dataTypeId, CancellationToken token = default)
{
try
{
if (!permissionValidation.Validate(new[]
{
7, 12
}))
{
return Forbid();
}
return Ok(mapper.Map<List<EntityAnalysisModelRequestXPathDto>>(
await repository.GetByEntityAnalysisModelIdByDataTypeAsync(entityAnalysisModelId, token, 1, 2, 3)));
}
catch (Exception e)
{
log.Error(e);
return StatusCode(500);
}
}
[HttpGet("{id:int}")]
public async Task<ActionResult<EntityAnalysisModelRequestXPathDto>> GetByIdAsync(int id, CancellationToken token = default)
{
try
{
if (!permissionValidation.Validate(new[]
{
7
}))
{
return Forbid();
}
return Ok(mapper.Map<EntityAnalysisModelRequestXPathDto>(await repository.GetByIdAsync(id, token)));
}
catch (Exception e)
{
log.Error(e);
return StatusCode(500);
}
}
[HttpPost]
[ProducesResponseType(typeof(EntityAnalysisModelRequestXPathDto), (int)HttpStatusCode.OK)]
[ProducesResponseType(typeof(ValidationResult), (int)HttpStatusCode.BadRequest)]
public async Task<ActionResult<EntityAnalysisModelRequestXPathDto>> CreateAsync(
[FromBody] EntityAnalysisModelRequestXPathDto model, CancellationToken token = default)
{
try
{
if (!permissionValidation.Validate(new[]
{
7
}))
{
return Forbid();
}
var results = await validator.ValidateAsync(model, token);
if (results.IsValid)
{
return Ok(await repository.InsertIncrementCacheIndexIdAsync(mapper.Map<EntityAnalysisModelRequestXpath>(model), token));
}
return BadRequest(results);
}
catch (Exception e)
{
log.Error(e);
return StatusCode(500);
}
}
[HttpPut]
[ProducesResponseType(typeof(EntityAnalysisModelRequestXPathDto), (int)HttpStatusCode.OK)]
[ProducesResponseType(typeof(ValidationResult), (int)HttpStatusCode.BadRequest)]
public async Task<ActionResult<EntityAnalysisModelRequestXPathDto>> UpdateAsync(
[FromBody] EntityAnalysisModelRequestXPathDto model, CancellationToken token = default)
{
try
{
if (!permissionValidation.Validate(new[]
{
7
}))
{
return Forbid();
}
var results = await validator.ValidateAsync(model, token);
if (results.IsValid)
{
return Ok(await repository.UpdateAsync(mapper.Map<EntityAnalysisModelRequestXpath>(model), token));
}
return BadRequest(results);
}
catch (KeyNotFoundException)
{
return StatusCode(204);
}
catch (Exception e)
{
log.Error(e);
return StatusCode(500);
}
}
[HttpDelete]
[Route("{id:int}")]
public async Task<ActionResult<List<EntityAnalysisModelRequestXPathDto>>> DeleteAsync(int id, CancellationToken token = default)
{
try
{
if (!permissionValidation.Validate(new[]
{
7
}))
{
return Forbid();
}
await repository.DeleteAsync(id, token);
return Ok();
}
catch (KeyNotFoundException)
{
return StatusCode(204);
}
catch (Exception e)
{
log.Error(e);
return StatusCode(500);
}
}
}
}