Workers, threads and cluster
NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), WORKER(), SHELL(), LOAD() and the cluster API.
On this page
Every function, property and start option for background workers, threads, shell commands and the cluster. The guide Workers, threads and cluster shows how they fit together.
API
method
NEWTHREAD(name, [data])
Runs a script from /workers/ as a worker_threads thread.
NEWTHREAD(name, [data])| Parameter | Type | Description |
|---|---|---|
name? |
String |
The file name in /workers/ without .js, @package or ~/absolute/path.js; leave it out inside a worker to get the helper |
data? |
Object |
Data for the thread (workerData) |
Returns Worker The thread, or the worker helper when name is empty
Starts /workers/{name}.js with new Worker() of the Node.js worker_threads module and returns the Worker. data reaches the thread as workerData (the helper's worker.data). The returned object gets kill() and exit(), which call terminate().
A name that starts with @ points to a package file, one that starts with ~ is an absolute path. Without name, the function returns the worker-side helper (see worker.data, worker.message, worker.send()).
var worker = NEWTHREAD('hash', { rounds: 10 });
worker.on('message', function(msg) {
console.log(msg);
worker.kill();
});
worker.postMessage('secret');
method
NEWFORK(name)
Runs a script from /workers/ as a child process.
NEWFORK(name)| Parameter | Type | Description |
|---|---|---|
name? |
String |
The file name in /workers/ without .js, @package or ~/absolute/path.js; leave it out inside a worker to get the helper |
Returns ChildProcess The child process, or the worker helper when name is empty
Starts /workers/{name}.js with child_process.fork() in the app directory and returns the ChildProcess. The object gets postMessage() (alias of send()) and terminate() (sends SIGTERM), so it has the same methods as a thread from NEWTHREAD().
The name rules are the same as in NEWTHREAD(). Without name, the function returns the worker-side helper.
var fork = NEWFORK('import');
fork.on('message', function(msg) {
console.log('Imported', msg.count);
fork.terminate();
});
fork.postMessage({ filename: PATH.databases('import.csv') });
method
NEWTHREADPOOL(name, count, [isfork])
Starts a fixed number of workers and lends them to jobs.
NEWTHREADPOOL(name, count, [isfork])| Parameter | Type | Description |
|---|---|---|
name |
String |
The file name in /workers/ without .js |
count |
Number |
How many workers to start |
isfork? |
Boolean |
Use child processes instead of threads Default: false |
Returns Object The pool with exec(), workers and pending
Starts count workers of /workers/{name}.js with NEWTHREAD(), or with NEWFORK() when isfork is true, and returns a pool. Jobs run with pool.exec(). The pool is also stored in F.workerspool[name].
var pool = NEWTHREADPOOL('resize', 4);
var pool = NEWTHREADPOOL('pdf', 2, true);
method
pool.exec([fn])
Runs a job on the next free worker of a pool.
pool.exec([fn])| Parameter | Type | Description |
|---|---|---|
fn? |
Function |
function(worker, release) |
Returns Promise Only when fn is not given; resolves with the worker
When a worker is free, the pool removes its message listeners and calls fn(worker, release); inside fn, this is the worker too. Call release() when the job is done so the worker can take the next job. Jobs wait in pool.pending while all workers are busy.
Without fn the method returns a promise that resolves with the free worker. Call worker.release() when you are done.
pool.exec(function(worker, release) {
worker.on('message', function(msg) {
release();
console.log(msg);
});
worker.postMessage({ id: 1 });
});
var worker = await pool.exec();
worker.on('message', function(msg) {
worker.release();
console.log(msg);
});
worker.postMessage({ id: 2 });
property
pool.workers
The workers of a pool.
pool.workersReturns Array
An array of the Worker or ChildProcess objects that the pool started. pool.pending is the array of jobs that wait for a free worker.
property
F.workerspool
The pools created by NEWTHREADPOOL(), by name.
F.workerspoolReturns Object
An object where each key is the name given to NEWTHREADPOOL() and each value is the pool. Use it to get a pool in another file.
F.workerspool.resize.exec(function(worker, release) {
// ...
release();
});
property
worker.data
The data that the parent passed to NEWTHREAD().
worker.dataReturns Object
Inside a worker file, NEWTHREAD() or NEWFORK() without arguments returns the worker helper. worker.data is the data argument of NEWTHREAD(name, data). In a child process it is an empty object; send data with a message instead.
require('total4');
var worker = NEWTHREAD();
console.log(worker.data.rounds);
delegate
worker.message = function(msg) {}
Receives the messages that the parent sends to the worker.
worker.message = function(msg) {}| Parameter | Type | Description |
|---|---|---|
msg |
Object |
The message from the parent |
Assign a function to the helper returned by NEWTHREAD() or NEWFORK() without arguments. It is called for each message from the parent, in a thread and in a child process.
require('total4');
var worker = NEWFORK();
worker.message = function(msg) {
worker.send({ id: msg.id, length: msg.text.length });
};
method
worker.send(message)
Sends a message from the worker to the parent.
worker.send(message)| Parameter | Type | Description |
|---|---|---|
message |
Object |
A serialisable value |
Uses parentPort.postMessage() in a thread and process.send() in a child process. worker.postMessage() is the same method. The parent receives the message in on('message') of the object that NEWTHREAD() or NEWFORK() returned.
worker.send({ progress: 50 });
method
worker.exit([code])
Ends the worker.
worker.exit([code])| Parameter | Type | Description |
|---|---|---|
code? |
Number |
The exit code Default: 0 |
Calls process.exit(code). worker.kill() and worker.close() are the same method.
worker.message = function(msg) {
worker.send(msg);
worker.exit();
};
method
worker.setTimeout(timeout)
Ends the worker after a time limit.
worker.setTimeout(timeout)| Parameter | Type | Description |
|---|---|---|
timeout |
Number |
Milliseconds |
Starts a timer that ends the worker with exit code 1 after timeout milliseconds. A new call replaces the previous timer, so you can call it again to extend the limit while the worker is busy.
var worker = NEWTHREAD();
worker.setTimeout(60000);
method
WORKER(name, [timeout], [args])
Forks a script from /workers/ (the older API).
WORKER(name, [timeout], [args])| Parameter | Type | Description |
|---|---|---|
name |
String |
The file name in /workers/, without .js |
timeout? |
Number |
Kills the process after this many milliseconds |
args? |
Array |
Command-line arguments for the script |
Returns ChildProcess
Runs /workers/{name}.js with child_process.fork() in the app directory and returns the ChildProcess. The arguments args and --worker are passed to the script. The process is stored in F.workers until it exits. When timeout (more than 10 ms) passes, the process is killed with SIGKILL.
timeout can be left out: WORKER(name, args). A name that starts with @ points to a package file; a name that starts with # returns a running worker from F.workers by its id. NEWFORK() is the newer alternative.
var worker = WORKER('stats', 10000);
worker.on('message', function(msg) {
console.log(msg);
});
worker.send({ year: 2024 });
require('total4');
process.on('message', function(msg) {
process.send({ year: msg.year, count: 0 });
process.exit(0);
});
method
WORKER2(name, [args], callback, [timeout])
Runs a script from /workers/ and returns its standard output.
WORKER2(name, [args], callback, [timeout])| Parameter | Type | Description |
|---|---|---|
name |
String |
The file name in /workers/, without .js |
args? |
Array |
Command-line arguments; the script reads them from process.argv |
callback |
Function |
function(err, buffer) |
timeout? |
Number |
Kills the process after this many milliseconds |
Returns ChildProcess
Forks /workers/{name}.js silently (like WORKER()), collects everything it writes to the standard output and calls callback(err, buffer) when the process exits or fails. args can be an array or one value. The order of callback and timeout can be swapped.
WORKER2('report', ['2024'], function(err, buffer) {
var report = buffer.toString('utf8').parseJSON();
console.log(report);
}, 30000);
var year = process.argv[2];
console.log(JSON.stringify({ year: year, total: 100 }));
property
F.workers
The running processes started by WORKER().
F.workersReturns Object
An object of the child processes that WORKER() and WORKER2() started, by their id ({name}_{number}). A process is removed when it exits. When the app stops, all of them are killed.
method
PATH.workers([filename])
Returns the path to a file in the /workers/ directory.
PATH.workers([filename])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
A file name |
Returns String
Joins directory_workers (default /workers/) with filename and returns the full path.
var exists = require('fs').existsSync(PATH.workers('resize.js'));
property
isWORKER
true when the framework runs through LOAD() without the HTTP server.
isWORKERReturns Boolean
The global is false by default. LOAD() sets it to true, and HTTP() sets it back to false. Use it in shared code that must not do things that need a web server (for example start schedulers) when it runs in a worker.
if (!isWORKER)
setInterval(cleanup, 60000);
method
LOAD([types], [cwd], [callback])
Loads parts of the app without starting the HTTP server.
LOAD([types], [cwd], [callback])| Parameter | Type | Description |
|---|---|---|
types? |
String|Array |
The parts to load or to skip |
cwd? |
String |
The app directory |
callback? |
Function |
Called when the app is loaded |
Returns Promise Only when callback is not given
Use it in worker files and scripts. It reads the config and .env, loads the parts named in types and calls callback (or resolves the returned promise) when they are ready. It sets isWORKER to true and emits load and ready.
types is an array or a string separated by commas or spaces, for example 'config,modules,schemas'. Names with the no prefix ('nobundles') exclude a part and load the rest. The default is ['nobundles', 'nopackages', 'nocomponents', 'nothemes']. Add 'debug' to run in debug mode and 'service' to run the ON('service') timer. Parts: actions, builds, bundles, components, controllers, definitions, extensions, flowstreams, jsonschemas, middleware, models, modules, operations, packages, plugins, preferences, schemas, sitemap, tasks, themes, versions.
require('total4');
LOAD('config,schemas,modules', function() {
console.log(isWORKER); // true
});
require('total4');
(async function() {
await LOAD('nobundles,nopackages');
console.log(CONF.name);
})();
method
SHELL(command, [callback], [cwd])
Runs a shell command.
SHELL(command, [callback], [cwd])| Parameter | Type | Description |
|---|---|---|
command |
String |
The command line |
callback? |
Function |
function(err, stdout, stderr) |
cwd? |
String |
The working directory Default: the app directory |
Returns Promise Only when callback is not given; resolves with stdout
Runs command with child_process.exec(). The working directory is cwd or the app directory; the shell is default_shell when it is set. The callback receives (err, stdout, stderr). Without a callback the function returns a promise that resolves with the standard output. You can pass cwd as the second argument when you use the promise.
Never put user input into command without escaping it.
SHELL('df -h', function(err, stdout) {
console.log(stdout);
});
var commit = await SHELL('git rev-parse HEAD', '/www/app/');
config
default_shell : <value>
The shell that SHELL() uses.
default_shell : <value>Returns String
The path of the shell for SHELL() (the shell option of child_process.exec()). When it is not set, Node.js uses /bin/sh on Unix and cmd.exe on Windows.
default_shell : /bin/bash
config
options.cluster = 4
Runs the app as a cluster of several instances.
options.cluster = 4Returns Number|String
A start-script option of total4/release and total4/debug. A number starts that many instances of the app; 'auto' starts one and adds or removes instances by their response time (see options.cluster_limit). The master process restarts an instance that exits after one second. In debug mode the master restarts all instances when a file changes.
When options.threads is set, the value applies to each thread instead of the main app.
const options = {};
options.cluster = 4;
require('total4/release')(options);
config
options.cluster_limit = 10
The maximum number of instances in the auto cluster.
options.cluster_limit = 10Returns Number
With options.cluster = 'auto', the master pings the instances every five seconds. It adds an instance when the average response is over 70 ms, until the count reaches cluster_limit. Without it there is no limit. When an instance answers fast, the master removes the last instance (at most every 25 seconds) if it has fewer than two pending requests.
const options = {};
options.cluster = 'auto';
options.cluster_limit = 8;
require('total4/release')(options);
config
options.tz = 'utc'
The time zone of a cluster.
options.tz = 'utc'Returns String
In cluster mode the master sets process.env.TZ for all instances to this value. When you do not set it, the cluster runs in 'utc', whatever the time zone of the server is.
const options = {};
options.cluster = 2;
options.tz = 'Europe/Bratislava';
require('total4/release')(options);
config
options.threads = '/api/'
Runs every subdirectory of /threads/ as a separate app.
options.threads = '/api/'Returns String|Boolean
For each directory in /threads/ the main app writes a start script {script}_{name}.js into the root and forks it. Requests under {threads}/{name}/ are forwarded to that thread over a Unix socket, without the prefix. true means no prefix (/{name}/).
Each thread loads the .js files of its directory with exports.install, its own config and .env files, views/ and public/. It skips the root /controllers/ and /middleware/.
const options = {};
options.threads = '/api/';
require('total4/release')(options);
exports.install = function() {
// Serves GET /api/users/
ROUTE('GET /', function() {
this.json({ thread: THREAD });
});
};
config
options.thread = 'name'
The thread name of the process.
options.thread = 'name'Returns String
Sets the global THREAD and loads the app as the thread /threads/{name}/. The scripts that options.threads writes set it for you. In cluster mode, the restart file is restart_{name}.
config
options.logs = 'isolated'
Writes the output of each thread into its own log file.
options.logs = 'isolated'Returns String
With 'isolated', the output of a thread goes to /threads/{name}/logs/debug.log instead of the console of the main app. The file is cleared when the thread starts (in debug mode only on the first start).
property
THREAD
The name of the current thread.
THREADReturns String
An empty string in a normal app. Inside a thread of /threads/{name}/ it is the name of the thread. The framework adds it to the console banner and to audit logs.
var key = THREAD ? ('cache_' + THREAD) : 'cache';
property
F.threads
The child processes of the threads, by name.
F.threadsReturns Object
In the main app with options.threads, an object where each key is a thread name and each value is its ChildProcess. Otherwise undefined.
property
F.isCluster
true in an instance of a cluster.
F.isClusterReturns Boolean
true when the process is an instance started by the cluster master.
if (!F.isCluster || F.id === '0')
SCHEDULE('03:00', '1 day', cleanup);
property
F.id
The id of the instance in a cluster.
F.idReturns String
The index of the instance as a string ('0', '1', ...), or null outside a cluster. Temporary files of an instance get the prefix cluster_{id}_.
method
F.cluster.emit(name, [a], [b], [c], [d], [e])
Raises an event in every instance of the cluster.
F.cluster.emit(name, [a], [b], [c], [d], [e])| Parameter | Type | Description |
|---|---|---|
name |
String |
The event name |
a? |
Object |
Up to five arguments |
Returns Framework
Sends the event through the master to all instances, the sender included. Each instance calls its ON(name) listeners with up to five arguments. The arguments travel as IPC messages, so they must be serialisable. Outside a cluster it does nothing.
ON('settings_changed', function() {
CACHE('settings', null);
});
F.cluster.emit('settings_changed');
method
F.cluster.master(name, [a], [b], [c], [d], [e])
Sends an event from an instance to the master process.
F.cluster.master(name, [a], [b], [c], [d], [e])| Parameter | Type | Description |
|---|---|---|
name |
String |
The event name |
a? |
Object |
Up to five arguments |
Returns Framework
The master calls the listeners registered with F.cluster.on(name). Outside a cluster it does nothing.
F.cluster.master('visit', F.id);
method
F.cluster.on(name, callback)
Listens in the master process to events from F.cluster.master().
F.cluster.on(name, callback)| Parameter | Type | Description |
|---|---|---|
name |
String |
The event name |
callback |
Function |
function(a, b, c, d, e) |
Returns Framework
Register it in the start script: the master runs that script, and so does every instance. The callback receives the arguments of F.cluster.master(). Register only one listener per name.
const options = {};
options.cluster = 4;
require('total4/release')(options);
var visits = 0;
F.cluster.on('visit', function(id) {
visits++;
});
method
F.cluster.restart([index])
Restarts instances of the cluster from the master process.
F.cluster.restart([index])| Parameter | Type | Description |
|---|---|---|
index? |
Number |
The index of the instance |
Restarts the instance with index, or all instances two seconds apart when index is not given. It works only in the master process. From outside, create the restart file instead.
// index.js
const options = {};
options.cluster = 4;
require('total4/release')(options);
// The start script also runs in every instance, so check the master
if (require('cluster').isMaster)
setInterval(() => F.cluster.restart(), 24 * 60 * 60 * 1000);
method
F.cluster.http(count, mode, [options], [callback])
Starts a cluster with an HTTP server.
F.cluster.http(count, mode, [options], [callback])| Parameter | Type | Description |
|---|---|---|
count |
Number|String |
Number of instances or 'auto' |
mode |
String |
'debug' or 'release' |
options? |
Object |
Start options |
callback? |
Function |
function(forks) |
This is what options.cluster calls in the start script. count is a number, 'auto' or null (one instance per CPU core). mode is 'debug' or 'release'. options are the start options that the instances receive. In the master, callback is called with the array of instances when all of them have started. F.cluster.https() takes the same arguments and starts HTTPS servers.
require('total4').cluster.http(4, 'release', { port: 8000 });
command
restart
A file that restarts all instances of a running cluster.
restartThe master checks every five seconds for a file named restart in the app directory (restart_{thread} when options.thread is set). When it finds it, it deletes the file and restarts all instances two seconds apart, at most once in 30 seconds. Use it after a deploy to load new code without stopping the app.
The master also writes its state (PID, versions, instance count, memory and statistics of every instance) into the start script name plus .json, for example index.js.json, about every 50 seconds.
touch /www/app/restart
config
allow_cache_cluster : false
Synchronizes the framework cache between cluster instances.
allow_cache_cluster : falseReturns Boolean
When true, every CACHE() / F.cache.set(), remove(), removeAll() and clear() in an instance is repeated in the other instances. Sessions are synchronized in a cluster without this option.
allow_cache_cluster : true