LaraflareDocsFrameworkPackagesReleases13.x

Docs / Digging Deeper / Processes

Processes

Introduction

laraflare provides an expressive, minimal API around Node's child_process module, allowing you to conveniently invoke external processes from your laraflare application. laraflare's process features are focused on the most common use cases and a wonderful developer experience.

Note

A Cloudflare Worker cannot start a process. The Process facade is for code that runs on Node: your artisan commands, scripts and tests. It is exported from @laraflare/framework/console, not from the main entry, so a Worker bundle never carries it.

Invoking Processes

To invoke a process, you may use the run and start methods offered by the Process facade. The run method will invoke a process and wait for the process to finish executing, while the start method is used for asynchronous process execution. We'll examine both approaches within this documentation. First, let's examine how to invoke a basic, synchronous process and inspect its result. Since a process cannot be waited on without blocking, run returns a promise of the result:

import { Process } from '@laraflare/framework/console';

const result = await Process.run('ls -la');

return result.output();

Of course, the ProcessResultContract instance returned by the run method offers a variety of helpful methods that may be used to inspect the process result:

const result = await Process.run('ls -la');

result.command();
result.successful();
result.failed();
result.output();
result.errorOutput();
result.exitCode();

Throwing Exceptions

If you have a process result and would like to throw an instance of ProcessFailedException if the exit code is greater than zero (thus indicating failure), you may use the throw and throwIf methods. If the process did not fail, the ProcessResult instance will be returned:

const result = (await Process.run('ls -la')).throw();

const result = (await Process.run('ls -la')).throwIf(condition);

Process Options

Of course, you may need to customize the behavior of a process before invoking it. Thankfully, laraflare allows you to tweak a variety of process features, such as the working directory, timeout, and environment variables.

Working Directory Path

You may use the path method to specify the working directory of the process. If this method is not invoked, the process will inherit the working directory of the currently executing script:

const result = await Process.path(import.meta.dirname).run('ls -la');

Input

You may provide input via the "standard input" of the process using the input method:

const result = await Process.input('Hello World').run('cat');

Timeouts

By default, processes will throw an instance of ProcessTimedOutException after executing for more than 60 seconds. However, you can customize this behavior via the timeout method:

const result = await Process.timeout(120).run('bash import.sh');

The timeout and idleTimeout methods also accept intervals:

import { minutes } from '@laraflare/framework';

const result = await Process.timeout(minutes(2)).run('bash import.sh');

Or, if you would like to disable the process timeout entirely, you may invoke the forever method:

const result = await Process.forever().run('bash import.sh');

The idleTimeout method may be used to specify the maximum number of seconds the process may run without returning any output:

const result = await Process.timeout(60).idleTimeout(30).run('bash import.sh');

Environment Variables

Environment variables may be provided to the process via the env method. The invoked process will also inherit all of the environment variables defined by your system:

const result = await Process.forever()
    .env({ IMPORT_PATH: import.meta.dirname })
    .run('bash import.sh');

If you wish to remove an inherited environment variable from the invoked process, you may provide that environment variable with a value of false:

const result = await Process.forever()
    .env({ LOAD_PATH: false })
    .run('bash import.sh');

TTY Mode

The tty method may be used to enable TTY mode for your process. TTY mode connects the input and output of the process to the input and output of your program, allowing your process to open an editor like Vim or Nano as a process:

await Process.forever().tty().run('vim');

Warning

TTY mode is not supported on Windows.

Process Output

As previously discussed, process output may be accessed using the output (stdout) and errorOutput (stderr) methods on a process result:

import { Process } from '@laraflare/framework/console';

const result = await Process.run('ls -la');

console.log(result.output());
console.log(result.errorOutput());

However, output may also be gathered in real-time by passing a closure as the second argument to the run method. The closure will receive two arguments: the "type" of output (out or err) and the output string itself:

const result = await Process.run('ls -la', (type, output) => {
    console.log(output);
});

laraflare also offers the seeInOutput and seeInErrorOutput methods, which provide a convenient way to determine if a given string was contained in the process' output:

if ((await Process.run('ls -la')).seeInOutput('laraflare')) {
    // ...
}

Disabling Process Output

If your process is writing a significant amount of output that you are not interested in, you can conserve memory by disabling output retrieval entirely. To accomplish this, invoke the quietly method while building the process:

