Spanish Total.js
English
Documentation For AI agents
Contents

Workers, threads and cluster

NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), WORKER(), SHELL(), LOAD() and the cluster API.

.md GitHub
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.
ParameterTypeDescription
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()).

Start a thread
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.
ParameterTypeDescription
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.

Start a fork
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.
ParameterTypeDescription
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].

A pool of four threads
var pool = NEWTHREADPOOL('resize', 4);
A pool of child processes
var pool = NEWTHREADPOOL('pdf', 2, true);
method

pool.exec([fn])

Runs a job on the next free worker of a pool.
ParameterTypeDescription
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.

With a callback
pool.exec(function(worker, release) {
	worker.on('message', function(msg) {
		release();
		console.log(msg);
	});
	worker.postMessage({ id: 1 });
});
With await
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.

Returns 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.

Returns 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.

Use a pool from another file
F.workerspool.resize.exec(function(worker, release) {
	// ...
	release();
});
property

worker.data

The data that the parent passed to NEWTHREAD().

Returns 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.

In /workers/hash.js
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.
ParameterTypeDescription
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.

Answer each message
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.
ParameterTypeDescription
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.

Report progress
worker.send({ progress: 50 });
method

worker.exit([code])

Ends the worker.
ParameterTypeDescription
code? Number The exit code Default: 0

Calls process.exit(code). worker.kill() and worker.close() are the same method.

Finish after the answer
worker.message = function(msg) {
	worker.send(msg);
	worker.exit();
};
method

worker.setTimeout(timeout)

Ends the worker after a time limit.
ParameterTypeDescription
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.

Limit the worker to one minute
var worker = NEWTHREAD();
worker.setTimeout(60000);
method

WORKER(name, [timeout], [args])

Forks a script from /workers/ (the older API).
ParameterTypeDescription
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.

Run a worker for at most 10 seconds
var worker = WORKER('stats', 10000);
worker.on('message', function(msg) {
	console.log(msg);
});
worker.send({ year: 2024 });
/workers/stats.js
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.
ParameterTypeDescription
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.

Read the output of a script
WORKER2('report', ['2024'], function(err, buffer) {
	var report = buffer.toString('utf8').parseJSON();
	console.log(report);
}, 30000);
/workers/report.js
var year = process.argv[2];
console.log(JSON.stringify({ year: year, total: 100 }));
property

F.workers

The running processes started by WORKER().

Returns 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.
ParameterTypeDescription
filename? String A file name

Returns String

Joins directory_workers (default /workers/) with filename and returns the full path.

Check a worker file
var exists = require('fs').existsSync(PATH.workers('resize.js'));
property

isWORKER

true when the framework runs through LOAD() without the HTTP server.

Returns 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.

Skip a timer in workers
if (!isWORKER)
	setInterval(cleanup, 60000);
method

LOAD([types], [cwd], [callback])

Loads parts of the app without starting the HTTP server.
ParameterTypeDescription
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.

A worker with schemas
require('total4');
LOAD('config,schemas,modules', function() {
	console.log(isWORKER); // true
});
With await
require('total4');
(async function() {
	await LOAD('nobundles,nopackages');
	console.log(CONF.name);
})();
method

SHELL(command, [callback], [cwd])

Runs a shell command.
ParameterTypeDescription
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.

With a callback
SHELL('df -h', function(err, stdout) {
	console.log(stdout);
});
With await and a directory
var commit = await SHELL('git rev-parse HEAD', '/www/app/');
config

default_shell : <value>

The shell that SHELL() uses.

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.

In the config file
default_shell : /bin/bash
config

options.cluster = 4

Runs the app as a cluster of several instances.

Returns 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.

index.js
const options = {};
options.cluster = 4;
require('total4/release')(options);
config

options.cluster_limit = 10

The maximum number of instances in the auto cluster.

Returns 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.

index.js
const options = {};
options.cluster = 'auto';
options.cluster_limit = 8;
require('total4/release')(options);
config

options.tz = 'utc'

The time zone of a cluster.

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.

index.js
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.

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/.

index.js
const options = {};
options.threads = '/api/';
require('total4/release')(options);
/threads/users/index.js
exports.install = function() {
	// Serves GET /api/users/
	ROUTE('GET /', function() {
		this.json({ thread: THREAD });
	});
};
config

options.thread = 'name'

The thread name of the process.

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.

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.

Returns 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.

Use the thread name
var key = THREAD ? ('cache_' + THREAD) : 'cache';
property

F.threads

The child processes of the threads, by name.

Returns 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.

Returns Boolean

true when the process is an instance started by the cluster master.

Run a job in one instance only
if (!F.isCluster || F.id === '0')
	SCHEDULE('03:00', '1 day', cleanup);
property

F.id

The id of the instance in a cluster.

Returns 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.
ParameterTypeDescription
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.

Clear a cache everywhere
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.
ParameterTypeDescription
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.

Report to the master
F.cluster.master('visit', F.id);
method

F.cluster.on(name, callback)

Listens in the master process to events from F.cluster.master().
ParameterTypeDescription
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.

index.js
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.
ParameterTypeDescription
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.

Restart all instances from the start script
// 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.
ParameterTypeDescription
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.

Start a cluster directly
require('total4').cluster.http(4, 'release', { port: 8000 });
command

restart

A file that restarts all instances of a running cluster.

The 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.

Restart after a deploy
touch /www/app/restart
config

allow_cache_cluster : false

Synchronizes the framework cache between cluster instances.

Returns 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.

In the config file
allow_cache_cluster : true
Made in Europe