apply<R> method
Submits an ApplyCommand to trigger a state change or an action within this cell.
apply is the primary architectural gateway for every mutation in the framework. Instead of calling functions directly, you submit a "Nervous Signal" (a command) that the cell must vet, execute, and record in its history.
In the framework's biological metaphor, this represents Signal Transmission. It sends a nervous impulse through the cell's governance layer to request a mutation in its underlying DNA (state).
When to use
- State Mutations: Use this whenever you need to update a cell's value in a way that is traceable and safe.
- Governed Actions: Use this for logic that requires "Integrity Gates" (safety rules) to prevent invalid data transitions.
- Grouped Changes: Use this when multiple actions must happen together as a single "all-or-nothing" transaction.
How it works
- Permission Check: The cell verifies if its current state allows mutations by checking the modifiable manifest.
- Integrity Gate: The cell's safety rules (TestCell.action) inspect the command and its data to ensure they are valid.
- Execution: If authorized, the function is run. If a transaction scope
(
tx) is provided, the change is "staged" in the ledger and waits for the transaction to finish. - Outcome: The framework returns an ApplyOutcome, which acts as the official Forensic Receipt for the action.
Parameters
- command: The ApplyCommand record. This contains the function you want to run, the data (arguments) it needs, and the optional "undo" logic.
- tx: An optional ApplyTransactionScope. Provide this if you want the command to be part of a larger transaction that succeeds or fails as a group.
Non‑obvious behavior
- Causal Binding: Every receipt contains a unique ID and timestamp. This creates a permanent forensic trail, allowing you to trace any state change back to the exact impulse that triggered it.
- Atomic Rollbacks: If a command includes "compensation" logic, the framework can use it to perform a Genetic Undo, restoring the previous state if a complex transaction fails later.
- Authority Hierarchy: Arguments passed directly to apply act as a
local override, taking precedence over inherited defaults.
Technical Details
- Execution Context: Returns a FutureOr. If the mutation is simple, it returns the result immediately. If the mutation is asynchronous, it returns a Future.
- Memory Efficiency: The command and receipt use "Flyweight" records to minimize memory overhead, even when tracking thousands of signals.
Example: Submitting a Governed Mutation
// 1. Define the mutation logic (the "impulse")
final updateProfile = (String name, {bool active = true}) {
return User(name: name, active: active);
};
// 2. Assemble the signal using the fluent builder (DSL)
// This creates the "Nervous Signal" with a built-in "Genetic Undo"
final outcome = await userCell.command(updateProfile)
.args(['Simon'])
.named({#active: true})
.undo(updateProfile, args: ['Previous Name'], named: {#active: false})
.run();
// 3. Handle the Forensic Receipt using modern Dart pattern matching
switch (outcome) {
case ApplyAccepted(result: final user, receipt: final r):
print('Mutation successful: ${user.name} (ID: ${r.id})');
case ApplyRejected(reason: final error):
print('Integrity Gate blocked mutation: $error');
case ApplyStaged(receipt: final r):
print('Signal queued in forensic ledger: ${r.id}');
}
See also:
- HowTo: See
HowTo-Cell.apply.mdfor a comprehensive guide on getting started with the Cell architecture and reactive patterns. - ApplyCommand — The structural blueprint of a signal impulse.
- ApplyOutcome — The sealed hierarchy of transition results.
Implementation
@override
FutureOr<ApplyOutcome<R>> apply<R>(
ApplyCommand command, {
ApplyTransactionScope? tx,
}) {
final vetted = modifiable.contains(command.function);
if (tx != null) {
final sequence = tx.enqueueCommand(this, command);
return ApplyStaged(ApplyLedger.receipt(
cell: this,
command: command,
txSequence: sequence,
vetted: vetted,
));
}
final receipt =
ApplyLedger.receipt(cell: this, command: command, vetted: vetted);
// Await Future-returning command functions: the docs promise that a
// Future-returning function makes `apply` async, and an asynchronous
// failure must surface here — not as an unhandled zone error. Sync
// functions keep their synchronous ApplyOutcome return. A function
// vetoing itself (ApplyVeto) is reported as ApplyRejected, matching
// the transaction layer.
FutureOr<ApplyOutcome<R>> accept(Object? rawResult) {
if (rawResult is Future<R>) {
return rawResult.then((r) {
if (identical(r, ApplyVeto.instance)) {
return ApplyRejected<R>(receipt);
}
return _acceptExecuted<R>(r, receipt);
});
}
if (identical(rawResult, ApplyVeto.instance)) {
return ApplyRejected<R>(receipt);
}
return _acceptExecuted<R>(rawResult as R, receipt);
}
Object? run() => Function.apply(
command.function,
command.arguments.positionalArguments,
command.arguments.namedArguments,
);
// EVERY apply is gated — including functions outside the capability
// manifest. The `vetted` flag only records manifest membership on the
// receipt; it must never decide whether the integrity gate runs.
// Consult the overridable `validate` getter (not `_nucleus.testRule`
// directly) so subclasses like `UnmodifiableValueCell` can layer
// additional read-only enforcement atop the principal's rule without
// having to mutate the shared nucleus.
FutureOr<bool> validation;
try {
validation = validate.action(command.function,
host: this, arguments: command.arguments, command: command);
} on Exception {
// A throwing integrity gate fails closed: reject the action.
return ApplyRejected<R>(receipt);
}
if (validation is Future<bool>) {
return validation.then((passed) {
if (!passed) return ApplyRejected<R>(receipt);
return accept(run());
});
}
if (!validation) return ApplyRejected<R>(receipt);
return accept(run());
}