Skip to content

Commit

Permalink
upd job evaluator (#488)
Browse files Browse the repository at this point in the history
  • Loading branch information
iatsuta authored Sep 20, 2024
1 parent 5faa986 commit 83054cc
Show file tree
Hide file tree
Showing 12 changed files with 56 additions and 36 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,6 @@ public static async Task RunJob<TJob>(this IServiceProvider rootServiceProvider,
await rootServiceProvider.GetRequiredService<IJobEvaluator>().RunJob<TJob>(cancellationToken);
}

public static async Task RunJob<TJob>(this IServiceProvider rootServiceProvider, Func<TJob, Task> executeAsync)
where TJob : notnull
{
await rootServiceProvider.GetRequiredService<IJobEvaluator>().RunJob(executeAsync);
}

public static ControllerEvaluator<TController> GetDefaultControllerEvaluator<TController>(
this IServiceProvider rootServiceProvider,
string? principalName = null)
Expand Down
24 changes: 22 additions & 2 deletions src/Framework.HangfireCore/BssHangfireSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ public class BssHangfireSettings : IBssHangfireSettings

private readonly List<Action> runJobActions = [];

private bool autoRegisterJob;

private readonly SqlServerStorageOptions sqlServerStorageOptions = new()
{
CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
Expand All @@ -42,6 +44,13 @@ public BssHangfireSettings()
this.SetConnectionStringName("DefaultConnectionString");
}

public IBssHangfireSettings SetAutoRegisterJob(bool value)
{
this.autoRegisterJob = value;

return this;
}

public IBssHangfireSettings SetConnectionString(string newConnectionString)
{
this.getConnectionStringFunc = _ => newConnectionString;
Expand Down Expand Up @@ -78,14 +87,25 @@ public IBssHangfireSettings WithSqlServerStorageOptions(Action<SqlServerStorageO


public IBssHangfireSettings AddJob<TJob, TArg>(Func<TJob, TArg, Task> executeAction, JobSettings? jobSettings = null)
where TJob : class
{
var jobName = jobSettings?.Name ?? typeof(TJob).Name;
var isInterface = typeof(TJob).IsInterface;

var jobName = jobSettings?.Name ?? typeof(TJob).Name.Pipe(isInterface, v => v.Skip("I", true));

var cronTiming = jobSettings?.CronTiming
?? this.JobTimings.Where(jt => jt.Name == jobName).Select(jt => jt.Schedule).SingleOrDefault()
?? throw new Exception($"{nameof(JobTiming)} for job '{jobName}' not found");

this.registerActions.Add(services => services.AddSingleton(new JobInfo<TJob, TArg>(executeAction)));
this.registerActions.Add(services =>
{
if (!isInterface && this.autoRegisterJob)
{
services.AddScoped<TJob>();
}

services.AddSingleton(new JobInfo<TJob, TArg>(executeAction));
});

this.runJobActions.Add(
() => RecurringJob.AddOrUpdate<MiddlewareJob<TJob, TArg>>(jobName, job => job.ExecuteAsync(default!), cronTiming));
Expand Down
15 changes: 12 additions & 3 deletions src/Framework.HangfireCore/IBssHangfireSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,13 @@ namespace Framework.HangfireCore;

public interface IBssHangfireSettings
{
/// <summary>
/// Автоматическая регистрация job-ов в scope
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
IBssHangfireSettings SetAutoRegisterJob(bool value);

IBssHangfireSettings SetConnectionString(string connectionString);

IBssHangfireSettings SetConnectionStringName(string connectionStringName);
Expand All @@ -16,11 +23,13 @@ public interface IBssHangfireSettings
IBssHangfireSettings WithSqlServerStorageOptions(Action<SqlServerStorageOptions> setupOptions);

IBssHangfireSettings AddJob<TJob>(JobSettings? jobSettings = null)
where TJob : IJob =>
where TJob : class, IJob =>
this.AddJob<TJob, CancellationToken>((job, cancellationToken) => job.ExecuteAsync(cancellationToken), jobSettings);

IBssHangfireSettings AddJob<TJob>(Func<TJob, CancellationToken, Task> executeAction, JobSettings? jobSettings = null) =>
IBssHangfireSettings AddJob<TJob>(Func<TJob, CancellationToken, Task> executeAction, JobSettings? jobSettings = null)
where TJob : class =>
this.AddJob<TJob, CancellationToken>(executeAction, jobSettings);

IBssHangfireSettings AddJob<TJob, TArg>(Func<TJob, TArg, Task> executeAction, JobSettings? jobSettings = null);
IBssHangfireSettings AddJob<TJob, TArg>(Func<TJob, TArg, Task> executeAction, JobSettings? jobSettings = null)
where TJob : class;
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ public interface IJobEvaluator
{
Task RunJob<TJob>(CancellationToken cancellationToken = default)
where TJob : IJob =>
this.RunJob<TJob>(job => job.ExecuteAsync(cancellationToken));
this.RunService<TJob>(job => job.ExecuteAsync(cancellationToken));

Task RunJob<TJob>(Func<TJob, Task> executeAsync)
where TJob : notnull;
Task RunService<TService>(Func<TService, Task> executeAsync)
where TService : notnull;
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,7 @@
public interface IJobEvaluatorFactory
{
IJobEvaluator Create(bool withRootLogging);

Task RunService<TService>(Func<TService, Task> executeAsync)
where TService : notnull => this.Create(false).RunService(executeAsync);
}
11 changes: 6 additions & 5 deletions src/_DomainDriven/Framework.DomainDriven.Jobs/JobEvaluator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,17 @@ namespace Framework.DomainDriven.Jobs;

public class JobEvaluator(IServiceProvider rootServiceProvider, JobEvaluatorSettings settings) : IJobEvaluator
{
public async Task RunJob<TJob>(Func<TJob, Task> executeAsync)
where TJob : notnull
public async Task RunService<TService>(Func<TService, Task> executeAsync)
where TService : notnull
{
await using var scope = rootServiceProvider.CreateAsyncScope();

var middlewareFactory = scope.ServiceProvider.GetRequiredService<IJobMiddlewareFactory>();

var job = scope.ServiceProvider.GetRequiredService<TJob>();
var service = scope.ServiceProvider.GetRequiredService<TService>();

await middlewareFactory
.Create<TJob>(settings.WithRootLogging)
.EvaluateAsync(async () => await executeAsync(job));
.Create<TService>(settings.WithRootLogging)
.EvaluateAsync(async () => await executeAsync(service));
}
}
5 changes: 0 additions & 5 deletions src/_SampleSystem/SampleSystem.BLL.Core/Jobs/ISampleJob.cs

This file was deleted.

6 changes: 3 additions & 3 deletions src/_SampleSystem/SampleSystem.BLL/Jobs/SampleJob.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
using Framework.DomainDriven.Repository;
using Framework.DomainDriven.Jobs;
using Framework.DomainDriven.Repository;
using Framework.SecuritySystem;
using Framework.SecuritySystem.UserSource;

using Microsoft.Extensions.Logging;

using SampleSystem.BLL.Core.Jobs;
using SampleSystem.Domain;

namespace SampleSystem.BLL.Jobs;

public class SampleJob([DisabledSecurity] IRepository<TestJobObject> testRepository, ILogger<SampleJob> logger, ICurrentUser currentUser) : ISampleJob
public class SampleJob([DisabledSecurity] IRepository<TestJobObject> testRepository, ILogger<SampleJob> logger, ICurrentUser currentUser) : IJob
{
public async Task ExecuteAsync(CancellationToken cancellationToken)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
using Microsoft.Extensions.DependencyInjection;

using SampleSystem.BLL;
using SampleSystem.BLL.Core.Jobs;
using SampleSystem.BLL.Jobs;
using SampleSystem.Domain;
using SampleSystem.Events;
Expand Down Expand Up @@ -50,5 +49,5 @@ private static IServiceCollection RegisterSmtpNotification(this IServiceCollecti
}

private static IServiceCollection RegisterJobs(this IServiceCollection services) =>
services.AddScoped<ISampleJob, SampleJob>();
services.AddScoped<SampleJob>();
}
3 changes: 1 addition & 2 deletions src/_SampleSystem/SampleSystem.WebApiCore/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
using Microsoft.AspNetCore.Authorization;

using SampleSystem.BLL._Command.CreateClassA.Integration;
using SampleSystem.BLL.Core.Jobs;
using SampleSystem.BLL.Jobs;
using SampleSystem.ServiceEnvironment;
using SampleSystem.WebApiCore.Services;
Expand Down Expand Up @@ -70,7 +69,7 @@

builder.Services.AddHangfireBss(
builder.Configuration,
s => s.AddJob<ISampleJob>(new JobSettings { Name = nameof(SampleJob) })
s => s.AddJob<SampleJob>()
.AddJob<ISendNotificationsJob>((job, ct) => job.ExecuteAsync(ct), new JobSettings { CronTiming = Cron.Never() }));

builder.Services.ValidateDuplicateDeclaration(typeof(ILoggerFactory));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
using Framework.DomainDriven;
using Microsoft.VisualStudio.TestTools.UnitTesting;

using SampleSystem.BLL.Core.Jobs;
using SampleSystem.BLL.Jobs;
using SampleSystem.Domain;
using SampleSystem.IntegrationTests.__Support.TestData;

Expand All @@ -23,7 +23,7 @@ public async Task InvokeJobs_JobObjectsCreated()
var repeatCount = 10;

// Act
await Task.WhenAll(Enumerable.Range(0, repeatCount).Select(_ => this.RootServiceProvider.RunJob<ISampleJob>()).ToArray());
await Task.WhenAll(Enumerable.Range(0, repeatCount).Select(_ => this.RootServiceProvider.RunJob<SampleJob>()).ToArray());

// Assert
var newCount = GetJobInstanceCount();
Expand Down
6 changes: 3 additions & 3 deletions src/__SolutionItems/CommonAssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
[assembly: AssemblyCompany("Luxoft")]
[assembly: AssemblyCopyright("Copyright © Luxoft 2009-2024")]

[assembly: AssemblyVersion("22.3.2.0")]
[assembly: AssemblyFileVersion("22.3.2.0")]
[assembly: AssemblyInformationalVersion("22.3.2.0")]
[assembly: AssemblyVersion("22.3.3.0")]
[assembly: AssemblyFileVersion("22.3.3.0")]
[assembly: AssemblyInformationalVersion("22.3.3.0")]

#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
Expand Down

0 comments on commit 83054cc

Please sign in to comment.