Initial commit
[yaffs-website] / node_modules / orchestrator / lib / runTask.js
1 /*jshint node:true */\r
2 \r
3 "use strict";\r
4 \r
5 var eos = require('end-of-stream');\r
6 var consume = require('stream-consume');\r
7 \r
8 module.exports = function (task, done) {\r
9         var that = this, finish, cb, isDone = false, start, r;\r
10 \r
11         finish = function (err, runMethod) {\r
12                 var hrDuration = process.hrtime(start);\r
13 \r
14                 if (isDone && !err) {\r
15                         err = new Error('task completion callback called too many times');\r
16                 }\r
17                 isDone = true;\r
18 \r
19                 var duration = hrDuration[0] + (hrDuration[1] / 1e9); // seconds\r
20 \r
21                 done.call(that, err, {\r
22                         duration: duration, // seconds\r
23                         hrDuration: hrDuration, // [seconds,nanoseconds]\r
24                         runMethod: runMethod\r
25                 });\r
26         };\r
27 \r
28         cb = function (err) {\r
29                 finish(err, 'callback');\r
30         };\r
31 \r
32         try {\r
33                 start = process.hrtime();\r
34                 r = task(cb);\r
35         } catch (err) {\r
36                 return finish(err, 'catch');\r
37         }\r
38 \r
39         if (r && typeof r.then === 'function') {\r
40                 // wait for promise to resolve\r
41                 // FRAGILE: ASSUME: Promises/A+, see http://promises-aplus.github.io/promises-spec/\r
42                 r.then(function () {\r
43                         finish(null, 'promise');\r
44                 }, function(err) {\r
45                         finish(err, 'promise');\r
46                 });\r
47 \r
48         } else if (r && typeof r.pipe === 'function') {\r
49                 // wait for stream to end\r
50 \r
51                 eos(r, { error: true, readable: r.readable, writable: r.writable && !r.readable }, function(err){\r
52                         finish(err, 'stream');\r
53                 });\r
54 \r
55                 // Ensure that the stream completes\r
56         consume(r);\r
57 \r
58         } else if (task.length === 0) {\r
59                 // synchronous, function took in args.length parameters, and the callback was extra\r
60                 finish(null, 'sync');\r
61 \r
62         //} else {\r
63                 // FRAGILE: ASSUME: callback\r
64 \r
65         }\r
66 };\r