├── LICENSE ├── README.md ├── aggregator.js ├── client.js ├── cloud-api.js ├── express.js ├── index.js ├── package.json ├── task.js └── test ├── aggregator.js └── tasks.js /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2016 LeanCloud 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LeanEngine APM 2 | 3 | 这个包将会取代 leanengine-sniper 来为 [云引擎](https://leancloud.cn/docs/leanengine_overview.html) 上的 Node.js 应用提供应用级别的性能统计分析。 4 | 5 | 先安装这个包: 6 | 7 | npm install --save leanengine-apm 8 | 9 | 然后访问 [apm.leanapp.cn](https://apm.leanapp.cn),通过 LeanCloud 登录,为你的应用获取一个 Token,然后在你的 `server.js` 中添加(确保添加到加载 `leanengine` 之前): 10 | 11 | ```javascript 12 | var apm = require('leanengine-apm'); 13 | apm.init('c4f7ddfebc2d107fa6b7097506ea4c3742e76044'); // 你的 Token 14 | ``` 15 | 16 | 如果遇到问题请到我们的 [技术支持论坛](https://forum.leancloud.cn/) 反馈,更新历史见 [Releases](https://github.com/leancloud/leanengine-nodejs-apm/releases/) 页面。 17 | 18 | ## 路由统计 19 | 20 | 然后在 `app.js` 中添加下面这行代码即可开启路由统计: 21 | 22 | ```javascript 23 | app.use(require('leanengine-apm').express()); 24 | ``` 25 | 26 | ## 任务统计 27 | 28 | 你还可以使用 `wrapTask` 来统计特定的函数,例如你有一个 `sendMail` 的函数: 29 | 30 | ```javascript 31 | var sendMail = function(template, address) { 32 | // ... 33 | }; 34 | ``` 35 | 36 | 那么你可以用 `wrapTask` 包装一下这个函数: 37 | 38 | ```javascript 39 | var apm = require('leanengine-apm'); 40 | var sendMail = apm.wrapTask('sendMail', function(template, address) { 41 | // ... 42 | }); 43 | ``` 44 | 45 | `wrapTask` 用于包装返回 Promise 的函数,此外还有一个 `wrapCallbackTask` 用于包装回调风格的函数。你还可以使用 46 | `runTask` 来为统计添加更多筛选标签: 47 | 48 | ```javascript 49 | var sendMail = function(template, address) { 50 | return apm.runTask('sendMail', {template: template}, function() { 51 | // ... 52 | }); 53 | }; 54 | ``` 55 | 56 | 建议取值数量有限的字段作为标签才有筛选和分组的意义,请勿使用每次执行值都不同的字段作为标签。 57 | -------------------------------------------------------------------------------- /aggregator.js: -------------------------------------------------------------------------------- 1 | var os = require('os'); 2 | var _ = require('underscore'); 3 | 4 | var client = require('./client'); 5 | 6 | var aggregator = module.exports; 7 | 8 | aggregator.interval = function interval(name, interval, options) { 9 | options = options || {}; 10 | var sumFields = options.sum || []; 11 | var averageFields = options.average || []; 12 | var valueFields = sumFields.concat(averageFields); 13 | var buffer = {}; 14 | 15 | setInterval(function() { 16 | if (!_.isEmpty(buffer)) { 17 | client.sendMetrics({ 18 | metric: name, 19 | instance: process.env.LEANCLOUD_APP_INSTANCE || os.hostname(), 20 | points: _.map(buffer, function(values) { 21 | return _.mapObject(values, function(value, field) { 22 | if (_.contains(averageFields, field)) { 23 | return value / values.count; 24 | } else { 25 | return value; 26 | } 27 | }); 28 | }) 29 | }); 30 | 31 | buffer = {}; 32 | } 33 | }, interval); 34 | 35 | return { 36 | put: function(tags) { 37 | var uniqueName = _.without.apply(null, [_.keys(tags)].concat(valueFields)).sort().map(function(tag) { 38 | return tags[tag]; 39 | }).join(); 40 | 41 | if (buffer[uniqueName]) { 42 | buffer[uniqueName].count += 1; 43 | 44 | valueFields.forEach(function(field) { 45 | buffer[uniqueName][field] += tags[field]; 46 | }); 47 | } else { 48 | buffer[uniqueName] = tags; 49 | buffer[uniqueName].count = 1; 50 | } 51 | }, 52 | 53 | buffer: function() { 54 | return buffer 55 | } 56 | }; 57 | }; 58 | -------------------------------------------------------------------------------- /client.js: -------------------------------------------------------------------------------- 1 | var request = require('request'); 2 | var debug = require('debug')('leanengine:apm'); 3 | 4 | exports.token = null; 5 | 6 | exports.sendMetrics = function(data) { 7 | if (exports.token === null) { 8 | console.error('[APM] was disabled because token is empty'); 9 | exports.token = 'disabled'; 10 | return; 11 | } else if (exports.token === 'disabled') { 12 | return; 13 | } 14 | 15 | debug('sendMetrics:request', data); 16 | 17 | request({ 18 | url: (process.env.APM_URL_PREFIX || 'http://apm.leanapp.cn') + '/metrics', 19 | method: 'POST', 20 | json: data, 21 | headers: { 22 | Authorization: exports.token 23 | } 24 | }, function(err, res, body) { 25 | if (err) { 26 | console.error('[APM] sendMetrics', err); 27 | } else { 28 | debug('sendMetrics:response', res.statusCode, body); 29 | } 30 | }); 31 | }; 32 | -------------------------------------------------------------------------------- /cloud-api.js: -------------------------------------------------------------------------------- 1 | var _ = require('underscore'); 2 | var debug = require('debug')('leanengine:apm'); 3 | 4 | module.exports = function(options) { 5 | var aggregator = require('./aggregator').interval('cloudApi', 60000, _.extend({ 6 | average: ['responseTime'] 7 | }, options)); 8 | 9 | var request; 10 | 11 | try { // cnpm, npm<=2 12 | request = require('leanengine/node_modules/leancloud-storage/dist/node/request'); 13 | } catch (err) { 14 | debug(err); 15 | 16 | try { // npm>=3 17 | request = require('leancloud-storage/dist/node/request'); 18 | } catch (err) { 19 | return console.error('[APM] Hack leancloud-storage failed', err); 20 | } 21 | } 22 | 23 | request.request = _.wrap(request.request, function(original, route, className, objectId, method) { 24 | var startedAt = new Date(); 25 | var promise = original.apply(request, Array.prototype.slice.call(arguments, 1)); 26 | 27 | promise.then(function(body, statusCode) { 28 | aggregator.put({ 29 | count: 1, 30 | responseTime: Date.now() - startedAt.getTime(), 31 | url: generateUrl(route, className, objectId, method), 32 | statusCode: statusCode, 33 | method: method 34 | }); 35 | }, function(err) { 36 | aggregator.put({ 37 | count: 1, 38 | responseTime: Date.now() - startedAt.getTime(), 39 | url: generateUrl(route, className, objectId, method), 40 | statusCode: err.statusCode, 41 | method: method 42 | }); 43 | }); 44 | 45 | return promise; 46 | }); 47 | }; 48 | 49 | function generateUrl(route, className, objectId, method) { 50 | var url = method + ' ' + route; 51 | 52 | if (className) 53 | url += '/' + className; 54 | 55 | if (objectId) 56 | url += '/:id'; 57 | 58 | return url; 59 | } 60 | -------------------------------------------------------------------------------- /express.js: -------------------------------------------------------------------------------- 1 | var onHeaders = require('on-headers'); 2 | var onFinished = require('on-finished'); 3 | var pathToRegexp = require('path-to-regexp'); 4 | var debug = require('debug')('leanengine:apm'); 5 | var request = require('request'); 6 | var _ = require('underscore'); 7 | 8 | module.exports = function(options) { 9 | var aggregator = require('./aggregator').interval('request', 60000, _.extend({ 10 | average: ['responseTime'] 11 | }, options)); 12 | 13 | var rewriteRules = [{ 14 | match: /^GET .*\.(css|js|jpe?g|gif|png|woff2?|ico)$/, 15 | rewrite: 'GET *.$1' 16 | }, { 17 | match: /^(.*)[a-f0-9]{24}(.*)$/, 18 | rewrite: '$1:objectId$2' 19 | }]; 20 | 21 | return function leanengineApm(req, res, next) { 22 | req._lc_startedAt = new Date(); 23 | 24 | onHeaders(res, function() { 25 | res._lc_startedAt = new Date(); 26 | }); 27 | 28 | onFinished(res, function(err) { 29 | if (err) 30 | return console.error(err); 31 | 32 | var requestUrl = req.originalUrl.replace(/\?.*/, ''); 33 | var responseTime = (res._lc_startedAt ? res._lc_startedAt.getTime() : Date.now()) - req._lc_startedAt.getTime(); 34 | 35 | if (req.route) { 36 | // 如果这个请求属于一个路由,则用路由路径替换掉 URL 中匹配的部分 37 | var regexp = pathToRegexp(req.route.path).toString().replace(/^\/\^/, '').replace(/\/i$/, ''); 38 | var matched = requestUrl.match(new RegExp(regexp, 'i')); 39 | 40 | if (matched[0]) { 41 | requestUrl = requestUrl.slice(0, matched.index) + req.route.path; 42 | } 43 | } 44 | 45 | requestUrl = req.method.toUpperCase() + ' ' + requestUrl; 46 | 47 | if (rewriteRules.some(function(rule) { 48 | if (requestUrl.match(rule.match)) { 49 | if (rule.ignore) 50 | return true; 51 | 52 | requestUrl = requestUrl.replace(rule.match, rule.rewrite); 53 | } 54 | })) { 55 | return debug('router: ignored %s', requestUrl); 56 | } 57 | 58 | debug('router: %s %s %sms', requestUrl, res.statusCode, responseTime); 59 | 60 | aggregator.put({ 61 | count: 1, 62 | responseTime: responseTime, 63 | url: requestUrl, 64 | method: req.method, 65 | statusCode: res.statusCode 66 | }); 67 | }); 68 | 69 | next(); 70 | }; 71 | }; 72 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | var cloudApi = require('./cloud-api'); 2 | var express = require('./express'); 3 | var client = require('./client'); 4 | var task = require('./task'); 5 | 6 | module.exports = { 7 | init: function(token) { 8 | client.token = token; 9 | }, 10 | 11 | express: express, 12 | cloudApi: cloudApi, 13 | runTask: task.runTask, 14 | createTracker: task.createTracker, 15 | wrapTask: task.wrapTask, 16 | wrapCallbackTask: task.wrapCallbackTask 17 | }; 18 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "leanengine-apm", 3 | "version": "0.5.0", 4 | "description": "LeanEngine application performance monitoring", 5 | "license": "Apache-2.0", 6 | "repository": { 7 | "type": "git", 8 | "url": "https://github.com/leancloud/leanengine-nodejs-apm" 9 | }, 10 | "dependencies": { 11 | "debug": "2.0.0", 12 | "on-finished": "2.3.0", 13 | "on-headers": "1.0.0", 14 | "path-to-regexp": "1.2.1", 15 | "request": "2.78.0", 16 | "underscore": "1.8.3" 17 | }, 18 | "devDependencies": { 19 | "async": "^1.5.0", 20 | "chai": "^3.4.1", 21 | "mocha": "^3.1.2", 22 | "supertest": "^1.1.0" 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /task.js: -------------------------------------------------------------------------------- 1 | var _ = require('underscore'); 2 | 3 | var aggregator = require('./aggregator').interval('task', 60000, _.extend({ 4 | average: ['duration'] 5 | })); 6 | 7 | var createTracker = function createTracker(name, started) { 8 | started = started || new Date(); 9 | 10 | return { 11 | end: function(tags) { 12 | aggregator.put(_.extend({ 13 | name: name, 14 | count: 1, 15 | duration: Date.now() - started.getTime() 16 | }, tags)) 17 | } 18 | } 19 | }; 20 | 21 | var runTask = function runTask() { 22 | return wrapTask.apply(this, arguments)(); 23 | }; 24 | 25 | var wrapTask = function wrapTask(name, tags, func) { 26 | if (!func) { 27 | func = tags; 28 | tags = {}; 29 | } 30 | 31 | return function wrappedFunction() { 32 | var tracker = createTracker(name); 33 | 34 | return Promise.resolve().then( () => { 35 | return func.apply(this, arguments); 36 | }).then(function(result) { 37 | tracker.end(_.extend({error: 'false'}, tags)); 38 | return result; 39 | }, function(err) { 40 | tracker.end(_.extend({error: 'true'}, tags)); 41 | throw err; 42 | }); 43 | } 44 | }; 45 | 46 | var wrapCallbackTask = function wrapCallbackTask(name, tags, func) { 47 | if (!func) { 48 | func = tags; 49 | tags = {}; 50 | } 51 | 52 | return function wrappedFunction() { 53 | var tracker = createTracker(name); 54 | 55 | var args = Array.prototype.slice.call(arguments); 56 | var callback; 57 | 58 | if (typeof args[args.length - 1] === 'function') { 59 | callback = args.pop(); 60 | 61 | } 62 | 63 | args.push(function(err) { 64 | if (err) { 65 | tracker.end(_.extend({error: 'false'}, tags)); 66 | } else { 67 | tracker.end(_.extend({error: 'true'}, tags)); 68 | } 69 | 70 | callback.apply(this, arguments); 71 | }); 72 | 73 | try { 74 | func.apply(this, args) 75 | } catch (err) { 76 | tracker.end(_.extend({error: 'true'}, tags)); 77 | throw err; 78 | } 79 | }; 80 | }; 81 | 82 | module.exports = { 83 | runTask, 84 | createTracker, 85 | wrapTask, 86 | wrapCallbackTask 87 | }; 88 | -------------------------------------------------------------------------------- /test/aggregator.js: -------------------------------------------------------------------------------- 1 | var chai = require('chai'); 2 | 3 | chai.Should(); 4 | 5 | describe('aggregator', function() { 6 | it('put', function() { 7 | var aggregator = require('../aggregator').interval('request', 60000, { 8 | average: ['responseTime'] 9 | }); 10 | 11 | aggregator.put({ 12 | url: 'GET /', 13 | method: 'GET', 14 | statusCode: 200, 15 | responseTime: 10 16 | }); 17 | 18 | aggregator.put({ 19 | url: 'GET /', 20 | method: 'GET', 21 | statusCode: 200, 22 | responseTime: 20 23 | }); 24 | 25 | aggregator.put({ 26 | url: 'POST /files', 27 | method: 'POST', 28 | statusCode: 401, 29 | responseTime: 20 30 | }); 31 | 32 | var buffer = aggregator.buffer(); 33 | 34 | buffer['GET,200,GET /'].should.be.eql({ 35 | url: 'GET /', 36 | method: 'GET', 37 | statusCode: 200, 38 | responseTime: 30, 39 | count: 2 40 | }); 41 | 42 | buffer['POST,401,POST /files'].should.be.eql({ 43 | url: 'POST /files', 44 | method: 'POST', 45 | statusCode: 401, 46 | responseTime: 20, 47 | count: 1 48 | }); 49 | }); 50 | }); 51 | -------------------------------------------------------------------------------- /test/tasks.js: -------------------------------------------------------------------------------- 1 | var chai = require('chai'); 2 | var apm = require('..'); 3 | 4 | chai.Should(); 5 | 6 | var promiseFuncSuccess = apm.wrapTask('promiseFuncSuccess', function(arg1, arg2) { 7 | arg1.should.be.equal(1); 8 | arg2.should.be.equal(2); 9 | return 3; 10 | }); 11 | 12 | var promiseFuncError = apm.wrapTask('promiseFuncError', function(arg1, arg2) { 13 | arg1.should.be.equal(1); 14 | arg2.should.be.equal(2); 15 | return Promise.reject(new Error('some error')); 16 | }); 17 | 18 | var callbackFuncSuccess = apm.wrapCallbackTask('callbackFuncSuccess', function(arg1, arg2, callback) { 19 | arg1.should.be.equal(1); 20 | arg2.should.be.equal(2); 21 | callback(null, 3); 22 | }); 23 | 24 | var callbackFuncError = apm.wrapCallbackTask('callbackFuncSuccess', function(arg1, arg2, callback) { 25 | arg1.should.be.equal(1); 26 | arg2.should.be.equal(2); 27 | callback(new Error('some error')); 28 | }); 29 | 30 | 31 | describe('aggregator', function() { 32 | it('promiseFuncSuccess', () => { 33 | return promiseFuncSuccess(1, 2).then( result => { 34 | result.should.be.equal(3); 35 | }); 36 | }) 37 | 38 | it('promiseFuncError', () => { 39 | return promiseFuncError(1, 2).then( () => { 40 | console.error('should failed'); 41 | }).catch( err => { 42 | err.message.should.be.equal('some error'); 43 | }); 44 | }) 45 | 46 | it('callbackFuncSuccess', done => { 47 | callbackFuncSuccess(1, 2, (err, result) => { 48 | result.should.be.equal(3); 49 | done(err); 50 | }); 51 | }); 52 | 53 | it('callbackFuncError', done => { 54 | callbackFuncError(1, 2, (err) => { 55 | err.message.should.be.equal('some error'); 56 | done(); 57 | }); 58 | }); 59 | 60 | it('runTask', () => { 61 | return apm.runTask('someTask', {type: 'a'}, () => { 62 | return Promise.resolve(); 63 | }); 64 | }); 65 | }); 66 | --------------------------------------------------------------------------------