write method
Atomically installs draft under the rules of MemoryCas.decide
and returns the committed envelope (C2).
expected is the version the writer read: null means "the row
must be absent" (a create); otherwise the store compares revision
and generation. The store assigns the next revision and the
commit instant.
Throws: MemoryConflict when the decide step refuses the write (the stored row rides on the exception when available); MemoryCorrupt on a malformed existing row; MemoryIoException on backend IO failure.
Implementation
@override
Future<MemoryEnvelope> write(MemoryDraft draft, {MemoryVersion? expected}) {
checkId(draft.id);
return _lifecycle.run(() => _serializer.run(draft.id, () async {
await _ensureDirectory();
await _checkCaseCollision(draft.id);
final file = _fileFor(draft.id);
MemoryEnvelope? existing;
if (await file.exists()) {
existing = await _readEnvelopeFile(file);
if (existing != null && existing.id != draft.id) {
throw MemoryCorrupt('envelope id "${existing.id}" does not '
'match file "${draft.id}"');
}
if (existing != null && _isExpired(existing)) {
existing = null; // expired is equivalent to absent
}
}
final now = _clock.now();
final decision = MemoryCas.decide(
stored: existing,
draft: draft,
expected: expected,
updatedAt: now,
);
switch (decision) {
case MemoryCasCommit(:final nextRevision):
final generation =
draft.generation ?? MemoryEnvelope.mintGeneration();
final committed = MemoryEnvelope(
id: draft.id,
revision: nextRevision,
generation: generation,
updatedAt: now,
expiresAt: draft.expiresAt,
codec: draft.codec,
codecVersion: draft.codecVersion,
payload: draft.payload,
sourceCellId: draft.sourceCellId,
meta: draft.meta,
);
await _writeAtomically(file, committed);
_nameIndex.add('${draft.id}.json');
return committed;
case MemoryCasAlreadyApplied(:final stored):
return stored;
case MemoryCasConflict(:final stored):
throw MemoryConflict(expected: expected, stored: stored);
}
}));
}