Writers
A writer
method gets exclusive, atomic access to state
in order to
update it. Any updates a writer
makes to the passed in state
argument are
persisted after the method returns, but before returning to the caller.
If the method fails (or it is part of a transaction
which aborts), its changes
to state
are not persisted.
A writer
method gets passed a context of type WriterContext
. A
WriterContext
can only be used to make calls to reader
methods (that is not a typo, writer
's can only call other
reader
's).
To replace an entire state
you'll need to do
state.CopyFrom(...)
in Python and state.copyFrom(...)
in Node.js.
Here's an example of a writer
method called Deposit
on our
Account
state that increments the account's current balance by some
amount in the request:
- Python
- TypeScript
async def Deposit(
self,
context: WriterContext,
state: Account.State,
request: DepositRequest,
) -> DepositResponse:
state.balance += request.amount
return DepositResponse(updated_balance=state.balance)
async deposit(
context: WriterContext,
state: Account.State,
request: DepositRequest
): Promise<PartialMessage<DepositResponse>> {
state.balance += request.amount;
return { updatedBalance: state.balance };
}
In addition to returning a response and updating state, a writer
can also schedule async tasks, which are atomically started (or enqueued) if and only if the writer
completes successfully.