import { Process } from '@laraflare/framework/console';

const result = await Process.quietly().run('bash import.sh');

Pipelines

Sometimes you may want to make the output of one process the input of another process. This is often referred to as "piping" the output of a process into another. The pipe method provided by the Process facade makes this easy to accomplish. The pipe method will execute the piped processes in order and return the process result for the last process in the pipeline:

import { Process } from '@laraflare/framework/console';

const result = await Process.pipe((pipe) => {
    pipe.command('cat example.txt');
    pipe.command('grep -i "laraflare"');
});

if (result?.successful()) {
    // ...
}

If you do not need to customize the individual processes that make up the pipeline, you may simply pass an array of command strings to the pipe method:

const result = await Process.pipe([
    'cat example.txt',
    'grep -i "laraflare"',
]);

The process output may be gathered in real-time by passing a closure as the second argument to the pipe method. The closure will receive three arguments: the "type" of output (out or err), the output string itself, and the key of the process:

const result = await Process.pipe((pipe) => {
    pipe.command('cat example.txt');
    pipe.command('grep -i "laraflare"');
}, (type, output) => {
    console.log(output);
});

laraflare also allows you to assign string keys to each process within a pipeline via the as method. This key will also be passed to the output closure provided to the pipe method, allowing you to determine which process the output belongs to:

const result = await Process.pipe((pipe) => {
    pipe.as('first').command('cat example.txt');
    pipe.as('second').command('grep -i "laraflare"');
}, (type, output, key) => {
    // ...
});

Asynchronous Processes

While the run method invokes processes synchronously, the start method may be used to invoke a process asynchronously. This allows your application to continue performing other tasks while the process runs in the background. Once the process has been invoked, you may utilize the running method to determine if the process is still running:

const process = Process.timeout(120).start('bash import.sh');

while (process.running()) {
    // ...
    await sleep(100);
}

const result = await process.wait();

Note

Node runs a process's callbacks between your own code's awaits, so a loop that checks running must await something (a short sleep, for example) on each pass, or it will never see the process finish.

As you may have noticed, you may invoke the wait method to wait until the process is finished executing and retrieve the ProcessResult instance:

const process = Process.timeout(120).start('bash import.sh');

// ...

const result = await process.wait();

Process IDs and Signals

The id method may be used to retrieve the operating system assigned process ID of the running process:

const process = Process.start('bash import.sh');

return process.id();

You may use the signal method to send a "signal" to the running process. A list of predefined signal constants can be found within the Node documentation:

import { constants } from 'node:os';

process.signal(constants.signals.SIGUSR2);

Asynchronous Process Output

While an asynchronous process is running, you may access its entire current output using the output and errorOutput methods; however, you may utilize the latestOutput and latestErrorOutput to access the output from the process that has occurred since the output was last retrieved:

const process = Process.timeout(120).start('bash import.sh');

while (process.running()) {
    console.log(process.latestOutput());
    console.log(process.latestErrorOutput());

    await sleep(1000);
}

Like the run method, output may also be gathered in real-time from asynchronous processes by passing a closure as the second argument to the start method. The closure will receive two arguments: the "type" of output (out or err) and the output string itself:

const process = Process.start('bash import.sh', (type, output) => {
    console.log(output);
});

const result = await process.wait();

Instead of waiting until the process has finished, you may use the waitUntil method to stop waiting based on the output of the process. laraflare will stop waiting for the process to finish when the closure given to the waitUntil method returns true:

const process = Process.start('bash import.sh');

await process.waitUntil((type, output) => {
    return output === 'Ready...';
});

Asynchronous Process Timeouts

While an asynchronous process is running, you may verify that the process has not timed out using the ensureNotTimedOut method. This method will throw a timeout exception if the process has timed out:

const process = Process.timeout(120).start('bash import.sh');

while (process.running()) {
    process.ensureNotTimedOut();

    // ...

    await sleep(1000);
}

Concurrent Processes

laraflare also makes it a breeze to manage a pool of concurrent, asynchronous processes, allowing you to easily execute many tasks simultaneously. To get started, invoke the pool method, which accepts a closure that receives an instance of Pool.

Within this closure, you may define the processes that belong to the pool. Once a process pool is started via the start method, you may access the collection of running processes via the running method:

import { Process } from '@laraflare/framework/console';

