@vbarbarosh/node-helpers 3.5.3 → 3.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "author": "Vladimir Barbarosh <vladimir.barbarosh@gmail.com>",
3
3
  "license": "MIT",
4
4
  "name": "@vbarbarosh/node-helpers",
5
- "version": "3.5.3",
5
+ "version": "3.7.0",
6
6
  "description": "A set of helpers for JavaScript/Node.js",
7
7
  "files": [
8
8
  "src"
@@ -28,7 +28,8 @@
28
28
  "form-data": "^4.0.0",
29
29
  "json-stable-stringify": "^1.0.2",
30
30
  "sanitize-filename": "^1.6.3",
31
- "split": "^1.0.1"
31
+ "split": "^1.0.1",
32
+ "ssh2": "^1.15.0"
32
33
  },
33
34
  "devDependencies": {
34
35
  "mocha": "^10.2.0",
@@ -0,0 +1,8 @@
1
+ class NotImplemented extends Error
2
+ {
3
+ constructor(message = 'Not Implemented') {
4
+ super(message);
5
+ }
6
+ }
7
+
8
+ module.exports = NotImplemented;
package/src/fastdl.js ADDED
@@ -0,0 +1,86 @@
1
+ const format_bytes = require('./format_bytes');
2
+ const format_seconds = require('./format_seconds');
3
+ const format_thousands = require('./format_thousands');
4
+ const fs = require('fs');
5
+ const make_progress = require('./progress');
6
+ const parallel = require('./parallel');
7
+ const stream = require('stream');
8
+
9
+ /**
10
+ * Download a file in several connections in parallel.
11
+ *
12
+ * await fastdl({
13
+ * file: fs_path_basename(new URL(url).pathname),
14
+ * read_stream_with_range: (first, last) => http_get_stream_range(url, first, last),
15
+ * });
16
+ */
17
+ async function fastdl({file, read_stream_with_range, concurrency = 60, log = v => console.log(v)})
18
+ {
19
+ const M = 1024*1024;
20
+ const chunk_min_bytes = M;
21
+ const chunk_max_bytes = 50*M;
22
+
23
+ log(`Truncating destination file [${file}]...`);
24
+ await fs.promises.writeFile(file, '');
25
+
26
+ log('Requesting first chunk to determine total size...');
27
+ const rs0 = await read_stream_with_range(0, chunk_min_bytes);
28
+
29
+ const total = rs0.content_range.total;
30
+ const chunk_size = Math.max(chunk_min_bytes, Math.min(chunk_max_bytes, Math.trunc(total/concurrency)));
31
+ const progress = make_progress(total);
32
+
33
+ let connections = 0;
34
+ let next_first = 0;
35
+ let total_written = 0;
36
+
37
+ const timer = setInterval(tick, 1000);
38
+ function tick() {
39
+ const p = progress;
40
+ const bb = format_bytes;
41
+ const ss = format_seconds;
42
+ log(`${bb(p.done)} of ${bb(p.total)} ${(p.percentage*100).toFixed(2)}% at ${bb(p.rate)}/s ETA ${ss(p.eta)} duration=${ss(p.duration)} connections=${connections}`);
43
+ }
44
+
45
+ log(`${format_bytes(total)} [${format_thousands(total)} bytes] to download`);
46
+
47
+ try {
48
+ await parallel({concurrency, spawn});
49
+ }
50
+ finally {
51
+ tick();
52
+ clearInterval(timer);
53
+ }
54
+
55
+ if (total !== total_written) {
56
+ throw new Error(`Total bytes written differs from size of a file: total[${total}] - total_written[${total_written}] = ${total - total_written}`);
57
+ }
58
+
59
+ function spawn() {
60
+ if (next_first >= total) {
61
+ return;
62
+ }
63
+ const first = next_first;
64
+ const last = Math.min(total - 1, first + (first === 0 ? rs0.content_range.last : chunk_size));
65
+ next_first = last + 1;
66
+ connections++;
67
+ return Promise.resolve(run()).finally(() => connections--);
68
+ async function run() {
69
+ const rs = (first === 0) ? rs0 : await read_stream_with_range(first, last);
70
+ const acc = new stream.PassThrough({
71
+ transform(buf, enc, cb) {
72
+ total_written += buf.length;
73
+ progress.add(buf.length);
74
+ cb(null, buf);
75
+ }
76
+ });
77
+ const ws = fs.createWriteStream(file, {
78
+ flags: fs.constants.O_WRONLY, // |fs.constants.O_CREAT,
79
+ start: first,
80
+ });
81
+ await stream.promises.pipeline(rs, acc, ws);
82
+ }
83
+ }
84
+ }
85
+
86
+ module.exports = fastdl;
package/src/logger.js ADDED
@@ -0,0 +1,25 @@
1
+ const NotImplemented = require('./errors/NotImplemented');
2
+
3
+ // grep_cle1grnu10000tu72diepbfet
4
+ const re = /^((?:\[\s*[^\]]*\])*)\s*(.*)$/m;
5
+
6
+ /**
7
+ * log = logger();
8
+ * log.add('hey')
9
+ * log.add('[tag] heyhey')
10
+ */
11
+ function logger(options = {})
12
+ {
13
+ function out(message) {
14
+ const v = typeof message === 'string' ? JSON.stringify(message.trim()).slice(1, -1) : JSON.stringify(message);
15
+ const [, a, m] = v.match(re);
16
+ const time = new Date().toJSON();
17
+ console.log(`${a} ${m}`.trim());
18
+ };
19
+ out.spawn = function () {
20
+ throw new NotImplemented();
21
+ };
22
+ return out;
23
+ }
24
+
25
+ module.exports = logger;
@@ -0,0 +1,51 @@
1
+ const NotImplemented = require('./errors/NotImplemented');
2
+
3
+ /**
4
+ * - Run until `spawn` return `null`.
5
+ * - Keep no more than `concurrency` number of workers at a time.
6
+ */
7
+ async function parallel({concurrency, spawn, progress})
8
+ {
9
+ const running = [];
10
+ return new Promise(function (resolve, reject) {
11
+ const timer = setInterval(tick, 1000);
12
+ schedule();
13
+ if (running.length) {
14
+ tick();
15
+ }
16
+ function schedule() {
17
+ while (running.length < concurrency) {
18
+ const w = spawn();
19
+ if (!w) {
20
+ break;
21
+ }
22
+ const item = Promise.resolve(w).then(resolved, rejected);
23
+ running.push(item);
24
+ function resolved() {
25
+ const i = running.indexOf(item);
26
+ if (i === -1) {
27
+ throw new NotImplemented();
28
+ }
29
+ running.splice(i, 1);
30
+ schedule();
31
+ }
32
+ function rejected(error) {
33
+ console.log(error);
34
+ throw new NotImplemented();
35
+ }
36
+ }
37
+ if (running.length === 0) {
38
+ tick();
39
+ clearInterval(timer);
40
+ resolve();
41
+ }
42
+ }
43
+ function tick() {
44
+ if (progress) {
45
+ progress(running);
46
+ }
47
+ }
48
+ });
49
+ }
50
+
51
+ module.exports = parallel;
package/src/progress.js CHANGED
@@ -8,27 +8,41 @@
8
8
  // https://bramcohen.livejournal.com/24122.html
