chore: Convert ErrorReporting to a Service to use DI. Add some tests (no-changelog) (#11279)

This commit is contained in:
कारतोफ्फेलस्क्रिप्ट™
2024-12-11 15:36:17 +01:00
committed by GitHub
parent 5300e0ac45
commit 73145b70b8
49 changed files with 443 additions and 386 deletions

View File

@@ -11,7 +11,6 @@ import type {
} from 'n8n-workflow';
import {
ApplicationError,
ErrorReporterProxy as ErrorReporter,
LoggerProxy as Logger,
toCronExpression,
TriggerCloseError,
@@ -20,12 +19,16 @@ import {
} from 'n8n-workflow';
import { Service } from 'typedi';
import { ErrorReporter } from './error-reporter';
import type { IWorkflowData } from './Interfaces';
import { ScheduledTaskManager } from './ScheduledTaskManager';
@Service()
export class ActiveWorkflows {
constructor(private readonly scheduledTaskManager: ScheduledTaskManager) {}
constructor(
private readonly scheduledTaskManager: ScheduledTaskManager,
private readonly errorReporter: ErrorReporter,
) {}
private activeWorkflows: { [workflowId: string]: IWorkflowData } = {};
@@ -218,7 +221,7 @@ export class ActiveWorkflows {
Logger.error(
`There was a problem calling "closeFunction" on "${e.node.name}" in workflow "${workflowId}"`,
);
ErrorReporter.error(e, { extra: { workflowId } });
this.errorReporter.error(e, { extra: { workflowId } });
return;
}

View File

@@ -46,11 +46,12 @@ import {
ApplicationError,
NodeExecutionOutput,
sleep,
ErrorReporterProxy,
ExecutionCancelledError,
} from 'n8n-workflow';
import PCancelable from 'p-cancelable';
import Container from 'typedi';
import { ErrorReporter } from './error-reporter';
import * as NodeExecuteFunctions from './NodeExecuteFunctions';
import {
DirectedGraph,
@@ -1428,7 +1429,7 @@ export class WorkflowExecute {
toReport = error;
}
if (toReport) {
ErrorReporterProxy.error(toReport, {
Container.get(ErrorReporter).error(toReport, {
extra: {
nodeName: executionNode.name,
nodeType: executionNode.type,

View File

@@ -0,0 +1,171 @@
import { GlobalConfig } from '@n8n/config';
import type { NodeOptions } from '@sentry/node';
import type { ErrorEvent, EventHint } from '@sentry/types';
import { AxiosError } from 'axios';
import { ApplicationError, LoggerProxy, type ReportingOptions } from 'n8n-workflow';
import { createHash } from 'node:crypto';
import { Service } from 'typedi';
import { InstanceSettings } from './InstanceSettings';
@Service()
export class ErrorReporter {
private initialized = false;
/** Hashes of error stack traces, to deduplicate error reports. */
private seenErrors = new Set<string>();
private report: (error: Error | string, options?: ReportingOptions) => void;
constructor(
private readonly globalConfig: GlobalConfig,
private readonly instanceSettings: InstanceSettings,
) {
// eslint-disable-next-line @typescript-eslint/unbound-method
this.report = this.defaultReport;
}
private defaultReport(error: Error | string, options?: ReportingOptions) {
if (error instanceof Error) {
let e = error;
const { executionId } = options ?? {};
const context = executionId ? ` (execution ${executionId})` : '';
do {
const msg = [e.message + context, e.stack ? `\n${e.stack}\n` : ''].join('');
const meta = e instanceof ApplicationError ? e.extra : undefined;
LoggerProxy.error(msg, meta);
e = e.cause as Error;
} while (e);
}
}
async init() {
if (this.initialized) return;
process.on('uncaughtException', (error) => {
this.error(error);
});
const dsn = this.globalConfig.sentry.backendDsn;
if (!dsn) {
this.initialized = true;
return;
}
// Collect longer stacktraces
Error.stackTraceLimit = 50;
const {
N8N_VERSION: release,
ENVIRONMENT: environment,
DEPLOYMENT_NAME: serverName,
} = process.env;
const { init, captureException, setTag } = await import('@sentry/node');
const { requestDataIntegration, rewriteFramesIntegration } = await import('@sentry/node');
const enabledIntegrations = [
'InboundFilters',
'FunctionToString',
'LinkedErrors',
'OnUnhandledRejection',
'ContextLines',
];
init({
dsn,
release,
environment,
enableTracing: false,
serverName,
beforeBreadcrumb: () => null,
beforeSend: this.beforeSend.bind(this) as NodeOptions['beforeSend'],
integrations: (integrations) => [
...integrations.filter(({ name }) => enabledIntegrations.includes(name)),
rewriteFramesIntegration({ root: process.cwd() }),
requestDataIntegration({
include: {
cookies: false,
data: false,
headers: false,
query_string: false,
url: true,
user: false,
},
}),
],
});
setTag('server_type', this.instanceSettings.instanceType);
this.report = (error, options) => captureException(error, options);
this.initialized = true;
}
async beforeSend(event: ErrorEvent, { originalException }: EventHint) {
if (!originalException) return null;
if (originalException instanceof Promise) {
originalException = await originalException.catch((error) => error as Error);
}
if (originalException instanceof AxiosError) return null;
if (
originalException instanceof Error &&
originalException.name === 'QueryFailedError' &&
['SQLITE_FULL', 'SQLITE_IOERR'].some((errMsg) => originalException.message.includes(errMsg))
) {
return null;
}
if (originalException instanceof ApplicationError) {
const { level, extra, tags } = originalException;
if (level === 'warning') return null;
event.level = level;
if (extra) event.extra = { ...event.extra, ...extra };
if (tags) event.tags = { ...event.tags, ...tags };
}
if (
originalException instanceof Error &&
'cause' in originalException &&
originalException.cause instanceof Error &&
'level' in originalException.cause &&
originalException.cause.level === 'warning'
) {
// handle underlying errors propagating from dependencies like ai-assistant-sdk
return null;
}
if (originalException instanceof Error && originalException.stack) {
const eventHash = createHash('sha1').update(originalException.stack).digest('base64');
if (this.seenErrors.has(eventHash)) return null;
this.seenErrors.add(eventHash);
}
return event;
}
error(e: unknown, options?: ReportingOptions) {
const toReport = this.wrap(e);
if (toReport) this.report(toReport, options);
}
warn(warning: Error | string, options?: ReportingOptions) {
this.error(warning, { ...options, level: 'warning' });
}
info(msg: string, options?: ReportingOptions) {
this.report(msg, { ...options, level: 'info' });
}
private wrap(e: unknown) {
if (e instanceof Error) return e;
if (typeof e === 'string') return new ApplicationError(e);
return;
}
}

View File

@@ -21,3 +21,4 @@ export { isStoredMode as isValidNonDefaultMode } from './BinaryData/utils';
export * from './ExecutionMetadata';
export * from './node-execution-context';
export * from './PartialExecutionUtils';
export { ErrorReporter } from './error-reporter';