multi-tasks 3.2.1 → 3.2.2

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.
Files changed (3) hide show
  1. package/README.md +36 -12
  2. package/package.json +1 -1
  3. package/workers/index.js +65 -19
package/README.md CHANGED
@@ -1,8 +1,6 @@
1
1
  # multi-tasks
2
2
 
3
- Multi-tasks is a toolkit to manage long-term and large-scale parallel computing tasks. Progress and tasks are stored on the file system, so tasks can be resumed even if the host crashes.
4
-
5
- **Zero dependencies:** multi-tasks has no runtime dependencies at all — it is built entirely on Node.js built-in modules (`cluster`, `fs`, `path`, `os`), so installing it adds nothing extra to your `node_modules`.
3
+ Multi-tasks is a toolkit to manage long-term and large-scale parallel computing tasks, with zero dependencies. Progress and tasks are stored on the file system, so tasks can be resumed even if the host crashes.
6
4
 
7
5
  ### Install:
8
6
 
@@ -18,13 +16,17 @@ Tip: monitor running tasks in real time — see [Real-Time Monitoring](#real-tim
18
16
  //see examples/example0
19
17
  let multiTasks = require('multi-tasks').multiTasks;
20
18
 
21
- //Step1, create the tasks to run in parallel as an array.
22
- let alltasks = [];
23
- for(let i=0;i<50;i++){
24
- alltasks.push({
25
- name: `task-${i}`,
26
- data: `This prop is for a subtask`
27
- });
19
+ //Step1, provide the tasks as a function returning them (or a Promise of them);
20
+ //it runs only once, in the master process.
21
+ let initialTasks = async ()=>{
22
+ let alltasks = [];
23
+ for(let i=0;i<50;i++){
24
+ alltasks.push({
25
+ name: `task-${i}`,
26
+ data: `This prop is for a subtask`
27
+ });
28
+ };
29
+ return alltasks;
28
30
  };
29
31
 
30
32
  //Step2, provide a function that processes each sub-task and returns the result
@@ -39,7 +41,7 @@ let processTask = (task, helper)=>{
39
41
 
40
42
  //Step3, run!
41
43
  multiTasks({
42
- initialTasks: alltasks,
44
+ initialTasks, //accepts array, function, or function returning a promise
43
45
  processTask,
44
46
  taskRootFolder: `../examples-tmp-data/example0`, //a directory to store progress and result files; you can check the progress here
45
47
  taskId: 'my-task',
@@ -175,6 +177,27 @@ multiTasks({
175
177
 
176
178
  ```
177
179
 
180
+ ### Performance: runs only once, in the master process
181
+
182
+ Every worker process re-runs your entire entry script — so top-level task-generation code (building a huge array, scanning folders, querying a database, ...) runs once per worker. Wrap it in a function for performance: it is called **only once, in the master process**, and workers never call it. `initialTasks` accepts three forms — pick one:
183
+
184
+ ```javascript
185
+
186
+ //Example8, the three forms of initialTasks
187
+
188
+ //form 1: a plain array — assign it directly
189
+ multiTasks({ initialTasks: alltasks, processTask, taskRootFolder, taskId });
190
+
191
+ //form 2: a function returning the array
192
+ multiTasks({ initialTasks: () => fetchTasksFromSomewhere(), processTask, taskRootFolder, taskId });
193
+
194
+ //form 3: a function returning a Promise of the array
195
+ multiTasks({ initialTasks: async () => await fetchTasksFromDb(), processTask, taskRootFolder, taskId });
196
+
197
+ ```
198
+
199
+ The (resolved) value must be an array, otherwise the master exits with an error. The resulting array — not the function — is stored in `task_config.json`, so the self-contained-function note under Resuming does not apply to it.
200
+
178
201
  ### Resuming
179
202
 
180
203
  If the execution is interrupted (e.g. a power outage), the simplest way to resume is to just re-run the same code — `multiTasks(config)` detects the existing task folder and auto-resumes, re-running only the stuck tasks:
@@ -261,7 +284,7 @@ The API has three parts: the entry functions, the config options, and the `helpe
261
284
 
262
285
  **Config options:**
263
286
 
264
- - **`initialTasks`** — array of task objects, or a folder path string to resume from.
287
+ - **`initialTasks`** — array of task objects, a function returning the array (or a Promise of it — called only once, in the master process; worker processes never call it; see [Performance: runs only once, in the master process](#performance-runs-only-once-in-the-master-process)), or a folder path string to resume from.
265
288
  - **`processTask(task, helper)`** — required; return a value or a Promise.
266
289
  - **`taskRootFolder`** — the task run folder (named by `taskId`) is created under this directory.
267
290
  - **`taskId`** — task folder name under `taskRootFolder`.
@@ -290,6 +313,7 @@ The API has three parts: the entry functions, the config options, and the `helpe
290
313
 
291
314
  ### Changelog:
292
315
 
316
+ - 3.2.2 initialTasks accepts a function (sync or async) that is called only once, in the master process
293
317
  - 3.2.1 Fix retry bug: user-defined taskCount/index no longer overwritten on task retries
294
318
  - 3.2.0 Add progressBar (on by default); console output diverted to run.log; new startup banner
295
319
  - 3.1.9 Print the multi-tasks-monitor command on startup
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "multi-tasks",
3
- "version": "3.2.1",
3
+ "version": "3.2.2",
4
4
  "description": "Multi-process task scheduling based on Node.js cluster, with crash resume and failed-task restart support",
5
5
  "main": "index.js",
6
6
  "files": [
package/workers/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  const fs = require('fs');
2
2
  const pathUtil = require('path');
3
+ const cluster = require('cluster');
3
4
  const Multithread = require('./Multithread');
4
5
  const backwardv1 = require('../utils/backward-v1');
5
6
  const { FUNCTION_CONFIG_KEYS, reviveConfig } = require('../utils/serializeFns');
@@ -52,19 +53,58 @@ const _computeSysLogFile = (config)=>{
52
53
  };
53
54
  };
54
55
 
56
+ //initialTasks 支持函数形式(惰性生成): 只在 master 进程求值一次, worker 进程重跑入口脚本时跳过,
57
+ //防生成逻辑(扫目录/查库等初始化脚本)在每个 worker 里各执行一遍。
58
+ //函数可同步返回数组, 也可返回 Promise(resolve 值同样必须是数组)——同步路径保持同步 throw,
59
+ //Promise 路径返回 then 链交给 _proceedAfterEval 等待。求值在入口统一完成(先于 _mergeSnapshotConfig
60
+ //与 Multithread.start): 求值后的数组才会参与合并并写入 task_config.json(函数本身会被
61
+ //JSON.stringify 丢弃, 不进存档、不参与 revive)。
62
+ const _evalInitialTasks = (config)=>{
63
+ if(typeof config.initialTasks !== 'function') return null;
64
+ if(!(cluster.isPrimary || cluster.isMaster)) return null;
65
+ let tasks = config.initialTasks();
66
+ let applyTasks = (resolved)=>{
67
+ if(!Array.isArray(resolved)){
68
+ throw new Error('FATAL: initialTasks function should return an array!');
69
+ };
70
+ config.initialTasks = resolved;
71
+ };
72
+ if(tasks && typeof tasks.then === 'function'){//Promise 形式: 异步求值, resolve 后同样校验数组(假设真 Promise, 即 .then 返回 Promise; 非标准 thenable 不支持)
73
+ return tasks.then(applyTasks);
74
+ };
75
+ applyTasks(tasks);
76
+ return null;
77
+ };
78
+
79
+ //同步路径(pending 为 null)直接执行 proceed, 保持既有同步 throw 语义;
80
+ //Promise 路径等 resolve 后执行, resolve 非数组/reject/proceed 抛错时打 FATAL 并 exit(1)
81
+ //(与 init 异步失败一致; Promise 路径只发生在 master, 无同步 throw 对象)。
82
+ const _proceedAfterEval = (pending, proceed)=>{
83
+ if(!pending){
84
+ proceed();
85
+ return;
86
+ };
87
+ return pending.then(proceed).catch((e)=>{
88
+ console.error('[FATAL] failed to evaluate initialTasks:', e);
89
+ process.exit(1);
90
+ });
91
+ };
92
+
55
93
  const start = (config)=>{
56
94
  config = backwardv1.v1tov2(config);
95
+ return _proceedAfterEval(_evalInitialTasks(config), ()=>{
57
96
 
58
- config.taskRootFolder = _toAbsPath(config.taskRootFolder);
59
- config.taskFolder = _toAbsPath(config.taskFolder);
60
- _computeSysLogFile(config);
97
+ config.taskRootFolder = _toAbsPath(config.taskRootFolder);
98
+ config.taskFolder = _toAbsPath(config.taskFolder);
99
+ _computeSysLogFile(config);
61
100
 
62
- Multithread.start(config);
101
+ Multithread.start(config);
102
+ });
63
103
  };
64
104
  const resume = (config)=>{
65
105
  config = _normalizeResumeArg('resume', config);
66
- config.__resume = true;
67
-
106
+ //先校验/推导 taskFolder 再求值 initialTasks(与 retry_fails/restart 一致):
107
+ //缺目录时同步 throw fail fast, 不让可能昂贵的生成逻辑白跑一遍
68
108
  config.taskRootFolder = _toAbsPath(config.taskRootFolder);
69
109
  config.taskFolder = _toAbsPath(config.taskFolder);
70
110
  if(!config.taskFolder){
@@ -75,10 +115,12 @@ const resume = (config)=>{
75
115
  };
76
116
  config.taskRootFolder = pathUtil.dirname(config.taskFolder);
77
117
  config.taskId = pathUtil.basename(config.taskFolder);
78
- _computeSysLogFile(config);
79
-
80
- config = _mergeSnapshotConfig(config);
81
- Multithread.start(config);
118
+ config.__resume = true;
119
+ return _proceedAfterEval(_evalInitialTasks(config), ()=>{
120
+ _computeSysLogFile(config);
121
+ config = _mergeSnapshotConfig(config);
122
+ Multithread.start(config);
123
+ });
82
124
  };
83
125
  const retry_fails = (config)=>{
84
126
  config = _normalizeResumeArg('retry_fails', config);
@@ -91,9 +133,11 @@ const retry_fails = (config)=>{
91
133
  config.taskId = pathUtil.basename(taskFolder);
92
134
  config.__resume = true;
93
135
  config.__retryFails = true;
94
- _computeSysLogFile(config);
95
- config = _mergeSnapshotConfig(config);
96
- Multithread.start(config);
136
+ return _proceedAfterEval(_evalInitialTasks(config), ()=>{
137
+ _computeSysLogFile(config);
138
+ config = _mergeSnapshotConfig(config);
139
+ Multithread.start(config);
140
+ });
97
141
  };
98
142
  const restart = (config)=>{
99
143
  config = _normalizeResumeArg('restart', config);
@@ -105,9 +149,11 @@ const restart = (config)=>{
105
149
  config.taskRootFolder = pathUtil.dirname(taskFolder);
106
150
  config.taskId = pathUtil.basename(taskFolder);
107
151
  config.__restart = true;
108
- _computeSysLogFile(config);
109
- config = _mergeSnapshotConfig(config);
110
- Multithread.start(config);
152
+ return _proceedAfterEval(_evalInitialTasks(config), ()=>{
153
+ _computeSysLogFile(config);
154
+ config = _mergeSnapshotConfig(config);
155
+ Multithread.start(config);
156
+ });
111
157
  };
112
158
 
113
159
  const multiTasks = (config)=>{
@@ -126,7 +172,7 @@ const multiTasks = (config)=>{
126
172
  config.taskRootFolder = pathUtil.dirname(folder);
127
173
  }
128
174
  }
129
- if(!isResume) throw new Error('FATAL: initialTasks should be an array or a task root folder!');
175
+ if(!isResume) throw new Error('FATAL: initialTasks should be an array, a function or a task root folder!');
130
176
  }else{
131
177
  let taskFolder = pathUtil.resolve(taskRootFolder, taskId);
132
178
  if(fs.existsSync(taskFolder)){
@@ -135,9 +181,9 @@ const multiTasks = (config)=>{
135
181
  }
136
182
 
137
183
  if(isResume){
138
- resume(config);
184
+ return resume(config);
139
185
  }else{
140
- start(config);
186
+ return start(config);
141
187
  }
142
188
 
143
189
  };