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

Callbacks perf #14915

Merged
merged 23 commits into from
Jul 4, 2019
Merged
Show file tree
Hide file tree
Changes from 22 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
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
2 changes: 1 addition & 1 deletion app/2fa/server/loginHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,4 @@ callbacks.add('onValidateLogin', (login) => {
throw new Meteor.Error('totp-invalid', 'TOTP Invalid');
}
}
});
}, callbacks.priority.MEDIUM, '2fa');
132 changes: 73 additions & 59 deletions app/callbacks/lib/callbacks.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,61 @@ import { Meteor } from 'meteor/meteor';
import { Random } from 'meteor/random';
import _ from 'underscore';

let timed = false;

if (Meteor.isClient) {
const { getConfig } = require('../../ui-utils/client/config');
timed = [getConfig('debug'), getConfig('timed-callbacks')].includes('true');
}
/*
* Callback hooks provide an easy way to add extra steps to common operations.
* @namespace RocketChat.callbacks
*/

export const callbacks = {};

if (Meteor.isServer) {
callbacks.showTime = true;
callbacks.showTotalTime = true;
} else {
callbacks.showTime = false;
callbacks.showTotalTime = false;
}
const wrapCallback = (callback) => (...args) => {
const time = Date.now();
const result = callback(...args);
const currentTime = Date.now() - time;
let stack = callback.stack
&& typeof callback.stack.split === 'function'
&& callback.stack.split('\n');
stack = stack && stack[2] && (stack[2].match(/\(.+\)/) || [])[0];
console.log(String(currentTime), callback.hook, callback.id, stack);
return result;
};

const wrapRun = (hook, fn) => (...args) => {
const time = Date.now();
const ret = fn(...args);
const totalTime = Date.now() - time;
console.log(`${ hook }:`, totalTime);
return ret;
};

const handleResult = (fn) => (result, constant) => {
const callbackResult = callbacks.runItem({ hook: fn.hook, callback: fn, result, constant });
return typeof callbackResult === 'undefined' ? result : callbackResult;
};


const empty = (e) => e;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👎

tassoevan marked this conversation as resolved.
Show resolved Hide resolved
const combine = (f, x) => (e, ...constants) => x(f(e, ...constants), ...constants);
tassoevan marked this conversation as resolved.
Show resolved Hide resolved
const createCallback = (hook, callbacks) => callbacks.map(handleResult).reduce(combine, empty);
tassoevan marked this conversation as resolved.
Show resolved Hide resolved

const createCallbackTimed = (hook, callbacks) =>
wrapRun(hook,
callbacks
.map(wrapCallback)
.map(handleResult)
.reduce(combine, empty)
tassoevan marked this conversation as resolved.
Show resolved Hide resolved
);

const create = (hook, cbs) =>
(timed ? createCallbackTimed(hook, cbs) : createCallback(hook, cbs));
const combinedCallbacks = new Map();
this.combinedCallbacks = combinedCallbacks;
/*
* Callback priorities
*/
Expand All @@ -36,26 +75,24 @@ const getHooks = (hookName) => callbacks[hookName] || [];
* @param {Function} callback - The callback function
*/

