Enhance inbound management by removing MaxClients property
CI / Backend (build + test) (push) Successful in 1m23s
CI / Frontend (lint + typecheck + build) (push) Successful in 34s

- Removed the MaxClients property from Inbound-related data models, including InboundDto and PublishInboundCommand.
- Updated related methods and handlers to reflect the removal of MaxClients, ensuring consistent behavior across the application.
- Adjusted API documentation and frontend components to remove references to MaxClients, streamlining the inbound publishing process.
- Enhanced logging in command handlers to handle node unavailability scenarios during user actions.
- Improved database schema and migrations to align with the updated data model.
This commit is contained in:
Leonid Pershin
2026-07-14 23:11:50 +03:00
parent bef3880593
commit 8f6807a456
34 changed files with 1150 additions and 77 deletions
@@ -11,7 +11,6 @@ public sealed record InboundDto(
int Port,
bool IsPublished,
string? DisplayName,
int? MaxClients,
IReadOnlyList<Guid> AllowedRoleIds,
DateTimeOffset? LastSyncAt
)
@@ -26,7 +25,6 @@ public sealed record InboundDto(
inbound.Port,
inbound.IsPublished,
inbound.DisplayName,
inbound.MaxClients,
inbound.AllowedRoleIds,
inbound.LastSyncAt
);
@@ -7,6 +7,5 @@ public sealed record PublishInboundCommand(
Guid InboundId,
bool IsPublished,
string? DisplayName,
IReadOnlyList<Guid> AllowedRoleIds,
int? MaxClients
IReadOnlyList<Guid> AllowedRoleIds
) : ICommand<Result<InboundDto>>;
@@ -22,7 +22,7 @@ public sealed class PublishInboundCommandHandler(IAppDbContext dbContext, ICurre
return Result.Failure<InboundDto>(InboundErrors.NotFound);
if (command.IsPublished)
inbound.Publish(command.DisplayName, command.AllowedRoleIds, command.MaxClients);
inbound.Publish(command.DisplayName, command.AllowedRoleIds);
else
inbound.Unpublish();
@@ -7,6 +7,5 @@ public sealed class PublishInboundCommandValidator : AbstractValidator<PublishIn
public PublishInboundCommandValidator()
{
RuleFor(x => x.DisplayName).MaximumLength(100);
RuleFor(x => x.MaxClients).GreaterThan(0).When(x => x.MaxClients.HasValue);
}
}
@@ -1,7 +1,9 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Common.Messaging;
using PnvPanel.Application.Common.Models;
using PnvPanel.Application.Configs;
using PnvPanel.Domain.Audit;
using PnvPanel.Domain.Configs;
@@ -13,7 +15,8 @@ public sealed class DeleteUserCommandHandler(
IIdentityService identityService,
IXuiPanelGateway gateway,
ITelegramNotifier telegramNotifier,
ICurrentUser currentUser
ICurrentUser currentUser,
ILogger<DeleteUserCommandHandler> logger
) : ICommandHandler<DeleteUserCommand, Result>
{
public async Task<Result> Handle(DeleteUserCommand command, CancellationToken cancellationToken)
@@ -37,7 +40,8 @@ public sealed class DeleteUserCommandHandler(
.FirstOrDefaultAsync(n => n.Id == inbound.NodeId, cancellationToken);
if (inbound is not null && node is not null)
await gateway.RemoveClientAsync(
{
var removeResult = await gateway.RemoveClientAsync(
node,
inbound.RemoteInboundId,
config.ClientExternalId,
@@ -45,6 +49,23 @@ public sealed class DeleteUserCommandHandler(
cancellationToken
);
if (!removeResult.IsSuccess)
{
// Нода недоступна — прерываем удаление целиком, не трогая учётку/уже
// просмотренные конфиги: иначе после удаления AppUser отозвать оставшиеся
// клиенты в 3x-ui будет уже не от чего (некому будет принадлежать конфиг).
// Админ может повторить DeleteUser позже, когда нода отойдёт.
logger.LogWarning(
"Failed to remove client for config {ConfigId} on node {NodeId} while deleting user {UserId}: {Error}",
config.Id,
node.Id,
command.UserId,
removeResult.Error
);
return Result.Failure(ConfigErrors.NodeUnavailable);
}
}
config.Revoke();
}
@@ -1,4 +1,5 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Common.Messaging;
using PnvPanel.Application.Common.Models;
@@ -13,7 +14,8 @@ public sealed class ForceRevokeConfigCommandHandler(
IXuiPanelGateway gateway,
IRealtimeNotifier notifier,
ITelegramNotifier telegramNotifier,
ICurrentUser currentUser
ICurrentUser currentUser,
ILogger<ForceRevokeConfigCommandHandler> logger
) : ICommandHandler<ForceRevokeConfigCommand, Result>
{
public async Task<Result> Handle(
@@ -41,7 +43,8 @@ public sealed class ForceRevokeConfigCommandHandler(
.FirstOrDefaultAsync(n => n.Id == inbound.NodeId, cancellationToken);
if (inbound is not null && node is not null)
await gateway.RemoveClientAsync(
{
var removeResult = await gateway.RemoveClientAsync(
node,
inbound.RemoteInboundId,
config.ClientExternalId,
@@ -49,6 +52,18 @@ public sealed class ForceRevokeConfigCommandHandler(
cancellationToken
);
if (!removeResult.IsSuccess)
{
logger.LogWarning(
"Failed to remove client for config {ConfigId} on node {NodeId} during force-revoke: {Error}",
config.Id,
node.Id,
removeResult.Error
);
return Result.Failure(ConfigErrors.NodeUnavailable);
}
}
config.Revoke();
await notifier.NotifyConfigStatusChangedAsync(
config.UserId,
@@ -1,7 +1,9 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Common.Messaging;
using PnvPanel.Application.Common.Models;
using PnvPanel.Application.Configs;
using PnvPanel.Domain.Configs;
namespace PnvPanel.Application.Auth.DeleteMyAccount;
@@ -10,7 +12,8 @@ public sealed class DeleteMyAccountCommandHandler(
IAppDbContext dbContext,
IIdentityService identityService,
IXuiPanelGateway gateway,
ICurrentUser currentUser
ICurrentUser currentUser,
ILogger<DeleteMyAccountCommandHandler> logger
) : ICommandHandler<DeleteMyAccountCommand, Result>
{
public async Task<Result> Handle(
@@ -37,7 +40,8 @@ public sealed class DeleteMyAccountCommandHandler(
.FirstOrDefaultAsync(n => n.Id == inbound.NodeId, cancellationToken);
if (inbound is not null && node is not null)
await gateway.RemoveClientAsync(
{
var removeResult = await gateway.RemoveClientAsync(
node,
inbound.RemoteInboundId,
config.ClientExternalId,
@@ -45,6 +49,21 @@ public sealed class DeleteMyAccountCommandHandler(
cancellationToken
);
if (!removeResult.IsSuccess)
{
// Прерываем самоудаление целиком — иначе после удаления учётки отозвать
// оставшиеся клиенты в 3x-ui будет уже не от чего. Пользователь может повторить.
logger.LogWarning(
"Failed to remove client for config {ConfigId} on node {NodeId} while user {UserId} deletes own account: {Error}",
config.Id,
node.Id,
userId,
removeResult.Error
);
return Result.Failure(ConfigErrors.NodeUnavailable);
}
}
config.Revoke();
}
@@ -1,5 +1,6 @@
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Common.Messaging;
using PnvPanel.Application.Common.Models;
namespace PnvPanel.Application.Common.Behaviors;
@@ -19,7 +20,12 @@ public sealed class UnitOfWorkBehavior<TRequest, TResponse>(IAppDbContext dbCont
)
{
var response = await next();
await dbContext.SaveChangesAsync(cancellationToken);
// Не коммитим мутации, сделанные до отказа хендлера (например Approve() до фейла
// последующего шага) — иначе в БД закрепляется частичное/противоречивое состояние.
if (response is not Result { IsSuccess: false })
await dbContext.SaveChangesAsync(cancellationToken);
return response;
}
}
@@ -25,4 +25,9 @@ public static class ConfigErrors
);
public static readonly Error NotFound = Error.NotFound("Configs.NotFound", "Конфиг не найден.");
public static readonly Error NodeUnavailable = Error.Failure(
"Configs.NodeUnavailable",
"Сервер временно недоступен. Попробуйте повторить операцию позже."
);
}
@@ -4,6 +4,7 @@ using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Common.Messaging;
using PnvPanel.Application.Common.Models;
using PnvPanel.Domain.Configs;
using PnvPanel.Domain.Nodes;
namespace PnvPanel.Application.Configs.Create;
@@ -39,7 +40,7 @@ public sealed class CreateVpnConfigCommandHandler(
var node = await dbContext
.Nodes.AsNoTracking()
.FirstOrDefaultAsync(n => n.Id == inbound.NodeId, cancellationToken);
if (node is null || !node.IsEnabled)
if (node is null || !node.IsEnabled || node.Status == NodeStatus.Offline)
return Result.Failure<VpnConfigDto>(ConfigErrors.NodeDisabled);
var config = VpnConfig.Create(userId, inbound.Id, inbound.Protocol, command.Label);
@@ -1,4 +1,5 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PnvPanel.Application.Auth;
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Common.Messaging;
@@ -9,7 +10,8 @@ namespace PnvPanel.Application.Configs.Edit;
public sealed class EditVpnConfigCommandHandler(
IAppDbContext dbContext,
IXuiPanelGateway gateway,
ICurrentUser currentUser
ICurrentUser currentUser,
ILogger<EditVpnConfigCommandHandler> logger
) : ICommandHandler<EditVpnConfigCommand, Result<VpnConfigDto>>
{
public async Task<Result<VpnConfigDto>> Handle(
@@ -35,23 +37,36 @@ public sealed class EditVpnConfigCommandHandler(
if (command.Label is not null)
{
config.Rename(command.Label);
var node = await dbContext
.Nodes.AsNoTracking()
.FirstOrDefaultAsync(n => n.Id == inbound.NodeId, cancellationToken);
if (node is not null)
{
await gateway.UpdateClientAsync(
var updateResult = await gateway.UpdateClientAsync(
node,
inbound.RemoteInboundId,
config.ClientExternalId,
config.Protocol,
config.Label ?? config.ClientEmail,
command.Label,
enable: true,
cancellationToken
);
if (!updateResult.IsSuccess)
{
// Нода недоступна — не переименовываем локально, иначе метка разойдётся
// с тем, что реально хранится в 3x-ui. Пользователь может повторить.
logger.LogWarning(
"Failed to rename client for config {ConfigId} on node {NodeId}: {Error}",
config.Id,
node.Id,
updateResult.Error
);
return Result.Failure<VpnConfigDto>(ConfigErrors.NodeUnavailable);
}
}
config.Rename(command.Label);
}
return Result.Success(VpnConfigDto.FromDomain(config, inbound));
@@ -1,4 +1,5 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PnvPanel.Application.Auth;
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Common.Messaging;
@@ -11,7 +12,8 @@ public sealed class RevokeVpnConfigCommandHandler(
IAppDbContext dbContext,
IXuiPanelGateway gateway,
IRealtimeNotifier notifier,
ICurrentUser currentUser
ICurrentUser currentUser,
ILogger<RevokeVpnConfigCommandHandler> logger
) : ICommandHandler<RevokeVpnConfigCommand, Result>
{
public async Task<Result> Handle(
@@ -42,7 +44,8 @@ public sealed class RevokeVpnConfigCommandHandler(
.FirstOrDefaultAsync(n => n.Id == inbound.NodeId, cancellationToken);
if (inbound is not null && node is not null)
await gateway.RemoveClientAsync(
{
var removeResult = await gateway.RemoveClientAsync(
node,
inbound.RemoteInboundId,
config.ClientExternalId,
@@ -50,6 +53,20 @@ public sealed class RevokeVpnConfigCommandHandler(
cancellationToken
);
if (!removeResult.IsSuccess)
{
// Нода недоступна/сбой панели — не помечаем конфиг Revoked локально, иначе БД
// разойдётся с реальным состоянием клиента в 3x-ui. Пользователь может повторить.
logger.LogWarning(
"Failed to remove client for config {ConfigId} on node {NodeId}: {Error}",
config.Id,
node.Id,
removeResult.Error
);
return Result.Failure(ConfigErrors.NodeUnavailable);
}
}
config.Revoke();
await notifier.NotifyConfigStatusChangedAsync(
userId,