Spanish Total.js
English
Documentation For AI agents
Contents

FlowStream

Visual data flows: loading FlowStreams, components, instances, messages and the Total.js Flow editor.

.md GitHub
On this page

FlowStream is the engine of visual data flows in Total.js. A flow is a set of components (small programs with inputs and outputs), their instances placed on a canvas, and the connections between them. Messages travel from the outputs of one instance to the inputs of others. The flows are designed in the Total.js Flow editor, which connects to your application through a WebSocket.

The engine is available as the global Flow (and its alias FlowStream). Every loaded flow is kept in Flow.instances[id].

Loading a FlowStream

Flow.load(schema, [callback]) starts a FlowStream from its schema. The schema is a plain object: the source code of the components, the design (instances and connections) and the variables.

Flow.load({ id: 'orders', name: 'Orders', components: {}, design: {}, variables: { token: '123' } }, function(err, flowstream) {
    // flowstream === Flow.instances.orders
});
KeyWhat it does
idIdentifier of the FlowStream (a random id when empty)
nameName shown in the editor (id when empty)
componentsObject: component id → source code of the component
designObject: instance id → { component, config, connections, x, y }
variablesValues available as {name} in the components
worker'worker' runs the flow in a worker thread, any other truthy value in a child process
memoryWith worker: the heap limit of the worker in MB (--max-old-space-size for a child process, resourceLimits for a worker thread)
proxypathURL path under which the HTTP server of a worker is reachable through the main app
cloningfalse disables cloning of message data between connections
pausedtrue loads the flow paused
readonlytrue disables saving
importComma-separated paths (from the app root) of modules whose install(flow) / init(flow) run on load
initscriptJavaScript code executed with the FlowStream as instance
envA value available as instance.env in the components

When the application starts, every *.flow file in the /flowstreams/ directory is loaded with Flow.load() (files with -bk or _bk in the name are skipped). A .flow file contains the schema as JSON.

Loading a schema with an id that is already running reloads the running FlowStream with the new schema.

Each time a FlowStream starts (also after the automatic restart of a worker), the framework emits the global event flowstream:

ON('flowstream', function(flowstream) {
    console.log('FlowStream started:', flowstream.id);
});

A plugin can contain its own flow: the file /plugins/{name}/index.flow is loaded with the plugin. Its id is the plugin id and the running FlowStream is stored in PLUGINS[id].flowstream. See Plugins and components.

Editing with Total.js Flow

The editor talks to the FlowStream over a WebSocket. Create a route and pass the connection to Flow.socket():

exports.install = function() {
    ROUTE('+SOCKET /flowstreams/{id}/ <8MB', socket);
};

function socket($) {
    $.autodestroy();
    Flow.socket($.params.id, $);
}

Open https://flow.totaljs.com/?socket= followed by the URL-encoded address of this WebSocket. The editor loads the components and the design, shows the status of the instances and saves every change back to the FlowStream.

The FlowStream does not write files. About 5 seconds after a change it emits save with the whole schema, and you store it yourself:

Flow.on('save', function(schema) {
    F.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\t'), NOOP);
});