callbacks.add = function(hook, callback, priority, id = Random.id()) {
if (!_.isNumber(priority)) {
priority = callbacks.priority.MEDIUM;
callbacks.add = function(
hook,
callback,
priority = callbacks.priority.MEDIUM,
id = Random.id()
) {
callbacks[hook] = getHooks(hook);
if (callbacks[hook].find((cb) => cb.id === id)) {
return;
}
callback.hook = hook;
callback.priority = priority;
callback.id = id;
callbacks[hook] = getHooks(hook);

if (callbacks.showTime === true) {
const err = new Error();
callback.stack = err.stack;
}
callback.stack = new Error().stack;

if (callbacks[hook].find((cb) => cb.id === callback.id)) {
return;
}
callbacks[hook].push(callback);
callbacks[hook] = _.sortBy(callbacks[hook], function(callback) {
return callback.priority || callbacks.priority.MEDIUM;
});
callbacks[hook] = _.sortBy(callbacks[hook], (callback) => callback.priority || callbacks.priority.MEDIUM);
combinedCallbacks.set(hook, create(hook, callbacks[hook]));
};


Expand All @@ -67,11 +104,10 @@ callbacks.add = function(hook, callback, priority, id = Random.id()) {

callbacks.remove = function(hook, id) {
callbacks[hook] = getHooks(hook).filter((callback) => callback.id !== id);
combinedCallbacks.set(hook, create(hook, callbacks[hook]));
};

callbacks.runItem = function({ callback, result, constant /* , hook */ }) {
return callback(result, constant);
};
callbacks.runItem = ({ callback, result, constant /* , hook */ }) => callback(result, constant);

/*
* Successively run all of a hook's callbacks on an item
Expand All @@ -82,38 +118,18 @@ callbacks.runItem = function({ callback, result, constant /* , hook */ }) {
*/

callbacks.run = function(hook, item, constant) {
const callbackItems = callbacks[hook];
if (!callbackItems || !callbackItems.length) {
const runner = combinedCallbacks.get(hook);
if (!runner) {
return item;
}

let totalTime = 0;
const result = callbackItems.reduce(function(result, callback) {
const time = callbacks.showTime === true || callbacks.showTotalTime === true ? Date.now() : 0;

const callbackResult = callbacks.runItem({ hook, callback, result, constant, time });

if (callbacks.showTime === true || callbacks.showTotalTime === true) {
const currentTime = Date.now() - time;
totalTime += currentTime;
if (callbacks.showTime === true) {
if (!Meteor.isServer) {
let stack = callback.stack && typeof callback.stack.split === 'function' && callback.stack.split('\n');
stack = stack && stack[2] && (stack[2].match(/\(.+\)/) || [])[0];
console.log(String(currentTime), hook, callback.id, stack);
}
}
}
return typeof callbackResult === 'undefined' ? result : callbackResult;
}, item);

if (callbacks.showTotalTime === true) {
if (!Meteor.isServer) {
console.log(`${ hook }:`, totalTime);
}
}
return runner(item, constant);

return result;
// return callbackItems.reduce(function(result, callback) {
// const callbackResult = callbacks.runItem({ hook, callback, result, constant });

// return typeof callbackResult === 'undefined' ? result : callbackResult;
// }, item);
};


Expand All @@ -124,12 +140,10 @@ callbacks.run = function(hook, item, constant) {
* @param {Object} [constant] - An optional constant that will be passed along to each callback
*/

callbacks.runAsync = function(hook, item, constant) {
callbacks.runAsync = Meteor.isServer ? function(hook, item, constant) {
const callbackItems = callbacks[hook];
if (Meteor.isServer && callbackItems && callbackItems.length) {
Meteor.defer(function() {
callbackItems.forEach((callback) => callback(item, constant));
});
if (callbackItems && callbackItems.length) {
callbackItems.forEach((callback) => Meteor.defer(function() { callback(item, constant); }));
}
return item;
};
} : () => { throw new Error('callbacks.runAsync on client server not allowed'); };
2 changes: 1 addition & 1 deletion app/discussion/server/hooks/joinDiscussionOnMessage.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,4 @@ callbacks.add('beforeSaveMessage', (message, room) => {
Meteor.runAsUser(message.u._id, () => Meteor.call('joinRoom', room._id));

return message;
});
}, callbacks.priority.MEDIUM, 'joinDiscussionOnMessage');
2 changes: 1 addition & 1 deletion app/dolphin/lib/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ if (Meteor.isServer) {
ServiceConfiguration.configurations.upsert({ service: 'dolphin' }, { $set: data });
}

callbacks.add('beforeCreateUser', DolphinOnCreateUser, callbacks.priority.HIGH);
callbacks.add('beforeCreateUser', DolphinOnCreateUser, callbacks.priority.HIGH, 'dolphin');
} else {
Meteor.startup(() =>
Tracker.autorun(function() {
Expand Down
2 changes: 1 addition & 1 deletion app/e2e/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ import './methods/requestSubscriptionKeys';

callbacks.add('afterJoinRoom', (user, room) => {
Notifications.notifyRoom('e2e.keyRequest', room._id, room.e2eKeyId);
});
}, callbacks.priority.MEDIUM, 'e2e');
2 changes: 1 addition & 1 deletion app/emoji-emojione/server/callbacks.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@ import emojione from 'emojione';
import { callbacks } from '../../callbacks';

Meteor.startup(function() {
callbacks.add('beforeSendMessageNotifications', (message) => emojione.shortnameToUnicode(message));
callbacks.add('beforeSendMessageNotifications', (message) => emojione.shortnameToUnicode(message), callbacks.priority.MEDIUM, 'emojione-shortnameToUnicode');
});
2 changes: 1 addition & 1 deletion app/google-vision/server/googlevision.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ class GoogleVision {
callbacks.remove('beforeSaveMessage', 'googlevision-blockunsafe');
}
});
callbacks.add('afterFileUpload', this.annotate.bind(this));
callbacks.add('afterFileUpload', this.annotate.bind(this), callbacks.priority.MEDIUM, 'GoogleVision');
}

incCallCount(count) {
Expand Down
2 changes: 1 addition & 1 deletion app/graphql/server/resolvers/messages/chatMessageAdded.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const resolver = {

callbacks.add('afterSaveMessage', (message) => {
publishMessage(message);
}, null, 'chatMessageAddedSubscription');
}, callbacks.priority.MEDIUM, 'chatMessageAddedSubscription');

export {
schema,
Expand Down
16 changes: 8 additions & 8 deletions app/integrations/server/triggers.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ const callbackHandler = function _callbackHandler(eventType) {
};
};

callbacks.add('afterSaveMessage', callbackHandler('sendMessage'), callbacks.priority.LOW);
callbacks.add('afterCreateChannel', callbackHandler('roomCreated'), callbacks.priority.LOW);
callbacks.add('afterCreatePrivateGroup', callbackHandler('roomCreated'), callbacks.priority.LOW);
callbacks.add('afterCreateUser', callbackHandler('userCreated'), callbacks.priority.LOW);
callbacks.add('afterJoinRoom', callbackHandler('roomJoined'), callbacks.priority.LOW);
callbacks.add('afterLeaveRoom', callbackHandler('roomLeft'), callbacks.priority.LOW);
callbacks.add('afterRoomArchived', callbackHandler('roomArchived'), callbacks.priority.LOW);
callbacks.add('afterFileUpload', callbackHandler('fileUploaded'), callbacks.priority.LOW);
callbacks.add('afterSaveMessage', callbackHandler('sendMessage'), callbacks.priority.LOW, 'integrations-sendMessage');
callbacks.add('afterCreateChannel', callbackHandler('roomCreated'), callbacks.priority.LOW, 'integrations-roomCreated');
callbacks.add('afterCreatePrivateGroup', callbackHandler('roomCreated'), callbacks.priority.LOW, 'integrations-roomCreated');
callbacks.add('afterCreateUser', callbackHandler('userCreated'), callbacks.priority.LOW, 'integrations-userCreated');
callbacks.add('afterJoinRoom', callbackHandler('roomJoined'), callbacks.priority.LOW, 'integrations-roomJoined');
callbacks.add('afterLeaveRoom', callbackHandler('roomLeft'), callbacks.priority.LOW, 'integrations-roomLeft');
callbacks.add('afterRoomArchived', callbackHandler('roomArchived'), callbacks.priority.LOW, 'integrations-roomArchived');
callbacks.add('afterFileUpload', callbackHandler('fileUploaded'), callbacks.priority.LOW, 'integrations-fileUploaded');
47 changes: 22 additions & 25 deletions app/livechat/server/hooks/externalMessage.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { Meteor } from 'meteor/meteor';
import { HTTP } from 'meteor/http';
import _ from 'underscore';

Expand Down Expand Up @@ -39,32 +38,30 @@ callbacks.add('afterSaveMessage', function(message, room) {
return message;
}

Meteor.defer(() => {
try {
const response = HTTP.post('https://api.api.ai/api/query?v=20150910', {
data: {
query: message.msg,
lang: apiaiLanguage,
sessionId: room._id,
},
headers: {
'Content-Type': 'application/json; charset=utf-8',
Authorization: `Bearer ${ apiaiKey }`,
},
});
try {
const response = HTTP.post('https://api.api.ai/api/query?v=20150910', {
data: {
query: message.msg,
lang: apiaiLanguage,
sessionId: room._id,
},
headers: {
'Content-Type': 'application/json; charset=utf-8',
Authorization: `Bearer ${ apiaiKey }`,
},
});

if (response.data && response.data.status.code === 200 && !_.isEmpty(response.data.result.fulfillment.speech)) {
LivechatExternalMessage.insert({
rid: message.rid,
msg: response.data.result.fulfillment.speech,
orig: message._id,
ts: new Date(),
});
}
} catch (e) {
SystemLogger.error('Error using Api.ai ->', e);
if (response.data && response.data.status.code === 200 && !_.isEmpty(response.data.result.fulfillment.speech)) {
LivechatExternalMessage.insert({
rid: message.rid,
msg: response.data.result.fulfillment.speech,
orig: message._id,
ts: new Date(),
});
}
});
} catch (e) {
SystemLogger.error('Error using Api.ai ->', e);
}

return message;
}, callbacks.priority.LOW, 'externalWebHook');
13 changes: 5 additions & 8 deletions app/livechat/server/hooks/markRoomResponded.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { Meteor } from 'meteor/meteor';

import { callbacks } from '../../../callbacks';
import { Rooms } from '../../../models';
Expand All @@ -19,13 +18,11 @@ callbacks.add('afterSaveMessage', function(message, room) {
return message;
}

Meteor.defer(() => {
Rooms.setResponseByRoomId(room._id, {
user: {
_id: message.u._id,
username: message.u.username,
},
});
Rooms.setResponseByRoomId(room._id, {
user: {
_id: message.u._id,
username: message.u.username,
},
});

return message;
Expand Down
Loading