forked from SciSharp/BotSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCrontabService.cs
More file actions
153 lines (131 loc) · 5.5 KB
/
CrontabService.cs
File metadata and controls
153 lines (131 loc) · 5.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
/*****************************************************************************
Copyright 2024 Written by Haiping Chen. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******************************************************************************/
using BotSharp.Abstraction.Agents.Models;
using BotSharp.Abstraction.Repositories;
using BotSharp.Abstraction.Repositories.Filters;
using BotSharp.Abstraction.Tasks;
using BotSharp.Abstraction.Tasks.Models;
using BotSharp.Abstraction.Utilities;
using BotSharp.Core.Infrastructures;
using Microsoft.Extensions.Logging;
using System.Text.RegularExpressions;
namespace BotSharp.Core.Crontab.Services;
/// <summary>
/// The Crontab service schedules distributed events based on the execution times provided by users.
/// In a scalable environment, distributed locks are used to ensure that each event is triggered only once.
/// </summary>
public class CrontabService : ICrontabService, ITaskFeeder
{
private readonly IServiceProvider _services;
private ILogger _logger;
public CrontabService(IServiceProvider services, ILogger<CrontabService> logger)
{
_services = services;
_logger = logger;
}
public async Task<List<CrontabItem>> GetCrontable()
{
var repo = _services.GetRequiredService<IBotSharpRepository>();
var crontable = await repo.GetCrontabItems(CrontabItemFilter.Empty());
// Add fixed crontab items from cronsources
var fixedCrontabItems = crontable.Items.ToList();
var cronSources = _services.GetServices<ICrontabSource>();
foreach (var source in cronSources)
{
if (source.IsRealTime)
{
continue;
}
var item = source.GetCrontabItem();
fixedCrontabItems.Add(item);
}
return fixedCrontabItems;
}
public async Task<List<AgentTask>> GetTasks()
{
var tasks = new List<AgentTask>();
var agentService = _services.GetRequiredService<IAgentService>();
var cronsources = _services.GetServices<ICrontabSource>();
// Get all agent subscribed to this cron
var agents = await agentService.GetAgents(new AgentFilter
{
Pager = new Pagination
{
Size = 1000
}
});
foreach (var source in cronsources)
{
var cron = source.GetCrontabItem();
var preFilteredAgents = agents.Items.Where(x =>
x.Rules.Exists(r => r.TriggerName == cron.Title)).ToList();
tasks.AddRange(preFilteredAgents.Select(x => new AgentTask
{
Id = Guid.Empty.ToString(),
AgentId = x.Id,
Agent = new Agent
{
Name = x.Name,
Description = x.Description
},
Name = FormatCrontabName(cron.Title, x.Name),
Content = $"Trigger: {cron.Title}\r\nAgent: {x.Name}\r\nCron expression: {cron.Cron}",
Status = TaskStatus.Scheduled,
Enabled = !x.Disabled,
Description = cron.Description,
LastExecutionTime = cron.LastExecutionTime
}));
}
return tasks;
}
private string FormatCrontabName(string trigger, string agent)
{
trigger = trigger.Replace("RuleTrigger", string.Empty);
trigger = Regex.Replace(trigger, "(?<!^)([A-Z])", " $1");
agent = agent.Replace("Operator", string.Empty);
return $"{trigger}";
}
public async Task ScheduledTimeArrived(CrontabItem item)
{
_logger.LogDebug($"ScheduledTimeArrived {item}");
if (!await HasEnabledTriggerRule(item)) return;
await HookEmitter.Emit<ICrontabHook>(_services, async hook =>
{
if (hook.Triggers == null || hook.Triggers.Contains(item.Title))
{
hook.OnAuthenticate(item);
await hook.OnTaskExecuting(item);
await hook.OnCronTriggered(item);
await hook.OnTaskExecuted(item);
}
}, item.AgentId);
}
/// <summary>
/// Returns whether the trigger is treated as enabled for this schedule: <c>true</c> unless a rule with the
/// same trigger name exists and is explicitly disabled (opt-out). Missing rules do not block.
/// </summary>
private async Task<bool> HasEnabledTriggerRule(CrontabItem item)
{
var agentService = _services.GetRequiredService<IAgentService>();
// No agent context: do not gate (legacy / callers without AgentId).
if (string.IsNullOrEmpty(item.AgentId)) return true;
var agent = await agentService.GetAgent(item.AgentId);
if (agent == null)
{
_logger.LogWarning("Agent {AgentId} is not found", item.AgentId);
return false;
}
// Opt-out only: block when a matching trigger rule exists and Disabled is true.
return !agent.Rules.Any(r => r.TriggerName == item.Title && r.Disabled);
}
}