set method
Writes data to local cache. Non-local collections sync to server.
Implementation
Future<bool> set(Map<String, dynamic> data) async {
// If Collection has index config, delegate to Collection.set()
if (_onSet != null) {
await _onSet(data);
return true;
}
_onMutate?.call();
Uint8List bytes = _serializer.serialize(data);
final crypto = _crypto;
if (crypto != null && _secretKey != null) {
bytes = await crypto.encrypt(bytes, _secretKey);
// Mark as encrypted with magic byte 0xAE
final marked = Uint8List(bytes.length + 1);
marked[0] = 0xAE;
marked.setRange(1, marked.length, bytes);
bytes = marked;
}
final smart = _smartCache;
// Local collections: add taint byte + write to cache only
if (_local) {
// Taint: 0xAA at the start of payload — if it reaches the server, it's rejected
final tainted = Uint8List(bytes.length + 1);
tainted[0] = 0xAA;
tainted.setRange(1, tainted.length, bytes);
bytes = tainted;
if (smart != null) {
await smart.put(_blockId, bytes, isLocal: _local);
} else if (_cache != null) {
await _cache.put(_blockId, bytes, isLocal: _local);
}
return true;
}
if (smart != null) { await smart.put(_blockId, bytes, isLocal: _local); }
if (!_ws.isConnected && smart != null) {
await smart.enqueuePut(_blockId, bytes);
return true;
}
try {
final created = await _ws.put(_blockId, bytes);
final cache = _effectiveCache;
if (cache != null) { await cache.put(_blockId, bytes); }
_ws.emitLocalSync(SyncEvent(action: 'put', blockId: _blockId));
return created;
} catch (e) {
if (e is WsDeniedException) {
if (smart != null) { await smart.evict(_blockId); }
rethrow;
}
if (smart != null) {
await smart.enqueuePut(_blockId, bytes);
return true;
}
rethrow;
}
}