-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathGanttDiagramTabState.ts
More file actions
300 lines (213 loc) · 11.2 KB
/
GanttDiagramTabState.ts
File metadata and controls
300 lines (213 loc) · 11.2 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import mermaid from 'mermaid';
import moment from 'moment';
import { DurableOrchestrationStatus, HistoryEvent, EventWithHistory } from '../DurableOrchestrationStatus';
import { MermaidDiagramTabState } from './MermaidDiagramTabState';
import { CancelToken } from '../../CancelToken';
import { dfmContextInstance } from '../../DfmContext';
type LineTextAndMetadata = { nextLine: string, functionName?: string, instanceId?: string, parentInstanceId?: string, duration?: number, widthPercentage?: number };
const MaxEventsBeforeStartAggregating = 500;
const TimestampIntervalInMsForAggregating = 500;
const MaxAggregatedEvents = 100;
const EventTypesToBeAggregated = ['TaskCompleted', 'TaskFailed', 'TimerFired'];
// State of Gantt Diagram tab on OrchestrationDetails view
export class GanttDiagramTabState extends MermaidDiagramTabState {
readonly name: string = "Gantt Chart";
protected buildDiagram(details: DurableOrchestrationStatus, history: HistoryEvent[], cancelToken: CancelToken): Promise<void> {
return this.loadSubOrchestrations(history as EventWithHistory[])
.then(history => {
return this.renderOrchestration(details.instanceId, details.name, history, true);
})
.then(lines => {
if (cancelToken.isCancelled) {
return;
}
const linesWithMetadata = lines.filter(l => !!l.functionName);
this._diagramCode = 'gantt \n' +
`title ${details.name}(${details.instanceId}) \n` +
'dateFormat YYYY-MM-DDTHH:mm:ss.SSS \n' +
lines.map(item => item.nextLine).join('');
return this.renderDiagram(linesWithMetadata);
}
);
}
// Promisifies diagram rendering
private renderDiagram(linesWithMetadata: LineTextAndMetadata[]): Promise<void> {
// Very much unknown, why this line is needed. Without it sometimes the diagrams fail to re-render
this._diagramSvg = '';
return new Promise<void>((resolve, reject) => {
try {
mermaid.render('mermaidSvgId', this._diagramCode).then(result => {
let svg = result.svg;
svg = this.injectFunctionNameAttributes(svg, linesWithMetadata);
this._diagramSvg = svg;
resolve();
}, err => {
reject(err);
});
} catch (err) {
reject(err);
}
});
}
// Adds data-function-name attributes to diagram lines, so that Function names can be further used by rendering
private injectFunctionNameAttributes(svg: string, linesWithMetadata: LineTextAndMetadata[]): string {
return svg.replace(new RegExp(`<(rect|text) id="task([0-9]+)(-text)?"`, 'gi'), (match, tagName, taskIndex) => {
const oneBasedLineIndex = parseInt(taskIndex);
if (oneBasedLineIndex <= 0 || oneBasedLineIndex > linesWithMetadata.length) {
return match;
}
const lineMetadata = linesWithMetadata[oneBasedLineIndex - 1];
if (!lineMetadata.functionName) {
return match;
}
return match + ` data-function-name="${lineMetadata.functionName}"`;
});
}
private renderOrchestration(orchestrationId: string, orchestrationName: string, historyEvents: EventWithHistory[], isParentOrchestration: boolean): LineTextAndMetadata[] {
const results: LineTextAndMetadata[] = [];
const startedEvent = historyEvents.find(event => event.eventType === 'ExecutionStarted');
const completedEvent = historyEvents.find(event => event.eventType === 'ExecutionCompleted');
var needToAddAxisFormat = isParentOrchestration;
var nextLine: string;
var orchDuration = 0;
if (!!startedEvent && !!completedEvent) {
if (needToAddAxisFormat) {
// Axis format should always appear on top, prior to all other lines - this is why it looks a bit complicated.
const longerThanADay = completedEvent.durationInMs > 86400000;
nextLine = longerThanADay ? 'axisFormat %Y-%m-%d %H:%M \n' : 'axisFormat %H:%M:%S \n';
results.push({ nextLine });
needToAddAxisFormat = false;
}
nextLine = isParentOrchestration ? '' : `section ${orchestrationName}(${this.escapeTitle(orchestrationId)}) \n`;
var lineName = this.formatDuration(completedEvent.durationInMs);
if (!lineName) {
lineName = this.formatLineName(orchestrationName, 0);
}
nextLine += `${lineName}: ${isParentOrchestration ? '' : 'active,'} ${this.formatDateTime(startedEvent.timestamp)}, ${completedEvent.durationInMs}ms \n`;
results.push({ nextLine, functionName: orchestrationName, instanceId: orchestrationId });
orchDuration = completedEvent.durationInMs;
}
if (needToAddAxisFormat) {
nextLine = 'axisFormat %H:%M:%S \n';
results.push({ nextLine });
}
for (let i = 0; i < historyEvents.length; i++) {
let event = historyEvents[i];
let numOfAggregatedEvents = 0;
// If too many events, then trying to aggregate
if (historyEvents.length > MaxEventsBeforeStartAggregating && EventTypesToBeAggregated.includes(event.eventType)) {
const scheduledTimeInMs = Date.parse(event.scheduledTime);
let maxDurationInMs = event.durationInMs;
let j = i + 1;
while (j < historyEvents.length) {
const nextScheduledTimeInMs = Date.parse(historyEvents[j].scheduledTime);
if (
(MaxAggregatedEvents <= j - i)
||
(historyEvents[j].eventType !== event.eventType)
||
(historyEvents[j].name !== event.name)
||
(TimestampIntervalInMsForAggregating < nextScheduledTimeInMs - scheduledTimeInMs)
) {
break;
}
const nextDurationInMs = (nextScheduledTimeInMs - scheduledTimeInMs) + historyEvents[j].durationInMs;
if (nextDurationInMs > maxDurationInMs) {
maxDurationInMs = nextDurationInMs;
}
j++;
}
if (j > i + 1) {
numOfAggregatedEvents = j - i;
event.durationInMs = maxDurationInMs;
i = j - 1;
}
}
var eventTimestamp = event.scheduledTime;
// Sometimes activity timestamp might appear to be earlier than orchestration start (due to machine time difference, I assume),
// and that breaks the diagram
if (!!startedEvent && (Date.parse(eventTimestamp) < Date.parse(startedEvent.timestamp))) {
eventTimestamp = startedEvent.timestamp;
}
switch (event.eventType) {
case 'SubOrchestrationInstanceCompleted':
case 'SubOrchestrationInstanceFailed':
if (!!event.subOrchestrationId && !!event.history) {
const subOrchestrationId = event.subOrchestrationId;
const subOrchestrationName = event.name;
results.push(...this.renderOrchestration(subOrchestrationId, subOrchestrationName, event.history, false));
nextLine = `section ${orchestrationName}(${this.escapeTitle(orchestrationId)}) \n`;
results.push({ nextLine });
}
break;
case 'TaskCompleted':
nextLine = `${this.formatLineName(event.name, numOfAggregatedEvents)} ${this.formatDuration(event.durationInMs)}: done, ${this.formatDateTime(eventTimestamp)}, ${event.durationInMs}ms \n`;
results.push({
nextLine,
functionName: event.name,
parentInstanceId: orchestrationId,
duration: event.durationInMs,
widthPercentage: orchDuration ? event.durationInMs / orchDuration : 0
});
break;
case 'TaskFailed':
nextLine = `${this.formatLineName(event.name, numOfAggregatedEvents)} ${this.formatDuration(event.durationInMs)}: crit, ${this.formatDateTime(eventTimestamp)}, ${event.durationInMs}ms \n`;
results.push({
nextLine,
functionName: event.name,
parentInstanceId: orchestrationId,
duration: event.durationInMs,
widthPercentage: orchDuration ? event.durationInMs / orchDuration : 0
});
break;
case 'TimerFired':
nextLine = `[TimerFired]: milestone, ${this.formatDateTime(event.timestamp)}, 0s \n`;
results.push({
nextLine,
functionName: orchestrationName,
parentInstanceId: orchestrationId
});
break;
}
}
return results;
}
// Loads the full hierarchy of orchestrations/suborchestrations
private loadSubOrchestrations(history: EventWithHistory[]): Promise<EventWithHistory[]> {
const promises: Promise<void>[] = [];
for (const event of history) {
switch (event.eventType) {
case "SubOrchestrationInstanceCompleted":
case "SubOrchestrationInstanceFailed":
promises.push(
this._loadHistory(event.subOrchestrationId)
.then(subHistory => this.loadSubOrchestrations(subHistory as any))
.then(subHistory => {
event.history = subHistory;
})
.catch(err => {
console.log(`Failed to load ${event.subOrchestrationId}. ${err.message}`);
})
);
break;
}
}
return Promise.all(promises).then(() => { return history as EventWithHistory[]; })
}
private formatDateTime(utcDateTimeString: string): string {
if (!dfmContextInstance.showTimeAsLocal) {
return utcDateTimeString.substr(0, 23);
}
return moment(utcDateTimeString).format('YYYY-MM-DDTHH:mm:ss.SSS')
}
private formatLineName(name: string, numOfTimes: number): string {
name = name.replace(/:/g, '-');
if (numOfTimes > 0) {
name += ` <<${numOfTimes} events>>`
}
return name;
}
}