const pool = Process.pool((pool) => {
    pool.path(import.meta.dirname).command('bash import-1.sh');
    pool.path(import.meta.dirname).command('bash import-2.sh');
    pool.path(import.meta.dirname).command('bash import-3.sh');
}).start((type, output, key) => {
    // ...
});

while (pool.running().isNotEmpty()) {
    // ...
    await sleep(100);
}

const results = await pool.wait();

As you can see, you may wait for all of the pool processes to finish executing and resolve their results via the wait method. The wait method returns an object that allows you to access the ProcessResult instance of each process in the pool by its key:

const results = await pool.wait();

console.log(results[0].output());

Or, for convenience, the concurrently method may be used to start an asynchronous process pool and immediately wait on its results. This can provide particularly expressive syntax when combined with array destructuring:

const [first, second, third] = await Process.concurrently((pool) => {
    pool.path(import.meta.dirname).command('ls -la');
    pool.path(appPath()).command('ls -la');
    pool.path(storagePath()).command('ls -la');
});

console.log(first.output());

Naming Pool Processes

Accessing process pool results via a numeric key is not very expressive; therefore, laraflare allows you to assign string keys to each process within a pool via the as method. This key will also be passed to the closure provided to the start method, allowing you to determine which process the output belongs to:

const pool = Process.pool((pool) => {
    pool.as('first').command('bash import-1.sh');
    pool.as('second').command('bash import-2.sh');
    pool.as('third').command('bash import-3.sh');
}).start((type, output, key) => {
    // ...
});

const results = await pool.wait();

return results.first.output();

Pool Process IDs and Signals

Since the process pool's running method provides a collection of all invoked processes within the pool, you may easily access the underlying pool process IDs:

const processIds = pool.running().map((process) => process.id());

And, for convenience, you may invoke the signal method on a process pool to send a signal to every process within the pool:

pool.signal(constants.signals.SIGUSR2);

Testing

Many laraflare services provide functionality to help you easily and expressively write tests, and laraflare's process service is no exception. The Process facade's fake method allows you to instruct laraflare to return stubbed / dummy results when processes are invoked.

Faking Processes

To explore laraflare's ability to fake processes, let's imagine a route that invokes a process:

import { Route } from '@laraflare/framework';
import { Process } from '@laraflare/framework/console';

Route.get('/import', async () => {
    await Process.run('bash import.sh');

    return 'Import complete!';
});

When testing this route, we can instruct laraflare to return a fake, successful process result for every invoked process by calling the fake method on the Process facade with no arguments. In addition, we can even assert that a given process was "run":

import { Process } from '@laraflare/framework/console';
import type { PendingProcess, ProcessResultContract } from '@laraflare/framework/console';

test('process is invoked', async () => {
    Process.fake();

    const response = await testCase.get('/import');

    // Simple process assertion...
    Process.assertRan('bash import.sh');

    // Or, inspecting the process configuration...
    Process.assertRan((process: PendingProcess, result: ProcessResultContract) => {
        return process.processCommand === 'bash import.sh' &&
               process.timeoutSeconds === 60;
    });
});

As discussed, invoking the fake method on the Process facade will instruct laraflare to always return a successful process result with no output. However, you may easily specify the output and exit code for faked processes using the Process facade's result method:

Process.fake({
    '*': Process.result('Test output', 'Test error output', 1),
});

The result method's arguments are the output, the error output and the exit code.

Faking Specific Processes

As you may have noticed in a previous example, the Process facade allows you to specify different fake results per process by passing an object to the fake method.

The object's keys should represent command patterns that you wish to fake and their associated results. The * character may be used as a wildcard character. Any process commands that have not been faked will actually be invoked. You may use the Process facade's result method to construct stub / fake results for these commands:

Process.fake({
    'cat *': Process.result('Test "cat" output'),
    'ls *': Process.result('Test "ls" output'),
});

If you do not need to customize the exit code or error output of a faked process, you may find it more convenient to specify the fake process results as simple strings:

Process.fake({
    'cat *': 'Test "cat" output',
    'ls *': 'Test "ls" output',
});

Faking Process Sequences

If the code you are testing invokes multiple processes with the same command, you may wish to assign a different fake process result to each process invocation. You may accomplish this via the Process facade's sequence method:

Process.fake({
    'ls *': Process.sequence()
        .push(Process.result('First invocation'))
        .push(Process.result('Second invocation')),
});

