WASM addons: one source, a native crate and a sandboxed component
Status: implemented (macros, dispatch, lifecycle, CLI, proof of concept, UI and override surfaces). The
macros and erp-sdk compile the same addon source natively and for wasm32-wasip2; a component exports describe() and
runs its methods in mixed native/WebAssembly override chains, overrides the core create, write and unlink, and
contributes scalar computed fields and constraints; a package installs into a running server, brings views, window
actions, menus and access rows, and its public methods are callable from the web client. Onchanges of a component come
later. Contract: ADR 0081, wit/addon/. Design:
docs/design/m2b-macros-wasm-backend.md.
Every example is taken from code that builds in CI: crates/erp-test-models/addons/test_wasm_dual_a and
test_wasm_dual_b and test_wasm_dual_c, tested by crates/erp-test-models/tests/wasm_dual_describe.rs,
wasm_dispatch_chain.rs and wasm_dispatch_component.rs (CI step wasm-dual-describe).
What stays the same
Section titled “What stays the same”You write #[model], #[extend], #[methods] with #[method], #[method(override)], #[compute],
#[constrains], #[onchange] and addon! exactly as for a native addon (see models.md,
cross-addon-extension.md). No cfg appears in business code. erp_sdk selects its backend by target: the
native one links the ORM, registry and database crates; for WebAssembly it is a small facade over erp-fields and
the guest bindings, with no ORM or database dependency.
use erp_sdk::prelude::*;
erp_sdk::addon!(name = "test_wasm_dual_a", depends = ["base"]);
#[model(name = "test.wasm.dual", description = "WASM dual-mode fixture")]pub struct Dual { #[field(char, required = true)] pub name: Option<Arc<str>>, #[field(integer, default = 1)] pub qty: i32,}An addon that extends another does so as on native: depend on the other crate and #[extend(Dual)]. Both crates
end up in one component.
Making a component
Section titled “Making a component”The crate you compile to the component (the leaf: test_wasm_dual_b above) writes one line:
erp_sdk::export_component!();Natively it expands to nothing. On WebAssembly it exports the addon world. Two build requirements:
Model company_access declarations use the same #[model] and #[extend] syntax in both
targets. The package loader reads all four forms from the component descriptor and passes
them to registry validation (ADR 0093). A malformed or unsupported declaration refuses
the package operation. Omission has the same meaning as an absent native declaration;
it does not imply unrestricted. The encoded company_access expression is limited to
8,192 bytes; the decoded unrestricted reason remains limited to 512 bytes.
For an existing package, deploy a server that understands this descriptor first,
upgrade the package with its explicit decisions, and verify it reloads before
enabling mandatory company access declarations for the registry.
- Lints. The export glue is the component ABI’s unsafe code, which the workspace’s
unsafe_code = "forbid"cannot allow. In the leaf crate’sCargo.tomlreplace[lints] workspace = truewith[lints.rust] unsafe_code = "deny"plus the workspace’s clippy denies (seetest_wasm_dual_b/Cargo.toml). The glue is allowed on that one expansion; nothing you write is unsafe. - Fat LTO. Build with
lto = "fat"(CARGO_PROFILE_RELEASE_LTO=fat). Without it the linker may drop the registrations of a dependency addon that no code references, anddescribe()would then miss that addon. CI builds the fixture this way and compares the result with the native build, which fails on a missing addon.
CARGO_PROFILE_RELEASE_LTO=fat cargo rustc --release -p erp-addon-test_wasm_dual_b \ --crate-type cdylib --target wasm32-wasip2erp addon build --target wasm does this for you:
erp addon build my_addon --target wasm --addons-path ./addonserp addon package my_addon --addons-path ./addons -o my_addon-1.0.0.erpaddonbuild compiles the crate in the addon directory as a cdylib for wasm32-wasip2 with fat LTO (set for that build
only), loads the result with the WASM host under its CPU and memory limits, and checks that describe() lists the
addon and every dependency of its manifest that has a [wasm] section; a missing one is an error naming it. The
component is then written to <addon>/wasm/<name>.wasm. The manifest needs a [wasm] section (sdk_version = "1.0");
a dependency that is a native addon, or that is not in the search paths, is listed in the output as not expected.
package writes the .erpaddon (manifest, the files data/demo name, i18n/, migrations/, static/dist/, the
component, SHA256SUMS), reads it back from disk with the installer’s reader, and prints the archive sha256 and the
capabilities the manifest requests. Both commands need the target once: rustup target add wasm32-wasip2; if it is
missing they stop with that command before building. Details: docs/design/m2b-cli.md.
describe()
Section titled “describe()”A component’s describe() returns what erp_sdk::describe() returns in a native program that links the same
addons: compact JSON, {"schema":1,"contributions":[...]}, one entry per addon, model, extension, method,
override, compute, constraint and onchange, sorted by (addon, model, kind, name, detail). An entry has addon,
kind (addon, model, extend, method, override, compute, compute_override, constraint, onchange),
model (empty for addon), name and a detail object. Models and extensions carry their arguments and fields
(name, kind, attrs); methods their arguments and result type; computes depends, reads,
depends_context; constraints and onchanges their field lists. Values are the source text you wrote ("1",
"\"Note\""), not resolved types. The text is produced by the macros at compile time, so the native and the WASM
build of one source cannot differ.
Methods in a component
Section titled “Methods in a component”A component runs the methods its addon registered (#[method], #[method(override)]) inside the same override
chains as native addons: a WebAssembly layer sits between native layers in the order of the addons, and super
crosses in both directions. A chain that mixes native and WebAssembly layers needs the wire form of the native
method: every native #[method] whose arguments and result implement Serialize + DeserializeOwned + Send + 'static has it without any attribute (WASM.WIRE-NATIVE). When the types of a native method are not serialisable,
or the method is sealed (below), the registry build refuses the chain and names each native implementation with
the type that blocks it (for example Vec<RawVals>, argument vals_list) or the place that seals it. #[method(wire)]
(or #[method(override, wire)]) is still accepted: it asserts at compile time that the method has a wire form, and
the compile error names the method and the type. Arguments travel as the JSON of the tuple (["x"]; no arguments
is null), the result as JSON.
#[method(override, wire)]async fn label(this: &RecordSet<Dual>, tx: &mut Transaction, prefix: String, sup: Super) -> Result<String> { let inner = sup.call(tx, this, (prefix,)).await?; // the layer below, native or WebAssembly Ok(format!("{inner}{MARK}"))}Sealed methods (for native addon authors)
Section titled “Sealed methods (for native addon authors)”#[method(sealed)] (or #[method(override, sealed)]) keeps a native method out of every chain that has a
WebAssembly layer: a package that overrides it is refused when the registry is built, with the method and the place
that seals it, whatever its types. One sealed implementation seals the chain. Seal what a package must never wrap or
skip: credentials, sessions, API keys, access rows, groups and membership, company access, record rules, validation
of stored definitions (views), and the schema and registry hooks (init, _register_hook). sealed and wire
contradict each other and are refused together. Base and mail seal their methods of that kind; the list is in
docs/design/WASM.WIRE-NATIVE-plan.md, section “Sealed methods”.
Three more seals need no attribute:
- Every
#[constrains]method is sealed as a constraint and every#[onchange]method as an onchange: the ORM runs them through their chains while it checks a write or answers a form, and a package layer that does not callsuperwould skip the check. Package overrides of constraints come with WASM.COMPUTE-REL, of onchange methods with WASM.ONCHANGE.wireon such a method is a compile error. - The core seals its record-level methods (
action_archive,action_unarchive,create,write,unlink,copy,copy_data,default_get,name_create,upsert,exists,filtered_domain) onres.users,res.groups,ir.access,res.users.apikeysandir.config_parameter(the listSEALED_ON_MODELincrates/erp-orm/src/method_wire.rs), whatever the native entries of the chain say; the refusal names the model, the method and the list’s line. - A native entry with no wire record at all (a core method without a codec yet, a selection hook, an implementation registered by hand) refuses every chain that crosses into a package, naming that entry.
A seal limits overriding, not calling. Native code and RPC call a sealed method as before. What a package may call
is decided separately (the methods exposed over RPC and the addon’s own, CallableMethods in
crates/erp-wasm-host/src/dispatch.rs). A sealed implementation contributes no wire codec, so a package’s call in
the wire form reaches a sealed method only when another native implementation of its chain has one; otherwise the
call is refused, naming what blocks it.
#[method(sealed)]async fn _set_password(this: &RecordSet<ResUsers>, tx: &mut Transaction) -> Result<()> { /* … */ }What a body may do in a component today: this.ensure_one(), this.get(tx, Field) and this.set(tx, Field, value)
for boolean, integer, float, decimal (read), char, text, html, selection, date, datetime, many2one and x2many fields;
sup.call(tx, this, args); the typed <Type>Methods call of another method (this.shout(tx, text).await);
tx.search_json(domain_json, limit, order); and creating, writing
several fields at once and following a relation (next section). Each is an
orm-host import made as the calling user and company and
through the ORM’s access rules; the host refuses what the administrator did not approve (orm:read,
orm:write, orm:create, orm:unlink, orm:call-method) with access-denied. A body must not wait on anything
but those calls. One call has a time budget (Limits::cpu, default 500 ms) that covers the guest and every host
call it waits for; a runaway or overdue call fails the method and poisons the transaction.
The same source runs natively: get, set, ensure_one, sup.call and the <Type>Methods calls have the native
signatures. search_json is the one guest-only call (the typed Domain is not in a component yet).
A component has no source of randomness: std::collections::HashMap and HashSet trap on first use with
wasi:random/insecure-seed ... has not been defined. Use BTreeMap/BTreeSet or a Vec.
Creating, writing and following relations
Section titled “Creating, writing and following relations”A component creates records, writes several fields at once, takes an empty recordset of another model and follows a
many2one to its records with the native API (crates/erp-test-models/addons/test_wasm_refs is the same source in
both modes; tests/wasm_refs_flow.rs runs it natively and as a component and expects the same answers):
let loans = this.env().model::<Loan>()?; // empty RecordSet<Loan>; env().model is the native calllet vals = loans.vals() // Vals<Loan>: only Loan fields (or those of models it inherits) .set(Loan::BOOK_ID, book.rec_ids()[0]) // Many2one<Book> takes a RecId .set(Loan::BORROWER_ID, partner_id) .set(Loan::LOAN_DATE, today) // Option<Date> takes a Date .set(Loan::STATE, "out"); // Option<Arc<str>> takes &strlet loan = loans.create(tx, vec![vals]).await?; // RecordSet<Loan> of the new recordsbook.write(tx, book.vals().set(Book::AVAILABLE, false)).await?; // several fields: one `write`let book = loan.related(tx, Loan::BOOK_ID).await?; // Many2one<Book> -> RecordSet<Book> (x2many too)| Call | Signature in both backends | Goes through |
|---|---|---|
this.env() / tx.env() | &Env / Env; Env::model::<M>() -> Result<RecordSet<M>> | nothing: an empty set. Whether the model exists is the host’s to say, at the first call that uses it |
Vals::<M>::new(), rs.vals(), .set(field, value) | typed by the field handle; a handle of another model does not compile | nothing |
rs.create(tx, Vec<Vals<M>>) | Result<RecordSet<M>>, one create-batch for the list; an empty list is a no-op | the model’s whole create chain: every addon’s override runs (native and WebAssembly), then the core. Needs orm:create; a create layer that calls super also needs orm:unlink, because values may carry x2many removals |
rs.write(tx, Vals<M>) | Result<()>, one write-batch for all fields; nothing happens on an empty set or no value | the model’s whole write chain. Needs orm:write |
rs.related(tx, field) | Result<RecordSet<Comodel>> for a Many2one<C> or X2many<C> handle, in order, each record once | one read-columns. Needs orm:read |
rs.browse(ids), rs.iter(), rs.rec_ids(), rs.len() | as native | nothing |
Values cross with the host’s own validation, field by field: a value that does not fit its field is a validation error
naming the field, never a default. Not in a component yet: x2many command values in Vals (Vals::commands), new
(in-memory) records, Records::create on untyped sets.
Naming fields another addon declares (model_ref! with fields)
Section titled “Naming fields another addon declares (model_ref! with fields)”model_ref!(pub Loan = "sample_library.loan") names a model. Add a field list to also get typed Field handles for
fields that the owner (a data-only addon’s TOML, or a native addon) or another extending addon declared:
erp_sdk::model_ref!( /// `sample_library.loan`, declared by the data-only addon `sample_library`. pub Loan = "sample_library.loan" { state: Option<Arc<str>>, // selection (also char, text, html) book_id: Many2one<Book>, // Book is another model_ref! borrower_id: Many2one<Partner>, loan_date: Option<Date>, due_date: Option<Date>, return_date: Option<Date>, });// Loan::STATE, Loan::BOOK_ID, ... are Field<Loan, T> constants (the field name in upper case);// `Loan` is also the model type of #[extend(Loan)] and #[methods(Loan)].- The handle types are the field types of
#[field]:bool,i32/Option<i32>,f64,Decimal,Option<Arc<str>>(char, text, html, selection),Option<Date>,Option<DateTime>,Option<serde_json::Value>,Many2one<C>,X2many<C>(one2many, many2many),Vec<RecId>. Any other type is a compile error (trait boundRefType). - The handle list goes into
describe()(entry kindmodel_ref, with the kinds the Rust type can hold and the comodel of a relation). When a package is installed or upgraded, the installer checks every handle against the registry of the module set it joins: a model nobody declares, a field the model does not have, a field of a kind the Rust type cannot hold (Option<Arc<str>>on an integer field) or aMany2one<C>whose field points at another model refuses the install withWasmReason::ModelRef, naming the addon, the model and the field, and nothing is written. This was chosen over a first-use check because the guest has no field metadata, and a handle that cannot work should never reach a running database. - A native build of the same source has no installer: a wrong handle shows at first use, as the ORM’s own error for
an unknown field or a value of the wrong type.
describe()carries the same entry natively, so a test can run the check (erp_modules::wasm_lifecycle::check_refs_in_registry, used bywasm_refs_flow.rs). - The handles do not make this addon the owner of the fields: they add no field, column or access rule. Declare the
addon’s own fields with
#[extend]as before. Two addons may name the same fields independently.
Overriding create, write and unlink
Section titled “Overriding create, write and unlink”The core methods are overridden from a component exactly as from a native addon, with the same signatures and
super. No wire is needed on them: the core implementations ship their wire form. The same holds for
name_create (["name"] in, [id, "display name"] out), action_archive and action_unarchive (null in and
out) since WASM.WIRE-NATIVE. On res.users, res.groups, ir.access, res.users.apikeys and
ir.config_parameter these core methods are sealed (above) and cannot be overridden from a component.
#[method(override)]async fn write(this: &RecordSet<Loan>, tx: &mut Transaction, mut vals: RawVals, sup: Super) -> Result<()> { if vals.contains("due_date") && !vals.contains("renewal_note") { vals.insert("renewal_note".into(), Cell::Str("due date edited by hand".into())); } sup.call(tx, this.as_records(), (vals,)).await // the core write, same user and company}- The override sits in the chain at the position of its addon, in the same
(depth, order)order as native layers: a native layer above and one below it both run, in that order (wasm_override.rs). superreaches the next layer or the core implementation with the environment of the records the method was invoked on (user,sudo, companies, context): access rights, record rules and the other checks of the core apply to what the override passes down, and a refusal comes back as the same error kind. An override cannot widen what its caller may do.createtakesVec<RawVals>and returnsRecords(the new ids);writetakesRawValsand the records are the ones being written;unlinktakes nothing. Values travel as JSON and are converted again with the field’s own type on the way down, so a value that does not fit its field is a validation error naming the field, never a default.- A component’s
RawValshas the scalar API of the native one (get,insert,remove,contains,iter). A selection is aCell::Str; date/datetime text also staysCell::Str, while an x2many command list or JSON document staysCell::Json. An untouched value goes back unchanged; the host validates it against the field. - A
createoverride must answer exactly the records itssuper()created, in order. The host records what thesuper-callofcreatereturned and compares: any other answer (a dropped, repeated or foreign id) is a validation error and the transaction cannot commit. The answer must also have one record per input value; skippingsuperfor a non-empty create is refused. - An
unlinkorwriteoverride that does not callsuperskips the layers below, the core included, and still reports success, as an override that does not callsuper()does in Odoo. Callsuperunless you mean to veto by returning an error. - In a
sudoor System environment (module install, data load,sudo()callers) a guest asks the host for nothing butsuper-call: the elevation belongs to the caller, not to the guest. Test a method that reads or writes as an ordinary user. - An override that returns an error ends the call; the layers below do not run. A
Validationerror poisons the transaction as in a native override.
copy, copy_data, default_get, exists, filtered_domain and upsert
Section titled “copy, copy_data, default_get, exists, filtered_domain and upsert”These six core methods are overridden from a component the same way since WASM.WIRE-NATIVE.CORE-CODECS: the same
signature as in a native addon, super reaches the layer below or the core, and no wire is needed. Before, the
registry build refused such an override.
use erp_sdk::ValueMap;
#[method(override)]async fn default_get(this: &RecordSet<Loan>, tx: &mut Transaction, fields: Vec<String>, sup: Super) -> Result<ValueMap> { let mut values = sup.call(tx, this.as_records(), (fields,)).await?; // the core's defaults values.insert("renewal_note".to_owned(), Value::str("new loan")); Ok(values)}| Method | Arguments | Result | What crosses (the JSON of the argument tuple, the JSON of the result) |
|---|---|---|---|
copy | Option<ValueMap> (the default) | Records | [default], a values object or null; the ids of the copies |
copy_data | Option<ValueMap> | Vec<Option<ValueMap>> | [default]; one values object (or null) per record |
default_get | Vec<String> (field names) | ValueMap | [[field, ...]]; a values object |
exists | none | Records | null; the ids that exist |
filtered_domain | Domain | Records | [domain] in list syntax; the matching ids |
upsert | UpsertCall | UpsertResult | [{"key", "rows", "update", "accumulate"}]; one [id, outcome, previous_version, version] per input row |
- The types have the names and the methods of the native ones (
erp_sdk::ValueMap, andDomain,UpsertCall,UpsertOutcome,UpsertResultin the prelude), so one source compiles in both backends. In a component aValueMapis the same ordered map (insert,get,iter); aDomainis its list syntax (Domain::from_json(&json),to_json()), without the builder API; anUpsertCallhas the builder and accessors of the native one. - Values are untyped on the way, as a client’s, and the host checks each against its field when the call reaches
the native implementation: a value that does not fit is a validation error naming the field. A field that has no
form in this ABI (bigint, uuid, xid8, timestamptz, binary) is refused by name in a
defaultand in an upsert row, as increateandwrite. existsandfiltered_domainare filters: an override answers a subset of the records it ran on, each at most once. An id that is not one of them, or that comes twice, is a validation error naming the id.copyanswers one record andcopy_dataone entry per record it ran on, anddefault_getanswers only fields it was asked for; any other answer is a validation error naming the difference.- The result of an
upserthas one entry per input row, in input order; an override that answers another count is refused, naming both counts. Leave the number of rows unchanged when you adjustrows_mut(). - A domain an override passes down is read as external input: the internal traversal operators of native framework code do not cross, so a native caller’s domain that uses them is refused at the layer, by name.
- Capabilities for the
superof these methods (and for calling the exposed ones) follow what they do:copyandcopy_dataneedorm:create,orm:unlink(their values may carry remove commands) andorm:read(they read the records),upsertneedsorm:create,orm:write,orm:unlinkandorm:read,default_get,existsandfiltered_domainneedorm:read. - An addon’s own
default_getorcopy_dataruns only when the addon holdsorm:createandorm:unlink, even if it calls nothing: what it answers becomes the values of a create, and values for a create need those capabilities however they are supplied. Without them the call is an access error naming the capability. - On
res.users,res.groups,ir.access,res.users.apikeysandir.config_parameterall six are sealed. - Not checked at the boundary: the answers of
copyandupsertoverrides are not compared with what theirsuperdid (the host does that forcreateonly). Access to the records they name is checked when they are used.
Computed fields and constraints
Section titled “Computed fields and constraints”#[field(char, string = "Lending summary", compute = "compute_lending_summary")]pub lending_summary: Option<Arc<str>>,#[field(boolean, string = "Popular", compute = "compute_popular", store = true)]pub popular: bool,
#[compute(depends = ["times_lent", "last_borrower"])]fn compute_lending_summary(batch: &mut Batch<'_, Book>) -> Result<()> { /* batch.get / batch.set */ }
#[constrains("renewals")]async fn check_renewals(this: &RecordSet<Loan>, tx: &mut Transaction) -> Result<()> { /* Err(Error::validation(..)) */ }- A compute is a synchronous
fn(batch)over plain fields of its own model listed independsandreads. The host reads those fields as the invoking environment reads them (access rights, record rules and field groups apply), hands the values over as data and takes the assigned columns back. A compute asks the host for nothing (everyorm-hostrequest is refused), never runs elevated (compute_sudo = trueis refused at install; the default is forced to false) and may not name a field restricted to groups. It also runs on records that are not in the database yet. Stored and non-stored computes use the ORM’s own dependency tracking: a write to a dependency marks the field and it is recomputed on read or at flush. - A constraint is an
asyncmethod that runs once on the whole recordset, in the environment that wrote, after a write or a create touched a field of its list. It is not elevated and its bridge is read-only: it may read (and search) with that user’s rights, and any other request is refused. In asudoor System environment it may ask for nothing, so the write fails closed. Its error, whatever kind the guest used, reaches the caller as a validation error; the transaction is poisoned and nothing is committed. Batch::get/values/set/set_allandRecordSet::mappedhave the native signatures. A computed or constrained field of a package may beboolean,integer,float,char,textorhtml; dates and relational fields are read as the follow-up lists below say.- Not available, refused by name when the package is installed (
WasmReason::Unsupported), never skipped:asynccomputes,#[compute(override)], adependsorreadspath through a relation (line_ids.qty),#[onchange],inverse,related,precompute. A computed field must name a compute the addon declares on the same model, and every compute must fill a field (WasmReason::DescribeMismatch). - The first call of a compute after install also fills the stored field of rows that already exist.
Temporal fields
Section titled “Temporal fields”Date values cross typed get/mapped/set as days since 1970-01-01;
DateTime values cross as microseconds since midnight UTC. Null remains None.
Dates are calendar days and datetimes mean naive UTC: caller timezone never shifts them.
The native temporal types are reexported by the SDK prelude.
Lifecycle create/write overrides use JSON server text: dates use YYYY-MM-DD,
datetimes use YYYY-MM-DD HH:MM:SS (without microseconds). This seam has second
precision even though WIT scalar/column transfers preserve microseconds. RawVals
keeps incoming strings as Cell::Str; the host validates them against the target
field, rather than guessing that arbitrary strings are dates. Typed date cells
inserted into RawVals serialize with the same server-text precision.
Range fields are outside this support.
Today’s date and the clock
Section titled “Today’s date and the clock”this.context_today(tx)? is Odoo’s fields.Date.context_today(record): today’s date as a
Date, in the time zone of the call (the context tz; UTC when the context has none or an
unknown one, as in Odoo). The signature is the same in a component and natively, so one source
compiles for both:
#[method(wire)]async fn lend(this: &RecordSet<Book>, tx: &mut Transaction) -> Result<i32> { let loan_date = this.context_today(tx)?; // 2024-01-02 in Asia/Jakarta let due_date = Date::from_days(loan_date.days() + 14); Ok(due_date.days())}Natively the zone comes from the recordset’s own environment; in a component it comes from the
call context, which the host built from the same environment. Without a recordset,
Date::today() is today in UTC, Date::context_today("Asia/Jakarta") today in a named zone and
Date::context_today_at(zone, timestamp) the date of a given naive-UTC datetime in a zone; an
unknown zone name is a Validation error there.
The component reads the clock through the host’s wasi:clocks/wall-clock (what
SystemTime::now() uses in the Rust standard library), reported to the microsecond. It is the only
WASI import the host answers with real data; the monotonic clock, environment, randomness and the
rest still trap when called (ADR 0081 amendment 2026-10-28). A component that uses time zones
carries the bundled time-zone database (about 340 KB in the fixture, release build with fat LTO);
one that does not use them does not.
What does not work in a component yet
Section titled “What does not work in a component yet”| You write | Result in a component | Added by |
|---|---|---|
#[rpc(...)], #[data_callable], #[field_access], #[access_domain] | compile error saying it is not supported yet | follow-up |
compute-fields, validate-constraints or onchange exports | unsupported error saying dispatch is not supported yet (computes and constraints are called as methods of the component instead, see above) | follow-up |
Domain-typed search, range, JSON and binary fields in get/set | does not compile, or unsupported error naming the follow-up | follow-up |
Vals::commands (x2many commands), new_record, Records::create on untyped sets, Env::records(name) | does not compile (the call is not in the guest API) | follow-up |
HashMap / HashSet | traps at first use (wasi:random/insecure-seed is not provided); use BTreeMap / BTreeSet | not planned |
a model name in env().model::<M>() that the registry lacks, a model_ref! field that does not exist | env().model succeeds (empty set) and the first create/read names the model; a handle is refused at install | n/a |
async computes, #[compute(override)], relation paths in depends, #[onchange] | the package is refused at install, naming the contribution | follow-up |
| a native method whose argument or result type is not serialisable, overridden from a component | the registry build refuses it, naming the implementation and the first type that blocks it | serde derives on the plain-data types of the main apps, follow-up |
a sealed native method (#[method(sealed)]: credentials, access, schema hooks; any #[constrains] or #[onchange] method; the core list on the access models) overridden from a component | the registry build refuses it, naming where it is sealed | constraints: WASM.COMPUTE-REL; onchange: WASM.ONCHANGE; the rest not planned |
read_group, the web read methods and the other core methods without a wire record | the registry build refuses it: the implementation has no wire record | follow-up |
#[migration], SQL migration scripts (migrations-sql) | not available for WebAssembly; schema changes follow the fields you declare | follow-up |
Installing, upgrading and uninstalling a package at runtime
Section titled “Installing, upgrading and uninstalling a package at runtime”A WebAssembly addon is shipped as a .erpaddon package (the [wasm] section of manifest.toml and
wasm/<name>.wasm). The administrator’s program installs it into a database without changing other
databases. Embedded library callers can adopt the returned registry directly. The native membership-bound
server requires draining and restarting membership when package identity changes; see
Native membership and installed package identity.
// once, at start-up: the package runtime goes to the module system, the lifecycle wraps bothlet packages = WasmPackages::new(Arc::new(HostLoader::new(host, Limits::default())));let system = Arc::new(ModuleSystem::builder(pool, index).signal(signal).package_runtime(packages.clone()).build()?);let life = WasmLifecycle::new(system, packages);
// the administrator approves what the package asks for, then installs itlet package = ErpAddonPackage::from_bytes(&bytes)?.consent(&consent)?; // capabilities, client-code digestlet outcome = life.install(&env, package).await?; // switch to outcome.ormlife.upgrade(&env, newer_package).await?;life.uninstall(&env, &ModuleName::new("my_addon")?).await?;
// an authenticated administrator (a browser or API session) goes through the trusted authorizerlife.install_authorized(&authorizer, package).await?; // also upgrade_authorized, uninstall_authorizedWho may call: install, upgrade and uninstall are the operator (CLI) entry points and accept only the System
environment (uid 1) of the module system, as the native immediate operations do; any other caller is refused with
AccessDenied before the package is looked at. The *_authorized forms take the same InstallAuthorizer the
browser installation of native addons uses: it rechecks the session and the module-administration right inside the
operation transaction, under the lifecycle lock. The audit row names the actor: the administrator’s own uid and the
session id (actor_kind = 'session'), or uid 1 ('operator') on the operator path.
A package cannot take the name of a native addon: base, web, an installed addon and an addon of a development
folder are refused. One package may contribute at most 4096 methods, 256 models and 4096 fields
(WasmReason::TooLarge).
What is checked before anything is written: the package digest and consent (by type: consent() is the only way to
get the ConsentedPackage that install takes), that every dependency of the manifest is already installed (the
lifecycle never installs dependencies for you), that describe() names your addon and the same dependencies as the
manifest (a different name or dependency list fails), and that the addon uses only what this build can run:
In describe() | Now |
|---|---|
models and extensions with boolean, integer, float, char (size), text, html, date, datetime fields and the attributes string, help, required, readonly, copy, store, translate | read into the registry; the schema is synced in the same transaction |
methods (method, override) | joined into the override chains |
compute and compute_sudo on a field; scalar compute (sync, plain-field depends/reads) and constraint contributions | read; the compute graph and the constraint list of the ORM are given the computes and constraints of the package |
model kind = "regular", "abstract" or "transient"; many2one fields with a nonempty comodel and optional ondelete = "set null", "restrict" or "cascade" | read into the registry; see Wizard dialogs for the transient form flow |
on a transient model: transient_max_age_seconds and transient_max_count, plain decimal integers (0 disables a threshold) | read into the registry as the validated cleanup policy, the same as natively; declared only, no cleanup runs yet (Wizard dialogs) |
selection fields (selection = [("value", "Label"), ...]), default, index, digits = (p, s) on float, groups; keys, parent_store and parent_name on a model the package creates | read into the registry, see Field attributes, keys and a parent store |
selection_add, selection_method, default_fn, a named digits; keys, parent_store or parent_name on an extension; the raw SQL forms constraints, indexes, unique_indexes | refused by name (WasmReason::Unsupported) |
other relational field declarations, related; async or overriding compute, onchange contributions | refused by name (WasmReason::Unsupported), nothing is skipped |
manifest capabilities (network:outbound:, filesystem:temp:, migrations-sql) | refused (CapabilityUnavailable): this host cannot enforce them yet. The ORM access every addon has is bounded by the caller’s own rights |
Everything happens in the module system’s own operation transaction: the package row (ir_module_package), one audit
row (ir_module_wasm_audit: operation, versions, SHA-256, capabilities, acknowledged client-code digest, actor) and
the registry-change signal other nodes wake on. Any error rolls all of it back and the registry you were using stays
the only one. An operation that would change anything else (a dependent uninstalled with it, a dependency installed on
the way) is refused. uninstall refuses while other installed addons depend on the package, and removes its models’
data under the module system’s uninstall rules.
A restarted server, or a node whose registry generation moved because another node changed a package, calls
life.load(): it reads the installed packages from ir_module_package, checks each stored archive again (content
address, SHA256SUMS, capabilities and client-code digest against the row) and loads the module set.
Field attributes, keys and a parent store
Section titled “Field attributes, keys and a parent store”A package model uses the same attribute syntax as a native #[model]; the installer reads the attribute text
describe() carries (SPEC-WASM-030, SPEC-WASM-031, SPEC-WASM-032, SPEC-WASM-033):
#[model( name = "my_assets.asset", keys = [key(name = "_serial_uniq", fields = ["serial_no"], message = "The serial number must be unique.", nulls_distinct = true)])]pub struct Asset { #[field(char, index)] // `index`, `index = true`, `index = "trigram"` pub name: Option<Arc<str>>, #[field(char)] pub serial_no: Option<Arc<str>>, #[field(selection, selection = [("draft", "Draft"), ("done", "Done")], default = "draft")] pub state: Option<Arc<str>>, #[field(float, digits = (16, 2), default = 1.5)] pub amount: Decimal, #[field(char, groups = "base.group_system")] pub secret: Option<Arc<str>>,}
#[model(name = "my_assets.node", parent_store = true, parent_name = "parent_id")]pub struct Node { #[field(char)] pub name: Option<Arc<str>>, #[field(many2one, comodel = "my_assets.node")] pub parent_id: Option<RecId>, #[field(char, index)] // the path the ORM maintains pub parent_path: Option<Arc<str>>,}- Defaults are literals: a string, a number (negative too) or
true/false.falseon a field that is not boolean means “no value”, as in a model file.default_fnnames a Rust function and is refused. - Selection: a static list of string pairs.
selection_add(extending another addon’s list) andselection_methodare refused;selection_addfollows in a later slice. A list is bounded byMAX_SELECTION_ENTRIES; a longer one is refused, not cut. digitsis(precision, scale)on afloatonly; a named precision (digits = "price") is refused.indexwith a named kind ("trigram","brin","gin") follows the native rules for the field type.- Keys are the typed
key(name, fields, message, nulls_distinct)only, never SQL: the registry checks the fields. A duplicate create fails with the key’s message.nulls_distinct = trueis a plainUNIQUE(rows with an empty part do not conflict, Odoo’sunique(field)); without it two rows with empty parts conflict. A temporal key (without_overlaps) and the raw SQL formsconstraints,indexesandunique_indexesare refused: raw SQL is native only. Keys andparent_storebelong to models the package creates; on anextendentry they are refused, since a key on a native table could make native inserts fail. - Upgrading to a version that adds a key over rows that already break it fails, names the key
(
cannot add key '_serial_uniq' to 'my_assets.asset': existing records conflict) and rolls back. An upgrade that turnsparent_storeon for a model the installed version has without it is refused (WasmReason::State, naming the model): nothing fills the paths of existing rows. Declareparent_storefrom the first version of the model. - An
extendentry only adds fields. Redeclaring a field another addon introduced, with any attribute (string,sanitize,comodel, an index, …), is refused at install, upgrade and load, naming the model, the field and the addon that declared it first. Changing the type of such a field is refused when the registry is composed. - Value shapes are fixed.
selection,digits,default,keysandcompany_accessare read by a flat reader that accepts only the forms shown above (string literals, numbers,true/false,( ) [ ] , = -); any other expression, a call, an index, a method chain, a cast, however it is repeated, is refused naming the attribute. Each value has a byte cap.digitsneeds a precision of at least 1 and a scale not above it; a key may not name a field twice, and may not take a name the ORM generates (primary key, foreign key, not-null, field index, the parent path index, the id sequence). - Upgrading
parent_name(or the model the parent field points to) whileparent_storestays on is refused, naming the model. groupsrestricts a field to a group. A package may setgroupsonly on a field it introduces: when the registry is composed, a runtime declaration (package or model file) that setsgroupson a field an earlier addon declared is refused, naming the model, the field and the addon that declared it first. The group applies to reads the same way as for a native field; a compute of a package reads with the caller’s rights.
Extending a data-only addon’s model (model_ref!)
Section titled “Extending a data-only addon’s model (model_ref!)”A model declared in a data-only addon (models/*.toml) has no Rust type. Name it with erp_sdk::model_ref!, then
extend it and add methods as for any model; the fields of the model stay with its owner and the extension adds its own.
From examples/wasm/sample_library_wasm/src/lib.rs (tested by crates/erp-cli/tests/wasm_addon_poc.rs):
erp_sdk::addon!(name = "sample_library_wasm", depends = ["sample_library"]);
erp_sdk::model_ref!(pub Loan = "sample_library.loan"); // add `{ field: Type, .. }` for typed handles, see above
#[extend(Loan)]pub struct LoanRenewals { #[field(integer, string = "Renewals")] pub renewals: i32,}
#[methods(Loan)]impl LoanRenewals { #[method(wire)] async fn renew(this: &RecordSet<Loan>, tx: &mut Transaction, note: String) -> Result<i32> { let loan = this.ensure_one()?; let renewals = loan.get(tx, LoanRenewals::RENEWALS).await? + 1; loan.set(tx, LoanRenewals::RENEWALS, renewals).await?; Ok(renewals) }}A second package overrides it with super, from its own package, without editing the first
(examples/wasm/sample_library_wasm_policy): #[method(override, wire)] async fn renew(..., sup: Super) refuses with
Error::validation(..) or calls sup.call(tx, this, (note,)).
When one addon is both the leaf of its own package and the dependency of another package’s leaf, export the component behind a default feature and let the dependent turn it off, because a component exports once:
# sample_library_wasm/Cargo.toml # sample_library_wasm_policy/Cargo.toml[features] erp-addon-sample_library_wasm = { path = "..", default-features = false }default = ["component"]component = []#[cfg(feature = "component")]erp_sdk::export_component!();The sample also shows the inherit/override surface: computed lending_summary (not stored) and
popular (stored) on a book, a constraint limiting a loan’s renewals, a write override with super on a loan, a
create override on a book and an unlink override on a loan. Date and datetime fields support get/mapped/set. See
docs/design/m2b-poc.md and docs/design/m2b-k-override.md. Screens, menus and RPC of a package are in the next two
sections.
Data files in a package: views, actions, menus, access rows
Section titled “Data files in a package: views, actions, menus, access rows”A package ships screens the way a data-only addon does: list the files under data in manifest.toml, put them in
views/, data/ or security/, and erp addon package carries them (and SHA256SUMS covers them, so the archive is
refused if one changes). They load in the install transaction through the same data loader as native addons: a failure
rolls the whole install back, the records get external ids owned by the package, an upgrade reloads them, and
uninstall removes them with the module’s other data.
A native dependency upgrade leaves the package version, archive and lifecycle audit unchanged. Before committing, it validates the installed package views against the final native views. If an inherited XPath no longer applies, the native upgrade rolls back and reports the package view that failed. Repair the native view or upgrade the package to a compatible extension before retrying; a native upgrade does not reapply the package’s data files. Native-install and post-init-hook paths have not been validated by this task; this paragraph describes native upgrades only.
From examples/wasm/sample_library_wasm:
depends = ["sample_library"]data = ["views/sample_library_wasm_views.xml"]<erp> <!-- extend the form of another addon in place; nothing of sample_library is edited --> <record id="book_form_lend" model="ir.ui.view"> <field name="name">sample_library.book.form.lend</field> <field name="model">sample_library.book</field> <field name="inherit_id" ref="sample_library.book_form"/> <field name="arch" type="xml"> <xpath expr="//field[@name='available']" position="after"> <field name="times_lent"/> <field name="last_borrower"/> </xpath> </field> </record></erp>What a package’s data files may declare (anything else fails the install, naming the file, the line and the rule):
| Allowed | Notes |
|---|---|
ir.ui.view records, also inherited views of any view of a dependency | the view’s model must be a model the package declares or extends (#[model], #[extend], model_ref!). On a model it only extends: extension views only (inherit_id required, mode absent or extension), no priority. No type=qweb, no key |
ir.actions.act_window records | res_model must be a model the package declares or extends; binding_model_id only on an action for a model the package declares, as ref="<package>.model_..." |
<menuitem> and ir.ui.menu records | a menu may sit under another addon’s menu (parent) and point at another addon’s action |
access rows, in a CSV file named ir.access.csv (the platform’s access model, see addons/base/security/ir.access.csv) | columns only id, name, model_id/id, group_id/id, operation (crud, r, …), active (no .id, no domain); only for models the package declares itself (model_id/id is <package>.model_...) |
An addon that only extends (#[extend]) a model of another addon must add at least one field or method to it; an empty
extension is refused at install. erp addon install|upgrade prints extended_models, next to rpc_methods.
Rules that apply to every record:
- Ids are the package’s own. Every record id, menu item id and access-CSV
idis unqualified or qualified with the package’s own name; a record needs an id. A package cannot updatebase.*menus, another addon’s views or actions or access rows (they would not be restored on uninstall).inherit_id,parent,actionandref()may point anywhere. - A
<field>name is given once per record, andcontextanduidare not allowed on any element (<data>,<record>,<menuitem>). - Values are checked by field type. A one2many gets no value (no child records, no links). A many2many takes
ref()or a list of 3-element commands whose code is a bare integer literal:(4, ref('x'), 0)link,(5, 0, 0)clear,(6, 0, [ref('x')])set; lists and tuples are read alike, and(0, ...),(1, ...),(2, ...),(3, ...), dicts,+2,Command.*are refused. Any other field takes text, numbers,ref()andevalof literals,ref('...')and lists and tuples of them;search=lookups and file-valued fields are refused. The field must exist in the registry being installed.
Refused by name: .sql files, demo data, <function>, <delete>, <template>, <asset>, records of any other model
(for example res.users, ir.cron, record rules), and an access record written in XML. Data files live in views/,
data/ or security/ and are .xml or .csv.
A form view may carry a <header> with <button type="object"> (the rest of the header grammar is planned). The header must be the first child of <form>, so an inherited view adds it with
<xpath expr="//sheet" position="before">. A button’s name must be a method exposed on the form’s model (see the next
section): the form is refused when it is built otherwise. The sample adds a Lend button to the book form and a Renew
button to the loan form.
A wizard field that the opening action fills from its context (default_<field>, such as the Lend wizard’s
book_id) is declared readonly = true, as in Odoo: the form shows it but cannot change it, the web client does not
send read-only fields when it saves, and create takes the value from the context default. The sample does this since
version 1.3.2. Starting with version 1.3.3, the book form and list show both popular and
lending_summary.
Calling a package method from the web client
Section titled “Calling a package method from the web client”A method is callable from the web client and over call_kw/JSON-2 on a record only when you say so, as for a native
method (#[rpc], ADR 0038): add rpc to the method attribute.
#[method(wire, rpc)]async fn lend(this: &RecordSet<Book>, tx: &mut Transaction, borrower: Option<String>) -> Result<i32> { /* ... */ }POST /erp/json/2/sample_library.book/lend {"ids": [7], "borrower": "Reader"} -> 2rpc is carried in describe() ("rpc": true). Natively it is a no-op (#[rpc] is the native marker); the dual
source stays one source. rpc on an override or on a name that starts with _ is a compile error. Nothing is exposed by default: a method without the marker, an override, a name that
starts with _ and a method with an argument that is not a plain name are never callable from a client.
erp addon installanderp addon upgradeprintrpc_methods: themodel.methodnames the package opens to clients. Read it before you trust a package: the capability consent does not cover it.- Arguments are the method’s arguments after
thisandtx, by name.Option<T>ones are optional (absent isnull). A required one must be present and notnull(422 before the method runs), and an integer, boolean, number or string argument is checked against its Rust type. Other types are accepted as any JSON value and the method’s own deserialisation refuses a wrong shape (the guest reports it as an invalid argument, which is a 422). A button passes no arguments, so give the arguments it should be able to omit the typeOption<T>. - The call runs as the signed-in user: the method’s own reads and writes go through the ORM’s access rules and record rules, so a user without write rights on the model is refused (403, access error) and nothing is stored.
- Effect class is
write: the transaction is a writing one, read-only API keys are refused, and the gates of the RPC service (scopes, idempotency keys) apply. A component cannot declare a read-only method yet. - The call reaches the top of the override chain, so an override from another package (the policy package in the sample) applies to a button press as well.
Install a WebAssembly addon (operator)
Section titled “Install a WebAssembly addon (operator)”You need the server’s deployment file (the one erp server --config reads), the .erpaddon, and the addons its
dependencies come from already installed (for the sample: sample_library, installed from the Addons screen or
erp module install).
erp addon build sample_library_wasm --target wasm --addons-path addons,examples/wasm # developer, onceerp addon package sample_library_wasm --addons-path addons,examples/wasm -o sample_library_wasm.erpaddon
erp addon install sample_library_wasm.erpaddon -d erpforall --config /etc/erpforall/server.toml --approve noneerp addon upgrade sample_library_wasm-1.4.0.erpaddon -d erpforall --config /etc/erpforall/server.toml --approve noneerp addon uninstall sample_library_wasm -d erpforall --config /etc/erpforall/server.toml--approveis required (an empty element or a capitalisedNONEis refused). List exactly the capabilities the package requests (comma-separated), ornone. Approving more or less than the package asks for is refused. (This host cannot enforce any capability yet, so a package that requests one is refused at install.)- A package with client code (
static/dist/) needs--ack-client-digest <sha256>of the code you reviewed (printed byerp addon package); a wrong digest, or a digest for a package without client code, is refused. -dmust be the database the configuration names.- On success one JSON line is printed:
operation,addon,version,archive_sha256,database,installed,upgraded,uninstalled,rpc_methods,runtime_grants. Exit codes: 1 refused (nothing written), 3 another module operation is running (retry), 4 rolled back, 5 committed but the post-commit phase did not finish, 2 system error. - Package operations bump the registry generation. A native membership-bound server refuses publication if loading changes its immutable catalogue; drain and restart membership after install, upgrade or removal. A fresh server verifies the stored packages before registration. Embedded library callers manage their own registry replacement. Nothing is written to a server’s addon directory.
- Keep the Rust source of an addon you install as a package out of the server’s
addons_path(the samples live inexamples/wasm, notaddons/). If it is there anyway, the folder is refused as a native addon (its manifest has a[wasm]section) and the installed package wins. - If the output ends with
the operation COMMITTED, but publishing the runtime grants failed, the package is installed. Fix the cause (usually the runtime role in the configuration) and runerp db publish-grants --config <file>before restarting native membership for the changed catalogue. Do not repeat the install: it would say the addon is already installed. - A server whose registry rebuild fails (a stored package that does not verify) keeps answering with maintenance and tries again after 1 s, 2 s, 4 s … up to 60 s between attempts, not on every request; the error is in the server log.
- The command acts as the System principal; the audit table
ir_module_wasm_auditrecords every operation, the package SHA-256 and the approved capabilities. Both tables are core tables created and owned by the schema owner, not by the runtime role. The audit table is insert-only (a trigger refuses row changes, removals and truncation even for the owner), the release grants give the runtime role nothing on it and onlySELECTonir_module_package(revoke_wasm_lifecycle_runtime_writes, called bygrant_runtime).load()loads a stored package only when an install or upgrade audit row records the same archive with the same capabilities and client-code digest; a row written outside the lifecycle is refused. After the first package operation on a database, run the runtime grants publication so the runtime role can read the package store.
Native membership and installed package identity
Section titled “Native membership and installed package identity”The native membership-bound server includes installed packages in its startup catalogue even
when no corresponding source folder is shipped. It verifies archives and lifecycle consent before
registration, then validates the loaded catalogue again before publishing authentication, RPC
and assets (login-admission ADR 0126, docs/adr/0126-login-rollout-admission.md). Earlier native
hot-update demonstrations in wasm_addon_poc.rs predate this membership boundary and remain
historical, optional demonstrations; this repair does not certify them. Library lifecycle examples
show registry loading, not native serving admission. For the native server, an install, upgrade or removal that
changes the catalogue requires draining and restarting membership; keeping the same addon name
does not permit different archive bytes under the old identity. Registry refresh with an unchanged
catalogue remains supported. See the operator procedure.
The required wasm-startup-catalogue CI stage builds the actual sample WASM packages and runs
native readiness, login and package-RPC checks with their sources outside the configured addon
paths. The test is fixture-dependent and runs explicitly through
scripts/wasm-poc.sh --startup-catalogue; an ordinary nextest run alone does not certify it.