-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathCohortIdentificationConfigurationUICommon.cs
378 lines (308 loc) · 12.4 KB
/
CohortIdentificationConfigurationUICommon.cs
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
// Copyright (c) The University of Dundee 2018-2024
// This file is part of the Research Data Management Platform (RDMP).
// RDMP is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
// RDMP is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with RDMP. If not, see <https://www.gnu.org/licenses/>.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Rdmp.Core.CohortCreation.Execution;
using Rdmp.Core.CohortCreation.Execution.Joinables;
using Rdmp.Core.CommandExecution;
using Rdmp.Core.Curation.Data;
using Rdmp.Core.Curation.Data.Aggregation;
using Rdmp.Core.Curation.Data.Cohort;
using Rdmp.Core.Curation.Data.Cohort.Joinables;
using Rdmp.Core.MapsDirectlyToDatabaseTable;
using Rdmp.Core.QueryCaching.Aggregation;
namespace Rdmp.Core.CohortCreation;
/// <summary>
/// Common methods used by Cohort Builder UI implementations. Eliminates
/// code duplication and makes it possible to add new UI formats later
/// e.g. web/console etc
/// </summary>
public class CohortIdentificationConfigurationUICommon
{
public CohortIdentificationConfiguration Configuration;
public ExternalDatabaseServer QueryCachingServer;
private CancellationTokenSource _cancelGlobalOperations;
private ISqlParameter[] _globals;
public CohortCompilerRunner Runner;
/// <summary>
/// User interface layer for modal dialogs, showing Exceptions etc
/// </summary>
public IBasicActivateItems Activator;
/// <summary>
/// Duration in seconds to allow tasks to run for before cancelling
/// </summary>
public int Timeout = 3000;
public CohortCompiler Compiler { get; }
public CohortIdentificationConfigurationUICommon()
{
Compiler = new CohortCompiler(null);
}
public object Working_AspectGetter(object rowobject) => GetKey(rowobject)?.State;
public object Time_AspectGetter(object rowobject) => GetKey(rowobject)?.ElapsedTime?.ToString(@"hh\:mm\:ss");
public object CumulativeTotal_AspectGetter(object rowobject) =>
GetKey(rowobject)?.CumulativeRowCount?.ToString("N0");
public ICompileable GetKey(object rowobject)
{
lock (Compiler.Tasks)
{
return
Compiler?.Tasks?.Keys.FirstOrDefault(k =>
(rowobject is AggregateConfiguration ac && k.Child is JoinableCohortAggregateConfiguration j
&& j.AggregateConfiguration_ID == ac.ID)
|| k.Child.Equals(rowobject));
}
}
public object Cached_AspectGetter(object rowobject)
{
var key = GetKey(rowobject);
return key != null
? Configuration.QueryCachingServer_ID == null ? "No Cache" : key.GetCachedQueryUseCount()
: (object)null;
}
public object Count_AspectGetter(object rowobject)
{
var key = GetKey(rowobject);
return key is { State: CompilationState.Finished } ? key.FinalRowCount.ToString("N0") : (object)null;
}
public static object Catalogue_AspectGetter(object rowobject) =>
rowobject is AggregateConfiguration ac ? ac.Catalogue.Name : null;
public object ExecuteAspectGetter(object rowObject)
{
//don't expose any buttons if global execution is in progress
if (IsExecutingGlobalOperations())
return null;
if (rowObject is AggregateConfiguration or CohortAggregateContainer)
{
var plannedOp = GetNextOperation(GetState((IMapsDirectlyToDatabaseTable)rowObject));
return plannedOp == Operation.None ? null : plannedOp;
}
return null;
}
private CompilationState GetState(IMapsDirectlyToDatabaseTable o)
{
lock (Compiler.Tasks)
{
var task = GetTaskIfExists(o);
return task == null ? CompilationState.NotScheduled : task.State;
}
}
public bool IsExecutingGlobalOperations() => Runner != null &&
Runner.ExecutionPhase != CohortCompilerRunner.Phase.None &&
Runner.ExecutionPhase != CohortCompilerRunner.Phase.Finished;
private static Operation GetNextOperation(CompilationState currentState)
{
return currentState switch
{
CompilationState.NotScheduled => Operation.Execute,
CompilationState.Building => Operation.Cancel,
CompilationState.Scheduled => Operation.None,
CompilationState.Executing => Operation.Cancel,
CompilationState.Finished => Operation.Execute,
CompilationState.Crashed => Operation.Execute,
_ => throw new ArgumentOutOfRangeException(nameof(currentState))
};
}
/// <summary>
/// Rebuilds the CohortCompiler diagram which shows all the currently configured tasks
/// </summary>
/// <param name="cancelTasks"></param>
public void RecreateAllTasks(bool cancelTasks = true)
{
if (cancelTasks)
Compiler.CancelAllTasks(false);
Configuration.CreateRootContainerIfNotExists();
//if there is no root container,create one
_globals = Configuration.GetAllParameters();
//Could have configured/unconfigured a joinable state
foreach (var j in Compiler.Tasks.Keys.OfType<JoinableTask>())
j.RefreshIsUsedState();
}
public void SetShowCumulativeTotals(bool show)
{
Compiler.IncludeCumulativeTotals = show;
RecreateAllTasks();
}
private void OrderActivity(Operation operation, IMapsDirectlyToDatabaseTable o, int? userDefinedTimeout)
{
switch (operation)
{
case Operation.Execute:
StartThisTaskOnly(o, userDefinedTimeout);
break;
case Operation.Cancel:
Cancel(o);
break;
case Operation.Clear:
Clear(o);
break;
case Operation.None:
break;
default:
throw new ArgumentOutOfRangeException(nameof(operation));
}
}
private void StartThisTaskOnly(IMapsDirectlyToDatabaseTable configOrContainer, int? userDefinedTimeout)
{
var task = Compiler.AddTask(configOrContainer, _globals);
if (task.State == CompilationState.Crashed)
{
Activator.ShowException("Task failed to build", task.CrashMessage);
return;
}
//Cancel the task and remove it from the Compilers task list - so it no longer knows about it
Compiler.CancelTask(task, true);
RecreateAllTasks(false);
task = Compiler.AddTask(configOrContainer, _globals);
//Task is now in state NotScheduled, so we can start it
Compiler.LaunchSingleTask(task, userDefinedTimeout ?? Timeout, true);
}
public void Cancel(IMapsDirectlyToDatabaseTable o)
{
var task = Compiler.Tasks.Single(t => t.Key.Child.Equals(o));
Compiler.CancelTask(task.Key, true);
}
public void CancelAll()
{
//don't start any more global operations if your midway through
_cancelGlobalOperations?.Cancel();
Compiler.CancelAllTasks(true);
RecreateAllTasks();
}
public ICompileable GetTaskIfExists(IMapsDirectlyToDatabaseTable o)
{
lock (Compiler.Tasks)
{
var kvps = Compiler.Tasks.Where(t => t.Key.Child.Equals(o)).ToArray();
if (kvps.Length == 0) return null;
if (kvps.Length == 1) return kvps[0].Key;
var running = kvps.FirstOrDefault(k => k.Value != null).Key;
return running ?? kvps[0].Key;
}
}
public void Clear(IMapsDirectlyToDatabaseTable o)
{
lock (Compiler.Tasks)
{
var task = GetTaskIfExists(o);
if (task == null)
return;
if (task is CacheableTask c)
ClearCacheFor(new ICacheableTask[] { c });
Compiler.CancelTask(task, true);
}
}
public void ClearAllCaches()
{
ClearCacheFor(Compiler.Tasks.Keys.OfType<ICacheableTask>().Where(t => !t.IsCacheableWhenFinished()).ToArray());
}
public void ClearCacheFor(ICacheableTask[] tasks)
{
var manager = new CachedAggregateConfigurationResultsManager(QueryCachingServer);
foreach (var t in tasks)
try
{
t.ClearYourselfFromCache(manager);
Compiler.CancelTask(t, true);
}
catch (Exception exception)
{
Activator.ShowException($"Could not clear cache for task {t}", exception);
}
RecreateAllTasks();
}
#region Job control
public enum Operation
{
Execute,
Cancel,
Clear,
None
}
public Operation PlanGlobalOperation()
{
var allTasks = GetAllTasks();
//if any are still executing or scheduled for execution
if (allTasks.Any(t =>
t.State == CompilationState.Executing || t.State == CompilationState.Building ||
t.State == CompilationState.Scheduled))
return Operation.Cancel;
//if all are complete
return Operation.Execute;
}
#endregion
public ICompileable[] GetAllTasks() => Compiler.Tasks.Keys.ToArray();
/// <summary>
/// Considers the state of <see cref="Compiler"/> to check for still running
/// processes. Returns true to cancel closing (also informs user that closing
/// cannot happen right now).
/// </summary>
/// <returns></returns>
public bool ConsultAboutClosing()
{
if (Compiler != null)
{
var aliveCount = Compiler.GetAliveThreadCount();
if (aliveCount > 0)
{
Activator.Show("Confirm Close",
$"There are {aliveCount} Tasks currently executing, you must cancel them before closing");
return true;
}
Compiler.CancelAllTasks(true);
}
return false;
}
/// <summary>
/// Inspects the state of the object and either starts its execution or
/// cancels it. See <see cref="ExecuteAspectGetter(object)"/> to display
/// the appropriate message to the user
/// </summary>
/// <param name="o"></param>
/// <param name="userDefinedTimeout"></param>
public void ExecuteOrCancel(object o, int? userDefinedTimeout)
{
Task.Run(() =>
{
switch (o)
{
case AggregateConfiguration aggregate:
{
var joinable = aggregate.JoinableCohortAggregateConfiguration;
if (joinable != null)
OrderActivity(GetNextOperation(GetState(joinable)), joinable, userDefinedTimeout);
else
OrderActivity(GetNextOperation(GetState(aggregate)), aggregate, userDefinedTimeout);
break;
}
case CohortAggregateContainer container:
OrderActivity(GetNextOperation(GetState(container)), container, userDefinedTimeout);
break;
}
});
}
public void StartAll(Action afterDelegate, EventHandler onRunnerPhaseChanged, int? userDefinedTimeout)
{
//only allow starting all if we are not mid execution already
if (IsExecutingGlobalOperations())
return;
_cancelGlobalOperations = new CancellationTokenSource();
Runner = new CohortCompilerRunner(Compiler, userDefinedTimeout ?? Timeout);
Runner.PhaseChanged += onRunnerPhaseChanged;
Task.Run(() =>
{
try
{
Runner.Run(_cancelGlobalOperations.Token);
}
catch (Exception e)
{
Activator.ShowException("Runner crashed", e);
}
}).ContinueWith((_, _) => { afterDelegate(); }, TaskScheduler.FromCurrentSynchronizationContext());
}
}