Fix backtest count

This commit is contained in:
2025-11-09 14:00:36 +07:00
parent 2ecd4a6306
commit b1cd01bf9b
5 changed files with 119 additions and 2 deletions

View File

@@ -36,6 +36,7 @@ public class BacktestController : BaseController
private readonly IMoneyManagementService _moneyManagementService;
private readonly IGeneticService _geneticService;
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly ILogger<BacktestController> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="BacktestController"/> class.
@@ -54,7 +55,8 @@ public class BacktestController : BaseController
IMoneyManagementService moneyManagementService,
IGeneticService geneticService,
IUserService userService,
IServiceScopeFactory serviceScopeFactory) : base(userService)
IServiceScopeFactory serviceScopeFactory,
ILogger<BacktestController> logger) : base(userService)
{
_hubContext = hubContext;
_backtester = backtester;
@@ -62,6 +64,7 @@ public class BacktestController : BaseController
_moneyManagementService = moneyManagementService;
_geneticService = geneticService;
_serviceScopeFactory = serviceScopeFactory;
_logger = logger;
}
/// <summary>
@@ -673,7 +676,59 @@ public class BacktestController : BaseController
Name = request.Name
};
await _backtester.InsertBundleBacktestRequestForUserAsync(user, bundleRequest, request.SaveAsTemplate);
// Save bundle request immediately (fast operation)
await _backtester.SaveBundleBacktestRequestAsync(user, bundleRequest);
// If not saving as template, create jobs in background task
if (!request.SaveAsTemplate)
{
// Capture values for background task
var bundleRequestId = bundleRequest.RequestId;
var userId = user.Id;
// Fire off background task to create jobs - don't await, return immediately
_ = Task.Run(async () =>
{
try
{
using var scope = _serviceScopeFactory.CreateScope();
var backtester = scope.ServiceProvider.GetRequiredService<IBacktester>();
var userService = scope.ServiceProvider.GetRequiredService<IUserService>();
// Reload user and bundle request to ensure we have the latest data
var reloadedUser = await userService.GetUserByIdAsync(userId);
if (reloadedUser == null)
{
_logger.LogWarning(
"User {UserId} not found when creating jobs for bundle request {BundleRequestId} in background",
userId, bundleRequestId);
return;
}
var savedBundleRequest = backtester.GetBundleBacktestRequestByIdForUser(reloadedUser, bundleRequestId);
if (savedBundleRequest != null)
{
await backtester.CreateJobsForBundleRequestAsync(savedBundleRequest);
_logger.LogInformation(
"Successfully created jobs for bundle request {BundleRequestId} in background",
bundleRequestId);
}
else
{
_logger.LogWarning(
"Bundle request {BundleRequestId} not found when creating jobs in background",
bundleRequestId);
}
}
catch (Exception ex)
{
_logger.LogError(ex,
"Error creating jobs for bundle request {BundleRequestId} in background task",
bundleRequestId);
}
});
}
return Ok(bundleRequest);
}
catch (Exception ex)