For remote editing, flowstream.edit([url]) opens a WebSocket client to a proxy (by default wss://flow.totaljs.com/{id}/), so the editor can reach a FlowStream that runs behind a firewall.

Components

A component is text with HTML-like parts. The server code is in <script total> (or <script node>); <settings>, <body>, <style>, <readme> and a plain <script> are used by the editor.

<script total>

    exports.name = 'Uppercase';
    exports.icon = 'ti ti-text';
    exports.group = 'Common';
    exports.config = { field: 'name' };
    exports.inputs = [{ id: 'input', name: 'Input' }];
    exports.outputs = [{ id: 'output', name: 'Output' }];

    exports.make = function(instance, config) {

        instance.message = function($) {
            var data = $.data;
            data[config.field] = (data[config.field] || '').toUpperCase();
            $.send('output');
        };

        instance.configure = function() {
            config = instance.config;
        };

    };

</script>

<readme>
Converts a field to upper case.
</readme>

exports.make(instance, config) runs once for each instance of the component on the canvas. Inside it you assign delegates to the instance: message (an incoming message), configure (new configuration), close (the instance is removed), variables (the variables have changed), trigger (the trigger button in the editor), service (called every minute) and others.

exports.npm = ['package'] installs the NPM packages before the component is registered. exports.install and exports.uninstall run when the component is registered and removed.

Messages

The message delegate receives a message, usually called $. $.data is the payload, $.repo is an object shared by all clones of the message, $.input and $.output are the ids of the input and the output. $.send(output, [data]) sends a clone to every instance connected to the output; the clones of the data are deep copies unless the flow has cloning: false. $.send(null) sends to all outputs; the message ends once, after the clones of all outputs end. A message that is not sent further must be ended with $.end().

instance.message = function($) {
    if ($.data.price > 100)
        $.send('expensive');
    else
        $.send('cheap', { price: $.data.price });
};

The fourth argument of $.send() filters the targets: $.send('output', null, null, function(from, to, output, input) { return to.component !== 'debug'; }).

Without an incoming message, an instance starts a new one with instance.send(output, data) (for example from a timer or from trigger). instance.send(null, data) sends to all outputs. The status of an instance (shown under it in the editor) is set with instance.status(data), errors are reported with instance.throw(err). The flow keeps the last 10 errors in instance.main.errors; the reset command of the editor clears them and the flow engine emits reset, so an instance can clear its own state too:

exports.make = function(instance) {

    instance.cache.count = 0;

    var onreset = function() {
        instance.cache.count = 0;
        instance.status({ count: 0 });
    };

    instance.main.on('reset', onreset);

    instance.close = function() {
        instance.main.off('reset', onreset);
    };

};

The next example starts messages from a timer and shows the time of the last one as the status:

exports.make = function(instance, config) {

    var timer = setInterval(function() {
        instance.send('output', { ts: NOW });
        instance.status({ last: NOW });
    }, 5000);

    instance.close = function() {
        clearInterval(timer);
    };

};

Instance data

instance.config is the configuration from the editor merged into exports.config. instance.cache is a plain object for your own runtime data; it is kept in memory for the instance id when the instance is initialized again (for example after its component is updated). Call instance.save() after you change config from the code: the flow is saved and the editor is redrawn (instance.save(false) saves without redrawing).

instance.repo is an object stored in the design together with the instance. It survives a reload and a restart, and the editor does not change it.

Activities

A long task can report its progress to the editor. instance.activity(key, name, [progress]) creates or updates an activity of the instance; progress is a number (percent). Progress 100 or an empty name removes the activity.

instance.message = function($) {
    instance.activity('import', 'Importing products', 0);
    importproducts($.data, function(percentage) {
        instance.activity('import', 'Importing products', percentage);
    }, function() {
        instance.activity('import', 'Importing products', 100);
        $.send('output');
    });
};

Variables

The variables of the flow are replaced in strings with instance.replace(text) (or $.variables(text) in a message). A {name} placeholder takes the value from the variables of the flow, the secrets, {hostname} or the given data object.

var url = instance.replace('https://api.example.com/orders/?token={token}');

flowstream.variables(obj) replaces the variables of a running flow; the instances are notified by their variables delegate.

Controlling a FlowStream from code

Flow.instances[id] is the running FlowStream. It works the same for flows in the main process and in workers.

var flowstream = Flow.instances.orders;

// Executes the "trigger" delegate of an instance
flowstream.trigger('instanceid', { manual: true });

// Sends data to an instance and waits for the end of the message
flowstream.send('instanceid', { id: 1 }, function(err, response) {
    console.log(response.data, response.duration);
});

flowstream.pause(true);
flowstream.reconfigure('instanceid', { field: 'title' });
flowstream.export(function(err, schema) {});

Instance ids can be replaced by @component (instances of a component id) or #name (instances of a component name).

Flow.remove(id) stops a FlowStream and removes it.

Workers

With worker: 'worker' (a worker thread) or worker: 'process' (a child process) the flow runs outside the main process, so a broken component cannot block the application. A worker that exits is started again automatically after a second. memory: 512 limits the heap of the worker to 512 MB. flowstream.restart() or Flow.restart(id) ends a worker so that it starts again with the current schema. For a flow in the main process, instance.main.restart() (and the restart command of the editor) asks the Total.js process manager to restart the whole application.

With proxypath, the worker runs its own HTTP server on a Unix socket and the main application forwards requests under that path to it. proxytimeout sets the timeout of that proxy; it is applied when the schema is loaded again into the running FlowStream.

flowstream.stats contains the counters: messages, pending, memory, minutes, errors, mm (messages in the last minute) and paused. For a flow in the main process, online is the number of editors connected to it. For flows in workers, Flow.on('stats', function(id, stats) {}) receives the counters every 15 seconds.

Notifications

Flow.notify($, id) passes an HTTP request to the notify delegate of an instance. The id is flowid-instanceid. Register the routes yourself:

exports.install = function() {
    ROUTE('GET /notify/{id}/', notify);
    ROUTE('POST /notify/{id}/ <1MB', notify);
};

function notify($) {
    Flow.notify($, $.params.id);
}

TMS sources

In the editor you can add a TMS source (a URL and a token of another Total.js app). The FlowStream connects to it and creates Publish, Subscribe and Call components from the source's schemas, so messages can cross applications. The sources are saved in the sources key of the schema. See Message Service (TMS).

Testing a component

Flow.test(name, source, [config], init) loads a single component in a test flow and gives you a Test object:

Flow.test('uppercase', source, { field: 'name' }, function(test) {
    test.message = function($, data) {
        test.assert(data.name === 'PETER', 'uppercase');
    };
    test.send('input', { name: 'Peter' });
});

The flow5 command

The total5 package installs the flow5 command. It loads one or more schemas from files or HTTPS URLs and starts an HTTP server with the WebSocket route for the editor:

flow5 orders.json 8001

Changes made in the editor are written back to the JSON files. See Command line.

Made in Europe