Faking Asynchronous Process Lifecycles

Thus far, we have primarily discussed faking processes which are invoked synchronously using the run method. However, if you are attempting to test code that interacts with asynchronous processes invoked via start, you may need a more sophisticated approach to describing your fake processes.

For example, let's imagine the following route which interacts with an asynchronous process:

import { Log, Route } from '@laraflare/framework';
import { Process } from '@laraflare/framework/console';

Route.get('/import', async () => {
    const process = Process.start('bash import.sh');

    while (process.running()) {
        Log.info(process.latestOutput());
        Log.info(process.latestErrorOutput());
    }

    return 'Done';
});

To properly fake this process, we need to be able to describe how many times the running method should return true. In addition, we may want to specify multiple lines of output that should be returned in sequence. To accomplish this, we can use the Process facade's describe method:

Process.fake({
    'bash import.sh': Process.describe()
        .output('First line of standard output')
        .errorOutput('First line of error output')
        .output('Second line of standard output')
        .exitCode(0)
        .iterations(3),
});

Let's dig into the example above. Using the output and errorOutput methods, we may specify multiple lines of output that will be returned in sequence. The exitCode method may be used to specify the final exit code of the fake process. Finally, the iterations method may be used to specify how many times the running method should return true.

Available Assertions

As previously discussed, laraflare provides several process assertions for your feature tests. We'll discuss each of these assertions below.

assertRan

Assert that a given process was invoked:

import { Process } from '@laraflare/framework/console';

Process.assertRan('ls -la');

When the process was invoked with an array of arguments, you may pass the same array to the assertion:

Process.assertRan(['npx', 'artisan', 'migrate']);

The assertRanTimes and assertDidntRun methods also accept array commands.

The assertRan method also accepts a closure, which will receive an instance of a process and a process result, allowing you to inspect the process' configured options. If this closure returns true, the assertion will "pass":

Process.assertRan((process, result) =>
    process.processCommand === 'ls -la' &&
    process.workingPath === import.meta.dirname &&
    process.timeoutSeconds === 60
);

The process passed to the assertRan closure is an instance of PendingProcess, while the result is an instance of ProcessResultContract. A PendingProcess holds what its methods set in processCommand, workingPath, timeoutSeconds, idleTimeoutSeconds, environment and inputData.

assertDidntRun

Assert that a given process was not invoked:

import { Process } from '@laraflare/framework/console';

Process.assertDidntRun('ls -la');

Like the assertRan method, the assertDidntRun method also accepts a closure, which will receive an instance of a process and a process result, allowing you to inspect the process' configured options. If this closure returns true, the assertion will "fail":

Process.assertDidntRun((process: PendingProcess, result: ProcessResultContract) =>
    process.processCommand === 'ls -la'
);

assertRanTimes

Assert that a given process was invoked a given number of times:

import { Process } from '@laraflare/framework/console';

Process.assertRanTimes('ls -la', 3);

The assertRanTimes method also accepts a closure, which will receive an instance of PendingProcess and ProcessResultContract, allowing you to inspect the process' configured options. If this closure returns true and the process was invoked the specified number of times, the assertion will "pass":

Process.assertRanTimes((process: PendingProcess, result: ProcessResultContract) => {
    return process.processCommand === 'ls -la';
}, 3);

assertRanInOrder

Assert that processes were invoked in a given order:

Process.assertRanInOrder([
    'git fetch',
    'npm install',
]);

The assertRanInOrder method accepts command strings, arrays of command arguments, or closures like the other process assertions.

Preventing Stray Processes

If you would like to ensure that all invoked processes have been faked throughout your individual test or complete test suite, you can call the preventStrayProcesses method. After calling this method, any processes that do not have a corresponding fake result will throw an exception rather than starting an actual process:

import { Process } from '@laraflare/framework/console';

Process.preventStrayProcesses();

Process.fake({
    'ls *': 'Test output...',
});

// Fake response is returned...
await Process.run('ls -la');

// An exception is thrown...
await Process.run('bash import.sh');

Note

Call preventStrayProcesses before fake: each call to fake starts from a new process factory, so what an earlier test faked or recorded does not carry over, and only the stray-process setting does.

Adapted from Laravel's documentation, Copyright (c) Taylor Otwell, used under the MIT License.