Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rate limit error reporting #694

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions src/main/util/rateLimiter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/**
* Code initially taken from https://github.com/wankdanker/node-function-rate-limit
* MIT License - Copyright (c) 2012 Daniel L. VerWeire
*/

/**
* Rate limiting utility function
* @param limitCount Maximum number of calls allowed within the interval
* @param limitInterval Time interval in milliseconds
* @param fn Function to be rate limited
* @returns Rate limited version of the function
*/
export function rateLimit<T extends (...args: any[]) => any>(
limitCount: number,
limitInterval: number,
fn: T
): T {
type Context = ThisParameterType<T>;
type Args = Parameters<T>;
type QueueItem = [Context, Args];

const fifo: QueueItem[] = [];
let count = limitCount;

function callNext(args?: QueueItem) {
setTimeout(() => {
if (fifo.length > 0) {
callNext();
} else {
count = count + 1;
}
}, limitInterval);

const callArgs = fifo.shift();

// if there is no next item in the queue
// and we were called with args, trigger function immediately
if (!callArgs && args) {
fn.apply(args[0], args[1]);
return;
}

if (callArgs) {
fn.apply(callArgs[0], callArgs[1]);
}
}

return function rateLimitedFunction(this: Context, ...args: Args): ReturnType<T> {
const ctx = this;

if (count <= 0) {
fifo.push([ctx, args]);
return undefined as ReturnType<T>;
}

count = count - 1;
callNext([ctx, args]);
return undefined as ReturnType<T>;
} as T;
}
29 changes: 22 additions & 7 deletions src/main/util/sentryWinstonTransport.ts
Original file line number Diff line number Diff line change
@@ -3,6 +3,7 @@
*/
import * as Sentry from '@sentry/electron/main';
import TransportStream from 'winston-transport';
import { rateLimit } from './rateLimiter.js';
// import { LEVEL } from 'triple-beam';

enum SentrySeverity {
@@ -47,21 +48,24 @@ class ExtendedError extends Error {

export default class SentryTransport extends TransportStream {
public silent = false;

private levelsMap: SeverityOptions = {};
private normalLogRateLimiter: (info: any, callback: () => void) => void;

public constructor(opts?: SentryTransportOptions) {
super(opts);

this.levelsMap = this.setLevelsMap(opts?.levelsMap);
this.silent = opts?.silent || false;

// Only rate limit normal logs, not errors
this.normalLogRateLimiter = rateLimit(10, 1000, this.processLog.bind(this));

if (!opts || !opts.skipSentryInit) {
Sentry.init(SentryTransport.withDefaults(opts?.sentry || {}));
}
}

public log(info: any, callback: () => void) {
private processLog(info: any, callback: () => void) {
setImmediate(() => {
this.emit('logged', info);
});
@@ -99,19 +103,30 @@ export default class SentryTransport extends TransportStream {
// // ...
// });

// Capturing Errors / Exceptions
// Capturing Errors / Exceptions - bypass rate limiting
if (SentryTransport.shouldLogException(sentryLevel)) {
const error =
Object.values(info).find((value) => value instanceof Error) ??
new ExtendedError(info);
Sentry.captureException(error, { tags });

return callback();
callback();
return;
}

// Capturing Messages
// Normal messages go through rate limiting
Sentry.captureMessage(message, sentryLevel);
return callback();
callback();
}

public log(info: any, callback: () => void) {
// Errors and fatal logs bypass rate limiting
if (SentryTransport.shouldLogException(this.levelsMap[info.level])) {
this.processLog(info, callback);
return;
}

// Normal logs are rate limited
this.normalLogRateLimiter(info, callback);
}

end(...args: any[]) {