wasmerio / wasmer-php

🐘🕸️ WebAssembly runtime for PHP
https://wasmerio.github.io/wasmer-php/wasm/
MIT License
1.01k stars 42 forks source link

feat(extension) Persistent modules #33

Closed Hywan closed 5 years ago

Hywan commented 5 years ago

Address #28.

A module can now be persistent. To enable it, pass a module unique identifier as a second argument to wasm_compile like this:

$bytes = wasm_fetch_bytes('my_program.wasm');
$module = wasm_compile($bytes, 'unique_identifier_foo_bar');

Or with the library:

$module = new Wasm\Module('my_program.wasm', Wasm\Module::PERSISTENT);

In this latter case, the module unique identifier is generated by the Wasm\Module::getUniqueIdentifier function, which by default computes the SHA3-512 of the real filepath.

This PR also renames wasm_read_bytes to wasm_fetch_bytes. Bytes are read lazily on-demand when the C function wasm_bytes_from_resource is called, i.e. when the PHP functions wasm_validate, wasm_compile and wasm_new_instance are called. Why? Because we don't want to read the bytes when the module has already been compiled and is persistent. So wasm_compile reads the bytes only when necessary.

Small benchmark with the nbody.wasm file:

It brings a speedup of 838 times :tada:. Note that it's absurd to compare a read+compilation vs. nothing :-], but it shows that —effectively— nothing happens when a persistent resource is found.

This PR also introduces the wasm_module_clean_up_persistent_resources function but it must be used only when no PHP requests are running, else it's easy to corrupt concurrent executions since the destructor wasm_module_destructor function is called. This function is not used in the library.

By default, all Wasm\Module are volatile.

Hywan commented 5 years ago

cc @xtuc