DocSpace-buildtools/common/ASC.Common/Threading/DistributedTaskQueue.cs

340 lines
10 KiB
C#
Raw Normal View History

2019-05-15 14:56:09 +00:00
/*
*
* (c) Copyright Ascensio System Limited 2010-2018
*
* This program is freeware. You can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) version 3 as published by the Free Software Foundation (https://www.gnu.org/copyleft/gpl.html).
* In accordance with Section 7(a) of the GNU GPL its Section 15 shall be amended to the effect that
* Ascensio System SIA expressly excludes the warranty of non-infringement of any third-party rights.
*
* THIS PROGRAM IS DISTRIBUTED WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. For more details, see GNU GPL at https://www.gnu.org/copyleft/gpl.html
*
* You can contact Ascensio System SIA by email at sales@onlyoffice.com
*
* The interactive user interfaces in modified source and object code versions of ONLYOFFICE must display
* Appropriate Legal Notices, as required under Section 5 of the GNU GPL version 3.
*
* Pursuant to Section 7 § 3(b) of the GNU GPL you must retain the original ONLYOFFICE logo which contains
* relevant author attributions when distributing the software. If the display of the logo in its graphic
* form is not reasonably feasible for technical reasons, you must include the words "Powered by ONLYOFFICE"
* in every copy of the program you distribute.
* Pursuant to Section 7 § 3(e) we decline to grant you any rights under trademark law for use of our trademarks.
*
*/
namespace ASC.Common.Threading;
[Singletone]
public class DistributedTaskCacheNotify
2019-10-14 08:23:45 +00:00
{
public ConcurrentDictionary<string, CancellationTokenSource> Cancelations { get; }
public ICache Cache { get; }
private readonly ICacheNotify<DistributedTaskCancelation> _cancelTaskNotify;
private readonly ICacheNotify<DistributedTaskCache> _taskCacheNotify;
public DistributedTaskCacheNotify(
ICacheNotify<DistributedTaskCancelation> cancelTaskNotify,
ICacheNotify<DistributedTaskCache> taskCacheNotify,
ICache cache)
2019-10-14 08:23:45 +00:00
{
Cancelations = new ConcurrentDictionary<string, CancellationTokenSource>();
Cache = cache;
_cancelTaskNotify = cancelTaskNotify;
2019-10-14 08:23:45 +00:00
cancelTaskNotify.Subscribe((c) =>
2019-10-14 08:23:45 +00:00
{
2022-02-08 11:07:28 +00:00
if (Cancelations.TryGetValue(c.Id, out var s))
{
s.Cancel();
}
}, CacheNotifyAction.Remove);
2020-03-04 07:42:43 +00:00
_taskCacheNotify = taskCacheNotify;
2019-10-14 08:23:45 +00:00
taskCacheNotify.Subscribe((c) =>
{
Cache.HashSet(c.Key, c.Id, (DistributedTaskCache)null);
}, CacheNotifyAction.Remove);
2019-10-14 08:23:45 +00:00
taskCacheNotify.Subscribe((c) =>
{
Cache.HashSet(c.Key, c.Id, c);
}, CacheNotifyAction.InsertOrUpdate);
}
2019-10-14 08:23:45 +00:00
2022-02-08 11:07:28 +00:00
public void CancelTask(string id)
{
_cancelTaskNotify.Publish(new DistributedTaskCancelation() { Id = id }, CacheNotifyAction.Remove);
2022-02-08 11:07:28 +00:00
}
2019-10-14 08:23:45 +00:00
2022-02-08 11:07:28 +00:00
public void SetTask(DistributedTask task)
{
_taskCacheNotify.Publish(task.DistributedTaskCache, CacheNotifyAction.InsertOrUpdate);
2022-02-08 11:07:28 +00:00
}
2019-10-14 08:23:45 +00:00
2022-02-08 11:07:28 +00:00
public void RemoveTask(string id, string key)
{
_taskCacheNotify.Publish(new DistributedTaskCache() { Id = id, Key = key }, CacheNotifyAction.Remove);
2022-02-08 11:07:28 +00:00
}
}
2019-10-14 08:23:45 +00:00
[Singletone(typeof(ConfigureDistributedTaskQueue))]
public class DistributedTaskQueueOptionsManager : OptionsManager<DistributedTaskQueue>
{
public DistributedTaskQueueOptionsManager(IOptionsFactory<DistributedTaskQueue> factory) : base(factory) { }
2022-02-08 11:07:28 +00:00
public DistributedTaskQueue Get<T>() where T : DistributedTask
{
return Get(typeof(T).FullName);
}
}
[Scope]
public class ConfigureDistributedTaskQueue : IConfigureNamedOptions<DistributedTaskQueue>
{
2022-02-08 11:07:28 +00:00
private readonly DistributedTaskCacheNotify _distributedTaskCacheNotify;
public readonly IServiceProvider _serviceProvider;
2022-02-04 09:56:15 +00:00
public ConfigureDistributedTaskQueue(
DistributedTaskCacheNotify distributedTaskCacheNotify,
IServiceProvider serviceProvider)
{
2022-02-08 11:07:28 +00:00
_distributedTaskCacheNotify = distributedTaskCacheNotify;
_serviceProvider = serviceProvider;
2019-10-14 08:23:45 +00:00
}
2020-07-13 15:26:21 +00:00
public void Configure(DistributedTaskQueue queue)
{
2022-02-08 11:07:28 +00:00
queue.DistributedTaskCacheNotify = _distributedTaskCacheNotify;
queue.ServiceProvider = _serviceProvider;
}
public void Configure(string name, DistributedTaskQueue options)
{
Configure(options);
options.Name = name;
}
}
public class DistributedTaskQueue
{
public IServiceProvider ServiceProvider { get; set; }
public DistributedTaskCacheNotify DistributedTaskCacheNotify { get; set; }
public string Name
{
Merge branch 'feature/backend-refactor' into feature/asc-common-refactor # Conflicts: # common/ASC.Api.Core/GlobalUsings.cs # common/ASC.Common/Caching/AscCache.cs # common/ASC.Common/Collections/CachedDictionaryBase.cs # common/ASC.Common/Collections/HttpRequestDictionary.cs # common/ASC.Common/DIHelper.cs # common/ASC.Common/Data/StreamExtension.cs # common/ASC.Common/Data/TempStream.cs # common/ASC.Common/DependencyInjection/AutofacExtension.cs # common/ASC.Common/Logging/Log.cs # common/ASC.Common/Logging/SelfCleaningTarget.cs # common/ASC.Common/Logging/SpecialFolderPathConverter.cs # common/ASC.Common/Mapping/MappingProfile.cs # common/ASC.Common/Security/AscRandom.cs # common/ASC.Common/Security/Authorizing/AuthorizingException.cs # common/ASC.Common/Security/Authorizing/Constants.cs # common/ASC.Common/Security/Authorizing/Domain/Role.cs # common/ASC.Common/Security/Cryptography/Hasher.cs # common/ASC.Common/Threading/DistributedTask.cs # common/ASC.Common/Threading/DistributedTaskQueue.cs # common/ASC.Common/Utils/DnsLookup.cs # common/ASC.Common/Utils/HtmlUtil.cs # common/ASC.Common/Utils/HttpRequestExtensions.cs # common/ASC.Common/Utils/JsonWebToken.cs # common/ASC.Common/Utils/MailAddressUtils.cs # common/ASC.Common/Utils/RandomString.cs # common/ASC.Common/Utils/TimeZoneConverter/TimeZoneConverter.cs # common/ASC.Common/Utils/VelocityFormatter.cs # common/ASC.Common/Utils/Wildcard.cs # common/ASC.Common/Web/MimeMapping.cs # common/ASC.Common/Web/VirtualPathUtility.cs # common/services/ASC.ClearEvents/Program.cs # products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs # products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs
2022-02-11 13:17:55 +00:00
get => _name;
set => _name = value + GetType().Name;
}
public int MaxThreadsCount
2020-07-13 15:26:21 +00:00
{
Merge branch 'feature/backend-refactor' into feature/asc-common-refactor # Conflicts: # common/ASC.Api.Core/GlobalUsings.cs # common/ASC.Common/Caching/AscCache.cs # common/ASC.Common/Collections/CachedDictionaryBase.cs # common/ASC.Common/Collections/HttpRequestDictionary.cs # common/ASC.Common/DIHelper.cs # common/ASC.Common/Data/StreamExtension.cs # common/ASC.Common/Data/TempStream.cs # common/ASC.Common/DependencyInjection/AutofacExtension.cs # common/ASC.Common/Logging/Log.cs # common/ASC.Common/Logging/SelfCleaningTarget.cs # common/ASC.Common/Logging/SpecialFolderPathConverter.cs # common/ASC.Common/Mapping/MappingProfile.cs # common/ASC.Common/Security/AscRandom.cs # common/ASC.Common/Security/Authorizing/AuthorizingException.cs # common/ASC.Common/Security/Authorizing/Constants.cs # common/ASC.Common/Security/Authorizing/Domain/Role.cs # common/ASC.Common/Security/Cryptography/Hasher.cs # common/ASC.Common/Threading/DistributedTask.cs # common/ASC.Common/Threading/DistributedTaskQueue.cs # common/ASC.Common/Utils/DnsLookup.cs # common/ASC.Common/Utils/HtmlUtil.cs # common/ASC.Common/Utils/HttpRequestExtensions.cs # common/ASC.Common/Utils/JsonWebToken.cs # common/ASC.Common/Utils/MailAddressUtils.cs # common/ASC.Common/Utils/RandomString.cs # common/ASC.Common/Utils/TimeZoneConverter/TimeZoneConverter.cs # common/ASC.Common/Utils/VelocityFormatter.cs # common/ASC.Common/Utils/Wildcard.cs # common/ASC.Common/Web/MimeMapping.cs # common/ASC.Common/Web/VirtualPathUtility.cs # common/services/ASC.ClearEvents/Program.cs # products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs # products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs
2022-02-11 13:17:55 +00:00
set => Scheduler = value <= 0
? TaskScheduler.Default
: new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, value).ConcurrentScheduler;
}
2020-08-06 18:07:27 +00:00
2022-02-04 09:56:15 +00:00
private ICache Cache => DistributedTaskCacheNotify.Cache;
private TaskScheduler Scheduler { get; set; } = TaskScheduler.Default;
Merge branch 'feature/backend-refactor' into feature/asc-common-refactor # Conflicts: # common/ASC.Api.Core/GlobalUsings.cs # common/ASC.Common/Caching/AscCache.cs # common/ASC.Common/Collections/CachedDictionaryBase.cs # common/ASC.Common/Collections/HttpRequestDictionary.cs # common/ASC.Common/DIHelper.cs # common/ASC.Common/Data/StreamExtension.cs # common/ASC.Common/Data/TempStream.cs # common/ASC.Common/DependencyInjection/AutofacExtension.cs # common/ASC.Common/Logging/Log.cs # common/ASC.Common/Logging/SelfCleaningTarget.cs # common/ASC.Common/Logging/SpecialFolderPathConverter.cs # common/ASC.Common/Mapping/MappingProfile.cs # common/ASC.Common/Security/AscRandom.cs # common/ASC.Common/Security/Authorizing/AuthorizingException.cs # common/ASC.Common/Security/Authorizing/Constants.cs # common/ASC.Common/Security/Authorizing/Domain/Role.cs # common/ASC.Common/Security/Cryptography/Hasher.cs # common/ASC.Common/Threading/DistributedTask.cs # common/ASC.Common/Threading/DistributedTaskQueue.cs # common/ASC.Common/Utils/DnsLookup.cs # common/ASC.Common/Utils/HtmlUtil.cs # common/ASC.Common/Utils/HttpRequestExtensions.cs # common/ASC.Common/Utils/JsonWebToken.cs # common/ASC.Common/Utils/MailAddressUtils.cs # common/ASC.Common/Utils/RandomString.cs # common/ASC.Common/Utils/TimeZoneConverter/TimeZoneConverter.cs # common/ASC.Common/Utils/VelocityFormatter.cs # common/ASC.Common/Utils/Wildcard.cs # common/ASC.Common/Web/MimeMapping.cs # common/ASC.Common/Web/VirtualPathUtility.cs # common/services/ASC.ClearEvents/Program.cs # products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs # products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs
2022-02-11 13:17:55 +00:00
public static readonly int InstanceId = Process.GetCurrentProcess().Id;
2022-02-04 09:56:15 +00:00
private string _name;
2020-07-13 15:26:21 +00:00
2022-02-08 11:07:28 +00:00
private ConcurrentDictionary<string, CancellationTokenSource> Cancelations
{
get
{
return DistributedTaskCacheNotify.Cancelations;
}
}
2022-02-08 11:07:28 +00:00
public void QueueTask(DistributedTaskProgress taskProgress)
{
QueueTask((a, b) => taskProgress.RunJob(), taskProgress);
}
public void QueueTask(Action<DistributedTask, CancellationToken> action, DistributedTask distributedTask = null)
{
2022-02-08 11:07:28 +00:00
if (distributedTask == null)
{
distributedTask = new DistributedTask();
}
distributedTask.InstanceId = InstanceId;
var cancelation = new CancellationTokenSource();
var token = cancelation.Token;
Cancelations[distributedTask.Id] = cancelation;
var task = new Task(() => { action(distributedTask, token); }, token, TaskCreationOptions.LongRunning);
task.ConfigureAwait(false)
.GetAwaiter()
.OnCompleted(() => OnCompleted(task, distributedTask.Id));
distributedTask.Status = DistributedTaskStatus.Running;
if (distributedTask.Publication == null)
2022-02-08 11:07:28 +00:00
{
distributedTask.Publication = GetPublication();
2022-02-08 11:07:28 +00:00
}
2020-07-13 15:26:21 +00:00
distributedTask.PublishChanges();
task.Start(Scheduler);
}
public IEnumerable<DistributedTask> GetTasks()
{
var tasks = Cache.HashGetAll<DistributedTaskCache>(_name).Values.Select(r => new DistributedTask(r)).ToList();
tasks.ForEach(t =>
2020-07-13 15:26:21 +00:00
{
2022-02-08 11:07:28 +00:00
if (t.Publication == null)
{
t.Publication = GetPublication();
}
});
return tasks;
2020-07-13 15:26:21 +00:00
}
public IEnumerable<T> GetTasks<T>() where T : DistributedTask
{
var tasks = Cache.HashGetAll<DistributedTaskCache>(_name).Values.Select(r =>
{
var result = ServiceProvider.GetService<T>();
result.DistributedTaskCache = r;
return result;
}).ToList();
tasks.ForEach(t =>
2020-07-13 15:26:21 +00:00
{
2022-02-08 11:07:28 +00:00
if (t.Publication == null)
{
t.Publication = GetPublication();
}
});
2019-10-14 08:23:45 +00:00
return tasks;
}
public T GetTask<T>(string id) where T : DistributedTask
{
var cache = Cache.HashGet<DistributedTaskCache>(_name, id);
if (cache != null)
{
using var scope = ServiceProvider.CreateScope();
var task = scope.ServiceProvider.GetService<T>();
task.DistributedTaskCache = cache;
Merge branch 'feature/backend-refactor' into feature/asc-common-refactor # Conflicts: # common/ASC.Api.Core/GlobalUsings.cs # common/ASC.Common/Caching/AscCache.cs # common/ASC.Common/Collections/CachedDictionaryBase.cs # common/ASC.Common/Collections/HttpRequestDictionary.cs # common/ASC.Common/DIHelper.cs # common/ASC.Common/Data/StreamExtension.cs # common/ASC.Common/Data/TempStream.cs # common/ASC.Common/DependencyInjection/AutofacExtension.cs # common/ASC.Common/Logging/Log.cs # common/ASC.Common/Logging/SelfCleaningTarget.cs # common/ASC.Common/Logging/SpecialFolderPathConverter.cs # common/ASC.Common/Mapping/MappingProfile.cs # common/ASC.Common/Security/AscRandom.cs # common/ASC.Common/Security/Authorizing/AuthorizingException.cs # common/ASC.Common/Security/Authorizing/Constants.cs # common/ASC.Common/Security/Authorizing/Domain/Role.cs # common/ASC.Common/Security/Cryptography/Hasher.cs # common/ASC.Common/Threading/DistributedTask.cs # common/ASC.Common/Threading/DistributedTaskQueue.cs # common/ASC.Common/Utils/DnsLookup.cs # common/ASC.Common/Utils/HtmlUtil.cs # common/ASC.Common/Utils/HttpRequestExtensions.cs # common/ASC.Common/Utils/JsonWebToken.cs # common/ASC.Common/Utils/MailAddressUtils.cs # common/ASC.Common/Utils/RandomString.cs # common/ASC.Common/Utils/TimeZoneConverter/TimeZoneConverter.cs # common/ASC.Common/Utils/VelocityFormatter.cs # common/ASC.Common/Utils/Wildcard.cs # common/ASC.Common/Web/MimeMapping.cs # common/ASC.Common/Web/VirtualPathUtility.cs # common/services/ASC.ClearEvents/Program.cs # products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs # products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs
2022-02-11 13:17:55 +00:00
if (task.Publication == null)
2022-02-08 11:07:28 +00:00
{
task.Publication = GetPublication();
2022-02-08 11:07:28 +00:00
}
return task;
}
2020-10-02 07:19:02 +00:00
return null;
}
public DistributedTask GetTask(string id)
{
var cache = Cache.HashGet<DistributedTaskCache>(_name, id);
if (cache != null)
2020-03-04 07:42:43 +00:00
{
var task = new DistributedTask();
task.DistributedTaskCache = cache;
Merge branch 'feature/backend-refactor' into feature/asc-common-refactor # Conflicts: # common/ASC.Api.Core/GlobalUsings.cs # common/ASC.Common/Caching/AscCache.cs # common/ASC.Common/Collections/CachedDictionaryBase.cs # common/ASC.Common/Collections/HttpRequestDictionary.cs # common/ASC.Common/DIHelper.cs # common/ASC.Common/Data/StreamExtension.cs # common/ASC.Common/Data/TempStream.cs # common/ASC.Common/DependencyInjection/AutofacExtension.cs # common/ASC.Common/Logging/Log.cs # common/ASC.Common/Logging/SelfCleaningTarget.cs # common/ASC.Common/Logging/SpecialFolderPathConverter.cs # common/ASC.Common/Mapping/MappingProfile.cs # common/ASC.Common/Security/AscRandom.cs # common/ASC.Common/Security/Authorizing/AuthorizingException.cs # common/ASC.Common/Security/Authorizing/Constants.cs # common/ASC.Common/Security/Authorizing/Domain/Role.cs # common/ASC.Common/Security/Cryptography/Hasher.cs # common/ASC.Common/Threading/DistributedTask.cs # common/ASC.Common/Threading/DistributedTaskQueue.cs # common/ASC.Common/Utils/DnsLookup.cs # common/ASC.Common/Utils/HtmlUtil.cs # common/ASC.Common/Utils/HttpRequestExtensions.cs # common/ASC.Common/Utils/JsonWebToken.cs # common/ASC.Common/Utils/MailAddressUtils.cs # common/ASC.Common/Utils/RandomString.cs # common/ASC.Common/Utils/TimeZoneConverter/TimeZoneConverter.cs # common/ASC.Common/Utils/VelocityFormatter.cs # common/ASC.Common/Utils/Wildcard.cs # common/ASC.Common/Web/MimeMapping.cs # common/ASC.Common/Web/VirtualPathUtility.cs # common/services/ASC.ClearEvents/Program.cs # products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs # products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs
2022-02-11 13:17:55 +00:00
if (task.Publication == null)
2022-02-08 11:07:28 +00:00
{
task.Publication = GetPublication();
}
return task;
2020-08-06 18:07:27 +00:00
}
return null;
}
2022-02-08 11:07:28 +00:00
public void SetTask(DistributedTask task)
{
DistributedTaskCacheNotify.SetTask(task);
}
2022-02-08 11:07:28 +00:00
public void RemoveTask(string id)
{
DistributedTaskCacheNotify.RemoveTask(id, _name);
}
2020-08-07 15:42:58 +00:00
2022-02-08 11:07:28 +00:00
public void CancelTask(string id)
{
DistributedTaskCacheNotify.CancelTask(id);
}
private void OnCompleted(Task task, string id)
{
var distributedTask = GetTask(id);
if (distributedTask != null)
2020-08-07 15:42:58 +00:00
{
distributedTask.Status = DistributedTaskStatus.Completed;
distributedTask.Exception = task.Exception;
2022-02-08 11:07:28 +00:00
if (task.IsFaulted)
{
distributedTask.Status = DistributedTaskStatus.Failted;
}
2022-02-08 11:07:28 +00:00
if (task.IsCanceled)
{
distributedTask.Status = DistributedTaskStatus.Canceled;
}
2020-08-07 15:42:58 +00:00
Cancelations.TryRemove(id, out _);
2020-02-07 11:34:25 +00:00
distributedTask.PublishChanges();
}
}
2020-02-07 11:34:25 +00:00
private Action<DistributedTask> GetPublication()
{
return (t) =>
{
2022-02-08 11:07:28 +00:00
if (t.DistributedTaskCache != null)
{
t.DistributedTaskCache.Key = _name;
}
2019-08-16 08:44:03 +00:00
DistributedTaskCacheNotify.SetTask(t);
};
}
}
public static class DistributedTaskQueueExtention
{
public static DIHelper AddDistributedTaskQueueService<T>(this DIHelper services, int maxThreadsCount) where T : DistributedTask
{
services.TryAdd<DistributedTaskCacheNotify>();
services.TryAdd<DistributedTaskQueueOptionsManager>();
services.TryAdd<DistributedTaskQueue>();
2021-05-19 08:31:50 +00:00
var type = typeof(T);
2022-02-08 11:07:28 +00:00
if (!type.IsAbstract)
{
services.TryAdd<T>();
}
services.TryAddSingleton<IConfigureOptions<DistributedTaskQueue>, ConfigureDistributedTaskQueue>();
_ = services.Configure<DistributedTaskQueue>(type.Name, r =>
{
r.MaxThreadsCount = maxThreadsCount;
//r.errorCount = 1;
});
return services;
}
2022-02-08 11:07:28 +00:00
}