9
9
  function progress(total)
10
10
  {
11
- let done = 0;
11
+ const history = [];
12
12
  const time0 = Date.now();
13
13
  const out = {
14
14
  done: 0,
15
15
  total,
16
16
  eta: null,
17
+ // `rate` instead of `bps` (bytes per speed) because this function could count any values (e.g.
18
+ // copied bytes over time, or handled jobs over time, or created object over time, etc.)
17
19
  rate: null,
18
20
  duration: 0,
19
21
  progress: null,
20
22
  percentage: null,
21
23
  add: function (delta = 0) {
24
+ const now_minus_5_seconds = Date.now() - 5000;
25
+ history.push({time: Date.now(), delta});
26
+ // Keep last 5 seconds
27
+ history.splice(0, history.findLastIndex(v => v.time < now_minus_5_seconds));
22
28
  out.done += delta;
23
29
  out.refresh();
24
30
  },
25
31
  update: function (done) {
26
- out.done = done;
27
- out.refresh();
32
+ out.add(done - out.done);
28
33
  },
29
34
  refresh: function () {
35
+ const now_minus_5_seconds = Date.now() - 5000;
36
+ const tmp = history.filter(v => v.time >= now_minus_5_seconds);
37
+ if (tmp.length > 1) {
38
+ const items = tmp.reduce((a,v) => a + v.delta, 0);
39
+ const time_sec = (tmp.pop().time - tmp[0].time)/1000;
40
+ out.rate = items/time_sec;
41
+ }
42
+ else {
43
+ out.rate = out.done/out.duration;
44
+ }
30
45
  out.duration = (Date.now() - time0)/1000;
31
- out.rate = out.done/out.duration;
32
46
  out.percentage = !out.total ? null : out.done/out.total;
33
47
  out.eta = !out.total ? null : (out.total - out.done)/out.rate;
34
48
  },
@@ -0,0 +1,44 @@
1
+ const Promise = require('bluebird');
2
+ const ignore = require('./ignore');
3
+ const ssh2 = require('ssh2');
4
+ const waitcb = require('./waitcb');
5
+
6
+ async function sftp_get_file_info(url, {log = ignore})
7
+ {
8
+ const u = new URL(url);
9
+ const host = u.host;
10
+ const port = +u.port || 22;
11
+ const username = decodeURIComponent(u.username);
12
+ const password = decodeURIComponent(u.password);
13
+ const pathname = u.pathname;
14
+
15
+ log('Establishing connection...');
16
+ const conn = new ssh2.Client();
17
+ try {
18
+ await new Promise(function (resolve, reject) {
19
+ conn.once('ready', resolve);
20
+ conn.once('error', reject);
21
+ conn.connect({host, port, username, password});
22
+ });
23
+
24
+ log('Asking for an sftp service...');
25
+ const sftp = await waitcb(cb => conn.sftp(cb));
26
+
27
+ log('Requesting file info...');
28
+ const [stat, lstat, readdir] = await Promise.all([
29
+ waitcb(cb => sftp.stat(pathname, cb)),
30
+ waitcb(cb => sftp.lstat(pathname, cb)),
31
+ waitcb(cb => sftp.readdir(pathname, cb)),
32
+ ]);
33
+ return {
34
+ stat,
35
+ lstat,
36
+ readdir,
37
+ };
38
+ }
39
+ finally {
40
+ conn.end();
41
+ }
42
+ }
43
+
44
+ module.exports = sftp_get_file_info;
@@ -0,0 +1,47 @@
1
+ const ignore = require('./ignore');
2
+ const ssh2 = require('ssh2');
3
+ const waitcb = require('./waitcb');
4
+
5
+ const ___stat = Symbol('sftp_get_stream_range.stat');
6
+
7
+ async function sftp_get_stream_range(url, first, last, {log = ignore} = {})
8
+ {
9
+ const u = new URL(url);
10
+ const host = u.host;
11
+ const port = +u.port || 22;
12
+ const username = decodeURIComponent(u.username);
13
+ const password = decodeURIComponent(u.password);
14
+ const pathname = u.pathname;
15
+
16
+ log('Establishing connection...');
17
+ const conn = new ssh2.Client();
18
+ await new Promise(function (resolve, reject) {
19
+ conn.on('ready', resolve);
20
+ conn.on('error', reject);
21
+ conn.connect({host, port, username, password});
22
+ });
23
+
24
+ log('Asking for an sftp service...');
25
+ const sftp = await waitcb(cb => conn.sftp(cb));
26
+
27
+ log('Requesting file info...');
28
+ const stat = url[___stat] || (url[___stat] = await waitcb(cb => sftp.stat(pathname, cb)));
29
+
30
+ if (first < 0 || last >= stat.size) {
31
+ throw new Error(`Invalid range: [first=${first}][last=${last}]`);
32
+ }
33
+
34
+ const out = sftp.createReadStream(pathname, {start: first, end: last})
35
+ out.content_range = {
36
+ type: 'bytes',
37
+ first,
38
+ last,
39
+ total: stat.size,
40
+ };
41
+ out.once('end', function () {
42
+ conn.end();
43
+ });
44
+ return out;
45
+ }
46
+
47
+ module.exports = sftp_get_stream_range;
package/src/waitcb.js ADDED
@@ -0,0 +1,18 @@
1
+ const Promise = require('bluebird');
2
+
3
+ /**
4
+ * Wait for a Node-like function to finish (which will call `callback`
5
+ * with 2 arguments: `error` and `value`).
6
+ *
7
+ * await waitcb(cb => fs.promises.writeFile('a', 'hello\n', cb));
8
+ */
9
+ function waitcb(fn)
10
+ {
11
+ return new Promise(function (resolve, reject) {
12
+ fn(function (error, out) {
13
+ error ? reject(error) : resolve(out);
14
+ });
15
+ });
16
+ }
17
+
18
+ module.exports = waitcb;