-
Notifications
You must be signed in to change notification settings - Fork 10.6k
/
Copy pathindex.ts
233 lines (199 loc) · 6.55 KB
/
index.ts
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
import axios from 'axios';
import type RudderStack from '@rudderstack/rudder-sdk-node';
import { PostHogClient } from '@/posthog';
import { Container, Service } from 'typedi';
import type { ITelemetryTrackProperties } from 'n8n-workflow';
import { InstanceSettings } from 'n8n-core';
import config from '@/config';
import type { IExecutionTrackProperties } from '@/Interfaces';
import { Logger } from '@/Logger';
import { License } from '@/License';
import { N8N_VERSION } from '@/constants';
import { WorkflowRepository } from '@db/repositories/workflow.repository';
import { SourceControlPreferencesService } from '../environments/sourceControl/sourceControlPreferences.service.ee';
import { UserRepository } from '@db/repositories/user.repository';
import { ProjectRepository } from '@/databases/repositories/project.repository';
import { ProjectRelationRepository } from '@/databases/repositories/projectRelation.repository';
type ExecutionTrackDataKey = 'manual_error' | 'manual_success' | 'prod_error' | 'prod_success';
interface IExecutionTrackData {
count: number;
first: Date;
}
interface IExecutionsBuffer {
[workflowId: string]: {
manual_error?: IExecutionTrackData;
manual_success?: IExecutionTrackData;
prod_error?: IExecutionTrackData;
prod_success?: IExecutionTrackData;
user_id: string | undefined;
};
}
@Service()
export class Telemetry {
private rudderStack?: RudderStack;
private pulseIntervalReference: NodeJS.Timeout;
private executionCountsBuffer: IExecutionsBuffer = {};
constructor(
private readonly logger: Logger,
private readonly postHog: PostHogClient,
private readonly license: License,
private readonly instanceSettings: InstanceSettings,
private readonly workflowRepository: WorkflowRepository,
) {}
async init() {
const enabled = config.getEnv('diagnostics.enabled');
if (enabled) {
const conf = config.getEnv('diagnostics.config.backend');
const [key, dataPlaneUrl] = conf.split(';');
if (!key || !dataPlaneUrl) {
this.logger.warn('Diagnostics backend config is invalid');
return;
}
const logLevel = config.getEnv('logs.level');
const { default: RudderStack } = await import('@rudderstack/rudder-sdk-node');
const axiosInstance = axios.create();
axiosInstance.interceptors.request.use((cfg) => {
cfg.headers.setContentType('application/json', false);
return cfg;
});
this.rudderStack = new RudderStack(key, {
axiosInstance,
logLevel,
dataPlaneUrl,
gzip: false,
});
this.startPulse();
}
}
private startPulse() {
this.pulseIntervalReference = setInterval(
async () => {
void this.pulse();
},
6 * 60 * 60 * 1000,
); // every 6 hours
}
private async pulse(): Promise<unknown> {
if (!this.rudderStack) {
return;
}
const allPromises = Object.keys(this.executionCountsBuffer)
.filter((workflowId) => {
const data = this.executionCountsBuffer[workflowId];
const sum =
(data.manual_error?.count ?? 0) +
(data.manual_success?.count ?? 0) +
(data.prod_error?.count ?? 0) +
(data.prod_success?.count ?? 0);
return sum > 0;
})
.map(async (workflowId) => {
const promise = this.track('Workflow execution count', {
event_version: '2',
workflow_id: workflowId,
...this.executionCountsBuffer[workflowId],
});
return await promise;
});
this.executionCountsBuffer = {};
const sourceControlPreferences = Container.get(
SourceControlPreferencesService,
).getPreferences();
// License info
const pulsePacket = {
plan_name_current: this.license.getPlanName(),
quota: this.license.getTriggerLimit(),
usage: await this.workflowRepository.getActiveTriggerCount(),
role_count: await Container.get(UserRepository).countUsersByRole(),
source_control_set_up: Container.get(SourceControlPreferencesService).isSourceControlSetup(),
branchName: sourceControlPreferences.branchName,
read_only_instance: sourceControlPreferences.branchReadOnly,
team_projects: (await Container.get(ProjectRepository).getProjectCounts()).team,
project_role_count: await Container.get(ProjectRelationRepository).countUsersByRole(),
};
allPromises.push(this.track('pulse', pulsePacket));
return await Promise.all(allPromises);
}
async trackWorkflowExecution(properties: IExecutionTrackProperties): Promise<void> {
if (this.rudderStack) {
const execTime = new Date();
const workflowId = properties.workflow_id;
this.executionCountsBuffer[workflowId] = this.executionCountsBuffer[workflowId] ?? {
user_id: properties.user_id,
};
const key: ExecutionTrackDataKey = `${properties.is_manual ? 'manual' : 'prod'}_${
properties.success ? 'success' : 'error'
}`;
const executionTrackDataKey = this.executionCountsBuffer[workflowId][key];
if (!executionTrackDataKey) {
this.executionCountsBuffer[workflowId][key] = {
count: 1,
first: execTime,
};
} else {
executionTrackDataKey.count++;
}
if (
!properties.success &&
properties.is_manual &&
properties.error_node_type?.startsWith('n8n-nodes-base')
) {
void this.track('Workflow execution errored', properties);
}
}
}
async trackN8nStop(): Promise<void> {
clearInterval(this.pulseIntervalReference);
await this.track('User instance stopped');
void Promise.all([this.postHog.stop(), this.rudderStack?.flush()]);
}
async identify(traits?: {
[key: string]: string | number | boolean | object | undefined | null;
}): Promise<void> {
const { instanceId } = this.instanceSettings;
return await new Promise<void>((resolve) => {
if (this.rudderStack) {
this.rudderStack.identify(
{
userId: instanceId,
traits: { ...traits, instanceId },
},
resolve,
);
} else {
resolve();
}
});
}
async track(
eventName: string,
properties: ITelemetryTrackProperties = {},
{ withPostHog } = { withPostHog: false }, // whether to additionally track with PostHog
): Promise<void> {
const { instanceId } = this.instanceSettings;
return await new Promise<void>((resolve) => {
if (this.rudderStack) {
const { user_id } = properties;
const updatedProperties = {
...properties,
instance_id: instanceId,
version_cli: N8N_VERSION,
};
const payload = {
userId: `${instanceId}${user_id ? `#${user_id}` : ''}`,
event: eventName,
properties: updatedProperties,
};
if (withPostHog) {
this.postHog?.track(payload);
}
return this.rudderStack.track(payload, resolve);
}
return resolve();
});
}
// test helpers
getCountsBuffer(): IExecutionsBuffer {
return this.executionCountsBuffer;
}
}