Limits and permissions
A call stack that is too deep throws RecursionError. A call that needs a permission you did not
give in nvs.toml throws RuntimeError. You can catch both. The program then continues.
A call stack that is too deep
A function that calls itself without ever returning is stopped. When the call stack grows past the depth Novis allows, the innermost call throws a RecursionError. The limit is on the size of the stack rather than on a number of calls, so how deep you can go depends on what each call holds. A small function reaches a few thousand calls.
A RecursionError is a kind of RuntimeError, so catch (RecursionError $e) and catch (RuntimeError $e) both handle it, and the program carries on. The frames are already gone when the handler runs, so the handler has the whole stack available again and may keep working. Uncaught, a RecursionError ends the program like any other error.
This is what makes a recursive walk over data you did not write safe. Input nested far deeper than you expected, or a cycle in a table you follow, gives you an error you can report instead of a crash.
The examples below show a runaway recursion caught, a walk a thousand calls deep that finishes, and a redirect chain that loops back on itself.
Catching a runaway recursion
<?nvs// Shows a function that calls itself with no way out. The runtime stops it at// the depth limit with a `RecursionError`, the `catch` handles it, and the// program carries on.
final class Down{ public static function forever(int $n): int { return Down::forever($n + 1) + 1; }}
try { echo Down::forever(0), "\n";} catch (RecursionError $tooDeep) { // This prints "stopped: the call stack is too deep". echo 'stopped: ', $tooDeep->message, "\n";}
echo "the program carries on\n";stopped: the call stack is too deepthe program carries onA deep walk that finishes
<?nvs// Shows how much room recursion has. This function calls itself a thousand// times before it returns, which stays inside the limit, so it finishes and// prints its result.
final class Sum{ public static function upTo(int $n): int { if ($n == 0) { return 0; } return $n + Sum::upTo($n - 1); }}
// This prints 500500.echo Sum::upTo(1000), "\n";500500A redirect chain that loops
<?nvs// Shows a recursive walk over a table somebody else filled in. Two entries that// point at each other make the walk endless, and the depth limit turns that// into an error you can report.
final class Links{ public static function follow(array<string> $targets, string $from): string { string $next = $targets[$from] ?? ''; if ($next == '') { return $from; } return Links::follow($targets, $next); }}
array<string> $plain = ['/old' => '/new', '/new' => '/home'];array<string> $loop = ['/a' => '/b', '/b' => '/a'];
// This prints /home.echo Links::follow($plain, '/old'), "\n";
try { echo Links::follow($loop, '/a'), "\n";} catch (RecursionError $endless) { echo "the redirect chain does not end\n";}/homethe redirect chain does not endA catch in the middle of the calls
<?nvs// Shows a `catch` in one of the calls of a deep recursion. The calls inside it// are gone. The calls outside it go on and return a value.
final class Down{ public static int $caughtAt = -1;
public static function count(int $depth): int { int $next = $depth + 1; if ($depth == 100) { try { return Down::count($next); } catch (RecursionError $tooDeep) { Down::$caughtAt = $depth; return 0; } } return Down::count($next) + 1; }}
// The call at depth 100 returns 0, and each of the 100 calls outside it adds 1.// This prints "100 calls returned, caught at depth 100".echo Down::count(0), ' calls returned, caught at depth ', Down::$caughtAt, "\n";100 calls returned, caught at depth 100Details
The message of the error is the call stack is too deep. $e is RuntimeError is true.
A function with a few parameters and locals reaches fewer calls than a function with one. The exact number can change between versions of Novis, so do not write code that needs it.
A catch in any of the calls handles the error. The calls inside it are gone, and the calls outside it go on as usual. The program may call the deep function again after a catch, and it throws a RecursionError again.
finally blocks in each call run while the error leaves the calls.
backtrace has one entry for each call, so a RecursionError has a few thousand entries. An uncaught one prints all of them in the report.
You may throw a RecursionError yourself with new RecursionError("…").
A call without permission
A call your program is not allowed to make throws a RuntimeError.
Reading a file, writing a file and starting another script each need a capability. A capability is permission to do one kind of thing. The person who runs the server grants it in nvs.toml. A program you start from the command line may read and write any file. A server program may read its application folder and write only its own temporary folders.
A call without the grant throws before it does any work. The message names the method, the capability it needed and the path it was given. A help: line under it says where to write the grant. This is an ordinary throw, so catch (RuntimeError $denied) takes it and the program keeps running.
Your program can use that. Try the call, catch the error, and do the work another way if it is not allowed.
The examples below show a call nobody allowed, and a grant that lets one call through while a second call is still denied. The third is a program that finishes its work without the capability.
The examples below run with this configuration file.
# Example 01 may not read any file.[[app]]entry = "01-a-call-nobody-allowed.nvs"
[app.capabilities.fs]read = []
# Example 02 may read the files in the `data` folder. It may not write any file.[[app]]entry = "02-a-grant-in-nvs-toml.nvs"
[app.capabilities.fs]read = ["data"]write = []
# Example 03 may not write any file.[[app]]entry = "03-a-report-when-the-disk-is-closed.nvs"
[app.capabilities.fs]write = []A call nobody allowed
<?nvs// Shows what a program sees when it reads a file and `nvs.toml` does not allow// it. The call throws a `RuntimeError`. The `catch` takes it, and the program// keeps running.
try { echo Core\IO::read('orders.csv');} catch (RuntimeError $denied) { // The message names the method, the capability and the full path of the file. // This prints the part before the path. echo Core\Str::before($denied->message, ' for '), "\n"; // The second line of the message is the line to add to `nvs.toml`. // It also contains the full path of the folder. This prints `...` in its place. tainted string $help = Core\Str::after($denied->message, "\n") ?? ''; echo Core\Str::before($help, "\""), '...]', Core\Str::after($help, "\"]"), "\n";}
echo "still running\n";Core\IO::read needs the capability `fs.read`help: add `read = [...]` under `[capabilities.fs]` in nvs.tomlstill runningA grant in nvs toml
<?nvs// Shows a program with one capability and not the other. `nvs.toml` grants// `fs.read` for one directory, so reading a file there works. Writing a file// needs `fs.write`, and this program does not have it.
echo Core\Str::trim(Core\IO::read('data/notice.txt')), "\n";
try { Core\IO::write('data/notice.txt', 'The shop is open all night.');} catch (RuntimeError $denied) { // The message names the full path of the file. This prints the part before it. echo Core\Str::before($denied->message, ' for '), "\n";}The shop closes at 18:00.Core\IO::write needs the capability `fs.write`A report when the disk is closed
<?nvs// Shows a program that does its work without a capability. It saves a report// to a file. Writing is not allowed here, so it prints the report instead.
string $report = 'orders: 3, total: 41.50';
try { Core\IO::write('report.txt', $report); echo "the report is in report.txt\n";} catch (RuntimeError $denied) { echo "report.txt cannot be written, so here is the report\n"; echo $report, "\n";}report.txt cannot be written, so here is the reportorders: 3, total: 41.50Details
The message has two lines. The first is `Core\IO::read needs the capability fs.read for <path>, which is not granted, with the full path of the file. The second is the line to add to nvs.toml: help: add read = ["<folder>"] under [capabilities.fs] in nvs.toml. <folder>` is the full path of the folder that contains the file.
fs.read covers every call that looks at a file, such as Core\IO::exists, and not only Core\IO::read. fs.write is a separate capability. A grant of read for a folder does not let your program write there.
A grant lists folders. Novis resolves each path to its real full path before it checks it. A .. that leads out of a granted folder is denied, and so is a symbolic link that points out of one. A path with .. that ends inside a granted folder is allowed.
A file that does not exist inside a granted folder is not a denial. The call throws IOError, a subclass of RuntimeError, with the operating system's message. A path that does not exist outside every granted folder is denied like any other path.
spawn script "job.nvs" needs script.spawn. Its message starts with `spawn script needs the capability script.spawn `, and the help: line names [capabilities.script]`.
Limits that stop the program
A resource limit stops your program at once, and no catch sees it.
nvs.toml sets four limits for a program: memory, cpu_time, wall_time and max_output. A program that goes past one of them is stopped where it stands. This is a FATAL. It is not a Throwable, so no catch clause matches it and no finally runs. The program writes a line starting with FATAL: to standard error and ends with status 1.
One hook runs before that end. Core\Fatal::onLimit registers a function that runs once when a limit stops the program, and it is told which limit fired. Use it to write a last note about what the program was doing. Registering a second function replaces the first. The program still ends after the handler.
The examples below show a limit that no catch and no finally sees, and a handler that names the limit that fired. The third is a job that records the order it stopped on.
The examples below run with this configuration file.
# Each example in this folder may use at most 16 megabytes of memory.[limits]memory = "16M"No catch sees a limit
<?nvs// Shows what a memory limit does to a program. `nvs.toml` gives this program// 16 megabytes. Holding more than that stops it where it stands. No `catch`// and no `finally` runs, and the program ends with status 1.// proof: exit 1
echo "before the limit\n";
try { array<string> $ballast = []; int $slab = 0; while ($slab < 4) { $ballast[] = Core\Str::repeat('x', 8388608); $slab = $slab + 1; } echo "not reached\n";} catch (Throwable $never) { // A limit is not a throw, so no class matches it. `Throwable` is the widest // clause there is, and it does not run either. echo "not reached: the catch ran\n";} finally { echo "not reached: the finally ran\n";}
echo "not reached: the program went on\n";before the limitA handler for the last moment
<?nvs// Shows the one hook a limit runs. `Core\Fatal::onLimit` registers a function// that runs when a limit stops the program. The function receives the name of// the limit that fired. The program still ends after it.// proof: exit 1
Core\Fatal::onLimit(fn(array<string> $report): void => { echo 'stopped by the ', $report['limit'], " limit\n";});
echo "working\n";
array<string> $ballast = [];int $slab = 0;while ($slab < 4) { $ballast[] = Core\Str::repeat('x', 8388608); $slab = $slab + 1;}
echo "not reached\n";workingstopped by the memory limitA job that says where it stopped
<?nvs// Shows how to leave a note when a limit stops a job. The handler prints the// order the job was on, so the person reading the log can start again from// there.// proof: exit 1
final class Job{ // The handler reads this. An anonymous function copies the variables it // captures when it is written, so a variable would still have its first value here. public static string $current = 'none';}
Core\Fatal::onLimit(fn(array<string> $report): void => { echo 'stopped on order ', Job::$current, ', limit: ', $report['limit'], "\n";});
array<string> $orders = ['A-1001', 'A-1002', 'A-1003', 'A-1004'];array<string> $labels = [];
foreach ($orders as string $order) { Job::$current = $order; echo 'packing ', $order, "\n"; $labels[] = Core\Str::repeat('x', 8388608);}
echo "not reached\n";packing A-1001packing A-1002stopped on order A-1002, limit: memoryDetails
The FATAL: line on standard error names the limit and the numbers. For memory it gives the bytes the program held, the limit, and the part of the limit kept for the handler. With memory = "16M", 1 megabyte is kept for the handler, so the program itself can use 15 megabytes. When nvs.toml sets no memory limit, the limit is 128M.
The handler receives an array with one key, limit. Its value is the name of the limit as nvs.toml writes it: memory, cpu_time, wall_time or max_output. The handler may also declare no parameter. A handler with a parameter of another type, such as fn (int $x): void, is the error E0401.
Core\Fatal::onLimit keeps one handler. A second call replaces the first, so only the last handler runs.
The handler runs once. If it throws an error, the error is not shown, and the program still writes the FATAL: line and ends with status 1. After the max_output limit, what the handler prints with echo still reaches standard output.
Two more errors end the program in the same way: send on a closed Core\Task\Channel, and new Core\Task\Channel<int>(0). Each writes a FATAL: line that names the method, and the program ends with status 1. No catch and no finally runs. The onLimit handler does not run either, because no limit fired.
Do and don’t
Section titled “Do and don’t”- Do catch
RecursionErrorwhere deep input can reach a recursive function. - Do limit each permission in
nvs.tomlto the folders and hosts your server needs. - Do use
Core\Fatal::onLimitto log which limit stopped the program. - Don’t use
catchto handle the memory limit. It is never caught.
