-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Expand file tree
/
Copy pathworkflow-run-count.repository.ts
More file actions
303 lines (268 loc) · 8.52 KB
/
workflow-run-count.repository.ts
File metadata and controls
303 lines (268 loc) · 8.52 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
import { Injectable } from '@nestjs/common';
import { PinoLogger } from 'nestjs-pino';
import { FeatureFlagsService } from '../../feature-flags/feature-flags.service';
import { ClickHouseService } from '../clickhouse.service';
import { LogRepository } from '../log.repository';
import {
WORKFLOW_RUN_COUNT_ORDER_BY,
WORKFLOW_RUN_COUNT_TABLE_NAME,
WorkflowRunCount,
workflowRunCountSchema,
} from './workflow-run-count.schema';
@Injectable()
export class WorkflowRunCountRepository extends LogRepository<typeof workflowRunCountSchema, WorkflowRunCount> {
public readonly table = WORKFLOW_RUN_COUNT_TABLE_NAME;
public readonly identifierPrefix = 'wrc_';
constructor(
protected readonly clickhouseService: ClickHouseService,
protected readonly logger: PinoLogger,
protected readonly featureFlagsService: FeatureFlagsService
) {
super(clickhouseService, logger, workflowRunCountSchema, WORKFLOW_RUN_COUNT_ORDER_BY, featureFlagsService);
this.logger.setContext(this.constructor.name);
}
async getTotalInteractionsCount(environmentIds: string[], startDate: Date, endDate: Date): Promise<number> {
if (environmentIds.length === 0) {
this.logger.info(
{ method: 'getTotalInteractionsCount' },
'Skipping workflow run count query: environmentIds is empty (prevents invalid IN clause)'
);
return 0;
}
const query = `
SELECT sum(count) as total
FROM ${WORKFLOW_RUN_COUNT_TABLE_NAME}
WHERE
environment_id IN {environmentIds:Array(String)}
AND date >= {startDate:Date}
AND date <= {endDate:Date}
AND event_type = 'workflow_run_delivery_interacted'
`;
const params: Record<string, unknown> = {
environmentIds,
startDate: startDate.toISOString().split('T')[0],
endDate: endDate.toISOString().split('T')[0],
};
const result = await this.clickhouseService.query<{ total: string }>({
query,
params,
});
return parseInt(result.data[0]?.total || '0', 10);
}
async getTopWorkflows(
environmentIds: string[],
startDate: Date,
endDate: Date,
limit: number = 5
): Promise<Array<{ workflow_run_id: string; count: string }>> {
if (environmentIds.length === 0) {
this.logger.info(
{ method: 'getTopWorkflows' },
'Skipping workflow run count query: environmentIds is empty (prevents invalid IN clause)'
);
return [];
}
const query = `
SELECT
workflow_run_id,
sum(count) as count
FROM ${WORKFLOW_RUN_COUNT_TABLE_NAME}
WHERE
environment_id IN {environmentIds:Array(String)}
AND date >= {startDate:Date}
AND date <= {endDate:Date}
AND event_type = 'workflow_run_delivery_sent'
GROUP BY workflow_run_id
ORDER BY count DESC
LIMIT {limit:UInt32}
`;
const params: Record<string, unknown> = {
environmentIds,
startDate: startDate.toISOString().split('T')[0],
endDate: endDate.toISOString().split('T')[0],
limit,
};
const result = await this.clickhouseService.query<{
workflow_run_id: string;
count: string;
}>({
query,
params,
});
return result.data;
}
async getUsageReportStats(
environmentIds: string[],
startDate: Date,
endDate: Date
): Promise<{
totalCreated: number;
totalRuns: number;
successRate: number;
failureRate: number;
}> {
if (environmentIds.length === 0) {
this.logger.info(
{ method: 'getUsageReportStats' },
'Skipping workflow run count query: environmentIds is empty (prevents invalid IN clause)'
);
return { totalCreated: 0, totalRuns: 0, successRate: 0, failureRate: 0 };
}
const query = `
SELECT
sumIf(count, event_type = 'workflow_run_status_processing') as total_created,
sumIf(count, event_type = 'workflow_run_status_completed') as succeeded,
sumIf(count, event_type = 'workflow_run_status_error') as failed
FROM ${WORKFLOW_RUN_COUNT_TABLE_NAME}
WHERE
environment_id IN {environmentIds:Array(String)}
AND date >= {startDate:Date}
AND date <= {endDate:Date}
AND event_type IN (
'workflow_run_status_processing',
'workflow_run_status_completed',
'workflow_run_status_error'
)
`;
const params: Record<string, unknown> = {
environmentIds,
startDate: startDate.toISOString().split('T')[0],
endDate: endDate.toISOString().split('T')[0],
};
const result = await this.clickhouseService.query<{
total_created: string;
succeeded: string;
failed: string;
}>({
query,
params,
});
const stats = result.data[0] || {
total_created: '0',
succeeded: '0',
failed: '0',
};
const totalCreated = parseInt(stats.total_created, 10);
const succeeded = parseInt(stats.succeeded, 10);
const failed = parseInt(stats.failed, 10);
const totalRuns = succeeded + failed;
const successRate = totalRuns > 0 ? Math.round((succeeded / totalRuns) * 100) : 0;
const failureRate = totalRuns > 0 ? Math.max(0, 100 - successRate) : 0;
return {
totalCreated,
totalRuns,
successRate,
failureRate,
};
}
async getActiveOrganizationIds(
startDate: Date,
endDate: Date,
minWorkflowRuns: number = 500,
minSentMessages: number = 100
): Promise<string[]> {
const query = `
SELECT
organization_id,
sumIf(count, event_type = 'workflow_run_status_processing') as total_workflow_runs,
sumIf(count, event_type = 'workflow_run_delivery_sent') as total_sent_messages
FROM ${WORKFLOW_RUN_COUNT_TABLE_NAME}
WHERE
date >= {startDate:Date}
AND date <= {endDate:Date}
GROUP BY organization_id
HAVING total_workflow_runs >= {minWorkflowRuns:UInt32}
AND total_sent_messages >= {minSentMessages:UInt32}
`;
const params: Record<string, unknown> = {
startDate: startDate.toISOString().split('T')[0],
endDate: endDate.toISOString().split('T')[0],
minWorkflowRuns,
minSentMessages,
};
const result = await this.clickhouseService.query<{
organization_id: string;
total_workflow_runs: string;
total_sent_messages: string;
}>({
query,
params,
});
return result.data.map((row) => row.organization_id);
}
async getWorkflowVolumeData(
environmentId: string,
organizationId: string,
startDate: Date,
endDate: Date,
limit: number = 5
): Promise<Array<{ workflow_run_id: string; count: string }>> {
const query = `
SELECT
workflow_run_id,
sum(count) as count
FROM ${WORKFLOW_RUN_COUNT_TABLE_NAME}
WHERE
environment_id = {environmentId:String}
AND organization_id = {organizationId:String}
AND date >= {startDate:Date}
AND date <= {endDate:Date}
AND event_type = 'workflow_run_status_processing'
GROUP BY workflow_run_id
ORDER BY count DESC
LIMIT {limit:UInt32}
`;
const params: Record<string, unknown> = {
environmentId,
organizationId,
startDate: startDate.toISOString().split('T')[0],
endDate: endDate.toISOString().split('T')[0],
limit,
};
const result = await this.clickhouseService.query<{
workflow_run_id: string;
count: string;
}>({
query,
params,
});
return result.data;
}
async getWorkflowRunsTrendData(
environmentId: string,
organizationId: string,
startDate: Date,
endDate: Date
): Promise<Array<{ date: string; event_type: string; count: string }>> {
const query = `
SELECT
date,
event_type,
sum(count) as count
FROM ${WORKFLOW_RUN_COUNT_TABLE_NAME}
WHERE
environment_id = {environmentId:String}
AND organization_id = {organizationId:String}
AND date >= {startDate:Date}
AND date <= {endDate:Date}
AND event_type IN ('workflow_run_status_processing', 'workflow_run_status_completed', 'workflow_run_status_error')
GROUP BY date, event_type
ORDER BY date, event_type
`;
const params: Record<string, unknown> = {
environmentId,
organizationId,
startDate: startDate.toISOString().split('T')[0],
endDate: endDate.toISOString().split('T')[0],
};
const result = await this.clickhouseService.query<{
date: string;
event_type: string;
count: string;
}>({
query,
params,
});
return result.data;
}
}