-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDomainObjectDemoDelayTask.cs
More file actions
307 lines (250 loc) · 11.6 KB
/
Copy pathDomainObjectDemoDelayTask.cs
File metadata and controls
307 lines (250 loc) · 11.6 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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
using Acme.DemoServer.Processing.Common;
using Acme.DemoServer.Processing.Generated.Interface;
using Acme.DemoServer.Processing.Model.DomainObjects.DemoDelayTask.Scenarios;
using Acme.DemoServer.Processing.Model.DomainObjects.DemoDelayTask.ScenarioStates;
using Acme.DemoServer.Processing.Model.Interfaces;
using Acme.Wattle.CodeGeneration.Generators;
using Acme.Wattle.Common.Exceptions;
using Acme.Wattle.DomainObjects.DomainObjects;
using Acme.Wattle.DomainObjects.DomainObjects.BaseDomainObjects;
using Acme.Wattle.DomainObjects.Interfaces;
using Acme.Wattle.DomainObjects.Serializers;
using Acme.Wattle.DomainObjects.Serializers.Binary;
using Acme.Wattle.DomainObjects.Serializers.Json;
using Acme.Wattle.DomainObjects.UnitOfWorkLocks;
using Acme.Wattle.Mappers.Primitives.MutableFields;
using System;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace Acme.DemoServer.Processing.Model.DomainObjects.DemoDelayTask;
[DomainObjectDataMapper]
// ReSharper disable once ClassNeverInstantiated.Global
public sealed class DomainObjectDemoDelayTask : BaseDomainObjectMutableWithUpdateLock<DomainObjectDemoDelayTask, IEntryPointContext<ICustomEntryPoint>>, IDomainObjectDemoDelayTask
{
#region Template - шаблон создания объекта
/// <summary>
/// Шаблон создания объекта <see cref="DomainObjectDemoDelayTask"/>.
/// </summary>
public class Template : IDomainObjectTemplate
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
// ReSharper disable once ConvertToPrimaryConstructor
public Template(
string scenario,
DateTimeOffset? startDate)
{
Scenario = scenario;
StartDate = startDate;
}
/// <summary>
/// <seealso cref="DemoDelayTaskScenario"/>.
/// </summary>
public readonly string Scenario;
public readonly DateTimeOffset? StartDate;
}
#endregion
#region Изменяемы поля
[DomainObjectFieldValue]
private readonly MutableField<bool> m_available;
[DomainObjectFieldValue]
private readonly MutableFieldNullable<DateTimeOffset> m_startDate;
[DomainObjectFieldValue]
private readonly BinaryFieldWithModel<DemoCycleTaskScenarioState> m_scenarioState;
[DomainObjectFieldValue]
private readonly StringFieldWithModel<DemoDelayTaskScenario> m_scenario;
#endregion
#region Конструкторы
[MethodImpl(MethodImplOptions.AggressiveInlining)]
// ReSharper disable once UnusedMember.Global
public DomainObjectDemoDelayTask(
DemoDelayTaskDtoActual data,
IEntryPointContext<ICustomEntryPoint> entryPointContext,
IDomainObjectUnitOfWorkLockService lockUpdate)
: base(entryPointContext, data, lockUpdate, false)
{
m_available = new MutableField<bool>(data.Available);
CreateDate = data.CreateDate;
ModificationDate = data.ModificationDate;
m_startDate =
new MutableFieldNullable<DateTimeOffset>(
// Дата-время в БД хранится с ограниченной точность.
DbTypesCorrector.DateTimeOffset(data.StartDate));
m_scenarioState =
new BinaryFieldWithModel<DemoCycleTaskScenarioState>(
m_entryPointContext.EntryPoint.BinaryDeserializer,
data.ScenarioState);
m_scenario =
new StringFieldWithModel<DemoDelayTaskScenario>(
m_entryPointContext.EntryPoint.JsonDeserializer,
data.Scenario);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
// ReSharper disable once UnusedMember.Global
public DomainObjectDemoDelayTask(
long identity,
Template template,
IEntryPointContext<ICustomEntryPoint> entryPointContext,
IDomainObjectUnitOfWorkLockService lockUpdate)
: base(entryPointContext, identity, lockUpdate, true)
{
m_available = new MutableField<bool>(true);
CreateDate = m_entryPointContext.TimeService.Now;
ModificationDate = CreateDate;
m_startDate = new MutableFieldNullable<DateTimeOffset>(template.StartDate);
m_scenarioState =
new BinaryFieldWithModel<DemoCycleTaskScenarioState>(
m_entryPointContext.EntryPoint.BinaryDeserializer,
Array.Empty<byte>());
m_scenario =
new StringFieldWithModel<DemoDelayTaskScenario>(
m_entryPointContext.EntryPoint.JsonDeserializer,
template.Scenario);
var scenario = m_scenario.AsRead;
switch (scenario.Type)
{
case DemoDelayTaskScenariosType.Empty:
case DemoDelayTaskScenariosType.Poisoned:
case DemoDelayTaskScenariosType.Delay:
/* NONE */
break;
case DemoDelayTaskScenariosType.Cycle:
{
var scenarioStateAsCycle =
new DemoCycleTaskScenarioStateAsCycle
{
Index = 0,
RunDate = [],
};
m_scenarioState.SetValue(scenarioStateAsCycle, ModelUseMode.ReadOnly);
break;
}
default:
throw new InternalException($"Неизвестный тип сценария '{scenario.GetType().Assembly}'.");
}
}
#endregion
public override Guid TypeId => WellknownDomainObjects.DemoDelayTask;
[DomainObjectFieldValue]
public DateTimeOffset CreateDate
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get;
}
[DomainObjectFieldValue]
public DateTimeOffset ModificationDate
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private set;
}
public string Scenario
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => m_scenario.Value;
}
public ReadOnlyMemory<byte> ScenarioState
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => m_scenarioState.Value;
}
public DateTimeOffset? StartDate
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => m_startDate.Value;
}
public async ValueTask<(bool IsCompleted, CancellationToken? CommitCancellationToken)> ProcessAsync(bool isRemoved, long count, CancellationToken cancellationToken)
{
m_lockUpdate.Has(Identity);
if (isRemoved)
{
Console.WriteLine($"[{m_entryPointContext.TimeService.NowDateTime:O}] DemoDelayTask.Id:{Identity} - Удалена.");
m_available.SetValue(false);
}
else
{
await DoRunScenarioAsync(count, cancellationToken).ConfigureAwait(false);
}
await DoUpdateAsync(cancellationToken).ConfigureAwait(false);
if (m_available.Value)
{
return (false, null);
}
// Явная очистка памяти. Это не обязательно т.к. данные по времени будут удаленны из кэша.
m_scenario.ReleaseSmartDeserializer();
m_scenarioState.ReleaseSmartDeserializer();
return (true, null);
}
protected override ValueTask DoUpdateAsync(CancellationToken cancellationToken = default)
{
ModificationDate = m_entryPointContext.TimeService.Now;
return base.DoUpdateAsync(cancellationToken);
}
private async ValueTask DoRunScenarioAsync(long count, CancellationToken cancellationToken)
{
var scenario = m_scenario.AsRead;
if (scenario is DemoDelayTaskScenarioAsDelay scenarioAsDelay)
{
if (count > 1)
{
throw new InternalException("Что-то сломалось, задача исполняется несколько раз.");
}
Console.WriteLine($"[{m_entryPointContext.TimeService.NowDateTime:O}] DemoDelayTask.Id:{Identity} ({scenarioAsDelay.Type}) - Начало ожидания '{scenarioAsDelay.Delay}' ...");
await Task.Delay(scenarioAsDelay.Delay, cancellationToken).ConfigureAwait(false);
Console.WriteLine($"[{m_entryPointContext.TimeService.NowDateTime:O}] DemoDelayTask.Id:{Identity} ({scenarioAsDelay.Type}) - Конец ожидания.");
m_available.SetValue(false);
}
else if (scenario is DemoDelayTaskScenarioAsEmpty scenarioAsEmpty)
{
if (count > 1)
{
throw new InternalException("Что-то сломалось, задача исполняется несколько раз.");
}
Console.WriteLine($"[{m_entryPointContext.TimeService.NowDateTime:O}] DemoDelayTask.Id:{Identity} ({scenarioAsEmpty.Type}) - Исполнена.");
m_available.SetValue(false);
}
else if (scenario is DemoDelayTaskScenarioAsPoisoned scenarioAsPoisoned)
{
if (count > 1)
{
throw new InternalException("Что-то сломалось, задача исполняется несколько раз.");
}
Console.WriteLine($"[{m_entryPointContext.TimeService.NowDateTime:O}] DemoDelayTask.Id:{Identity} ({scenarioAsPoisoned.Type}) - Начало исполнения 'IsSuspended: {m_entryPointContext.EntryPoint.DemoDelayTaskProcessor.IsSuspended}' ...");
m_entryPointContext.EntryPoint.DemoDelayTaskProcessor.Suspend();
Console.WriteLine($"[{m_entryPointContext.TimeService.NowDateTime:O}] DemoDelayTask.Id:{Identity} ({scenarioAsPoisoned.Type}) - Конец исполнения 'IsSuspended: {m_entryPointContext.EntryPoint.DemoDelayTaskProcessor.IsSuspended}'.");
m_available.SetValue(false);
}
else if (scenario is DemoDelayTaskScenarioAsCycle scenarioAsCycle)
{
if (count > scenarioAsCycle.Count)
{
throw new InternalException("Что-то сломалось, задача исполняется слишком много раз.");
}
var scenariostate = m_scenarioState.GetAsWrite<DemoCycleTaskScenarioStateAsCycle>();
Console.WriteLine($"[{m_entryPointContext.TimeService.NowDateTime:O}] DemoDelayTask.Id:{Identity} ({scenarioAsCycle.Type}) - Начало исполнения '{scenariostate.Index}' ...");
if (scenariostate.Index < scenarioAsCycle.Count)
{
scenariostate.Index++;
var now = m_entryPointContext.TimeService.Now;
scenariostate.RunDate.Add(now);
if (scenarioAsCycle.NextRunTimeout.HasValue)
{
m_startDate.SetValue(
// Дата-время в БД хранится с ограниченной точность.
DbTypesCorrector.DateTimeOffset(now + scenarioAsCycle.NextRunTimeout.Value));
}
else
{
m_startDate.SetValue(null);
}
}
Console.WriteLine($"[{m_entryPointContext.TimeService.NowDateTime:O}] DemoDelayTask.Id:{Identity} ({scenarioAsCycle.Type}) - Конец исполнения '{scenariostate.Index}' [{(m_startDate.Value?.ToString("O") ?? "НЕТ ДАТЫ")}].");
m_available.SetValue(scenariostate.Index < scenarioAsCycle.Count);
}
else
{
throw new InternalException($"Неизвестный тип сценария '{scenario.GetType().Assembly}'.");
}
}
}