2026-05-07 00:42:23 -03:00
|
|
|
part of 'recorder.dart';
|
|
|
|
|
|
|
|
|
|
/// Adds merge-specific behavior to [CrdtMutationRecorder].
|
|
|
|
|
extension CrdtMergeRecorderExtension on CrdtMutationRecorder {
|
|
|
|
|
/// Locks the current user row so merges can serialize with other work.
|
|
|
|
|
Future<void> lockCurrentUser(Transaction transaction) async {
|
2026-08-07 13:01:29 -03:00
|
|
|
final user = _context.effectiveScopeFor(transaction);
|
2026-05-07 00:42:23 -03:00
|
|
|
// Use a row lock without fetching the record since the merge path only
|
|
|
|
|
// needs serialization against concurrent work for the same user.
|
2026-06-18 01:05:24 -03:00
|
|
|
await CrdtScope.db.lockRows(
|
2026-05-07 00:42:23 -03:00
|
|
|
_session,
|
|
|
|
|
where: (t) => t.id.equals(user.id),
|
|
|
|
|
transaction: transaction,
|
|
|
|
|
lockMode: LockMode.forUpdate,
|
|
|
|
|
lockBehavior: LockBehavior.wait,
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Merges remote CRDT changes into the current database.
|
|
|
|
|
Future<void> mergeChanges(
|
|
|
|
|
CrdtMergeSet mergeSet,
|
|
|
|
|
Transaction transaction,
|
|
|
|
|
) async {
|
|
|
|
|
if (mergeSet.isEmpty) return;
|
|
|
|
|
|
|
|
|
|
final operations = mergeSet.causallyOrderedChanges;
|
2026-08-07 13:01:29 -03:00
|
|
|
final shouldProjectForeignKeys = _foreignKeyProjector
|
|
|
|
|
.mergeOperationsMayAffectForeignKeys(operations);
|
|
|
|
|
final currentUser = _context.effectiveScopeFor(transaction);
|
2026-05-07 00:42:23 -03:00
|
|
|
final remoteNodes = await _findOrCreateNodesForMerge(
|
|
|
|
|
currentUser.id!,
|
|
|
|
|
{for (final change in operations) change.uuidNodeId},
|
|
|
|
|
transaction,
|
|
|
|
|
);
|
2026-07-03 01:25:15 -03:00
|
|
|
final nodesByUuid = remoteNodes.nodesByUuid;
|
2026-06-06 00:55:10 -03:00
|
|
|
final context = await _loadMergeContext(mergeSet, transaction);
|
2026-05-07 00:42:23 -03:00
|
|
|
|
|
|
|
|
for (final operation in operations) {
|
2026-08-07 13:01:29 -03:00
|
|
|
if (!_context.isCrdtTrackedTableName(operation.tableName)) {
|
2026-05-07 00:42:23 -03:00
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
switch (operation) {
|
|
|
|
|
case final CrdtMergeInsert insert:
|
|
|
|
|
await _applyMergeInsert(
|
|
|
|
|
insert,
|
2026-07-03 01:25:15 -03:00
|
|
|
nodesByUuid,
|
2026-06-06 00:55:10 -03:00
|
|
|
context,
|
2026-05-07 00:42:23 -03:00
|
|
|
transaction,
|
|
|
|
|
);
|
|
|
|
|
case final CrdtMergeUpdate update:
|
|
|
|
|
await _applyMergeUpdate(
|
|
|
|
|
update,
|
2026-07-03 01:25:15 -03:00
|
|
|
nodesByUuid,
|
2026-06-06 00:55:10 -03:00
|
|
|
context,
|
2026-05-07 00:42:23 -03:00
|
|
|
transaction,
|
|
|
|
|
);
|
|
|
|
|
case final CrdtMergeDelete delete:
|
|
|
|
|
await _applyMergeDelete(
|
|
|
|
|
delete,
|
2026-07-03 01:25:15 -03:00
|
|
|
nodesByUuid,
|
2026-06-06 00:55:10 -03:00
|
|
|
context,
|
2026-05-07 00:42:23 -03:00
|
|
|
transaction,
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-10 17:31:05 -03:00
|
|
|
if (shouldProjectForeignKeys) {
|
2026-08-07 13:01:29 -03:00
|
|
|
await _foreignKeyProjector.project(transaction);
|
2026-06-10 17:31:05 -03:00
|
|
|
}
|
2026-05-29 01:54:23 -03:00
|
|
|
await _updateHlcFromIncomingOperations(
|
|
|
|
|
operations,
|
|
|
|
|
remoteNodes,
|
|
|
|
|
transaction,
|
|
|
|
|
);
|
2026-05-07 00:42:23 -03:00
|
|
|
}
|
|
|
|
|
|
2026-05-29 01:54:23 -03:00
|
|
|
Future<void> _updateHlcFromIncomingOperations(
|
2026-05-07 00:42:23 -03:00
|
|
|
List<CrdtMergeChange> operations,
|
2026-08-07 13:01:29 -03:00
|
|
|
MergeNodes remoteNodes,
|
2026-05-07 00:42:23 -03:00
|
|
|
Transaction transaction,
|
2026-05-29 01:54:23 -03:00
|
|
|
) async {
|
2026-05-07 00:42:23 -03:00
|
|
|
final maxIncomingHlc = operations.fold<Hlc?>(
|
|
|
|
|
null,
|
2026-05-29 01:54:23 -03:00
|
|
|
(current, change) => change.hlc.maxBetween(current),
|
2026-05-07 00:42:23 -03:00
|
|
|
);
|
2026-07-03 01:25:15 -03:00
|
|
|
final scopeNodesToUpdate = <CrdtScopeNode>[];
|
2026-05-29 01:54:23 -03:00
|
|
|
|
2026-05-07 00:42:23 -03:00
|
|
|
if (maxIncomingHlc != null) {
|
2026-08-07 13:01:29 -03:00
|
|
|
final hlcManager = _context.hlcManagerFor(transaction);
|
2026-05-07 00:42:23 -03:00
|
|
|
if (maxIncomingHlc.nodeId == hlcManager.uuidNodeId) {
|
|
|
|
|
if (maxIncomingHlc > hlcManager.lastHlc) {
|
|
|
|
|
hlcManager.lastHlc = maxIncomingHlc;
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
hlcManager.merge(maxIncomingHlc);
|
|
|
|
|
}
|
2026-05-29 01:54:23 -03:00
|
|
|
|
2026-08-07 13:01:29 -03:00
|
|
|
await _context.persistCurrentNodeHlc(hlcManager, transaction);
|
2026-05-29 01:54:23 -03:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
final maxIncomingHlcByNode = <UuidValue, Hlc>{};
|
|
|
|
|
for (final operation in operations) {
|
|
|
|
|
maxIncomingHlcByNode[operation.uuidNodeId] = operation.hlc.maxBetween(
|
|
|
|
|
maxIncomingHlcByNode[operation.uuidNodeId],
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for (final MapEntry(key: nodeId, value: incomingHlc)
|
|
|
|
|
in maxIncomingHlcByNode.entries) {
|
2026-07-03 01:25:15 -03:00
|
|
|
final remoteNode = remoteNodes.scopeNodesByUuid[nodeId];
|
2026-05-29 01:54:23 -03:00
|
|
|
if (remoteNode == null) continue;
|
2026-07-03 01:25:15 -03:00
|
|
|
final updatedScopeNode = remoteNode.copyWith(
|
2026-05-29 01:54:23 -03:00
|
|
|
lastReceivedHlc: incomingHlc.maxBetween(remoteNode.lastReceivedHlc),
|
|
|
|
|
);
|
2026-07-03 01:25:15 -03:00
|
|
|
if (updatedScopeNode.lastReceivedHlc == remoteNode.lastReceivedHlc) {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
2026-05-29 01:54:23 -03:00
|
|
|
|
2026-07-03 01:25:15 -03:00
|
|
|
scopeNodesToUpdate.add(updatedScopeNode);
|
|
|
|
|
remoteNodes.scopeNodesByUuid[nodeId] = updatedScopeNode;
|
2026-05-29 01:54:23 -03:00
|
|
|
}
|
|
|
|
|
|
2026-07-03 01:25:15 -03:00
|
|
|
if (scopeNodesToUpdate.isNotEmpty) {
|
|
|
|
|
await CrdtScopeNode.db.update(
|
2026-05-29 01:54:23 -03:00
|
|
|
_session,
|
2026-07-03 01:25:15 -03:00
|
|
|
scopeNodesToUpdate,
|
2026-05-29 01:54:23 -03:00
|
|
|
columns: (t) => [t.lastReceivedHlc],
|
|
|
|
|
transaction: transaction,
|
|
|
|
|
);
|
2026-05-07 00:42:23 -03:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-07 13:01:29 -03:00
|
|
|
Future<MergeNodes> _findOrCreateNodesForMerge(
|
2026-05-07 00:42:23 -03:00
|
|
|
int userId,
|
|
|
|
|
Set<UuidValue> nodeIds,
|
|
|
|
|
Transaction transaction,
|
|
|
|
|
) async {
|
2026-07-03 01:25:15 -03:00
|
|
|
if (nodeIds.isEmpty) {
|
|
|
|
|
return (
|
|
|
|
|
nodesByUuid: const <UuidValue, CrdtNode>{},
|
|
|
|
|
scopeNodesByUuid: const <UuidValue, CrdtScopeNode>{},
|
2026-05-07 00:42:23 -03:00
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-03 01:25:15 -03:00
|
|
|
final nodesByUuid = {
|
|
|
|
|
for (final uuidNodeId in nodeIds)
|
2026-08-07 13:01:29 -03:00
|
|
|
uuidNodeId: await _context.findOrCreateNode(uuidNodeId, transaction),
|
2026-05-07 00:42:23 -03:00
|
|
|
};
|
2026-07-03 01:25:15 -03:00
|
|
|
|
|
|
|
|
final scopeNodesByUuid = {
|
|
|
|
|
for (final entry in nodesByUuid.entries)
|
2026-08-07 13:01:29 -03:00
|
|
|
entry.key: await _context.findOrCreateScopeNode(
|
2026-07-03 01:25:15 -03:00
|
|
|
userId,
|
|
|
|
|
entry.value.id!,
|
|
|
|
|
transaction,
|
|
|
|
|
),
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
return (
|
|
|
|
|
nodesByUuid: nodesByUuid,
|
|
|
|
|
scopeNodesByUuid: scopeNodesByUuid,
|
|
|
|
|
);
|
2026-05-07 00:42:23 -03:00
|
|
|
}
|
|
|
|
|
|
2026-08-07 13:01:29 -03:00
|
|
|
Future<MergeContext> _loadMergeContext(
|
2026-05-07 00:42:23 -03:00
|
|
|
CrdtMergeSet mergeSet,
|
|
|
|
|
Transaction transaction,
|
|
|
|
|
) async {
|
|
|
|
|
final (:rowIdsByTable, :columnNamesByTable) = mergeSet.collectMetadataLookup(
|
2026-08-07 13:01:29 -03:00
|
|
|
columnNamesByTableName: _context.syncedTableColumnNamesForMerge,
|
2026-05-07 00:42:23 -03:00
|
|
|
);
|
|
|
|
|
|
2026-08-07 13:01:29 -03:00
|
|
|
final rows = <MergeRowKey, CrdtDataRow>{};
|
|
|
|
|
final fields = <MergeFieldKey, CrdtDataField>{};
|
2026-06-06 00:55:10 -03:00
|
|
|
final incomingFieldHlcs = {
|
|
|
|
|
for (final update in mergeSet.whereType<CrdtMergeUpdate>())
|
|
|
|
|
(update.tableName, update.uuidRowId, update.columnName): update.hlc,
|
|
|
|
|
};
|
2026-08-07 13:01:29 -03:00
|
|
|
final tombstones = <MergeRowKey, CrdtDataDeleted>{};
|
2026-06-18 01:05:24 -03:00
|
|
|
// Owning scope per row, snapshotted once so the per-operation ownership
|
|
|
|
|
// checks never re-read the same immutable `scopeId`. Only rows that
|
|
|
|
|
// already have a tracker are pre-read here — those are exactly the rows
|
|
|
|
|
// whose ownership the update/delete/existing-insert paths verify. New
|
|
|
|
|
// rows go through the insert path, which proves ownership at the physical
|
|
|
|
|
// write and refreshes this entry afterwards.
|
2026-08-07 13:01:29 -03:00
|
|
|
final domainOwners = <MergeRowKey, DomainRowOwner>{};
|
2026-05-07 00:42:23 -03:00
|
|
|
|
|
|
|
|
for (final MapEntry(key: tableName, value: rowIds) in rowIdsByTable.entries) {
|
2026-08-07 13:01:29 -03:00
|
|
|
final loadedRows = await _context.findCrdtRows(
|
2026-05-07 00:42:23 -03:00
|
|
|
tableName,
|
|
|
|
|
rowIds,
|
|
|
|
|
transaction,
|
|
|
|
|
include: CrdtDataRow.include(
|
|
|
|
|
node: CrdtNode.include(),
|
|
|
|
|
deleted: CrdtDataDeleted.include(node: CrdtNode.include()),
|
|
|
|
|
),
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
for (final row in loadedRows) {
|
|
|
|
|
rows[(tableName, row.uuidRowId)] = row;
|
|
|
|
|
if (row.deleted != null) {
|
|
|
|
|
tombstones[(tableName, row.uuidRowId)] = row.deleted!;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-18 01:05:24 -03:00
|
|
|
final trackedRowIds = loadedRows.map((row) => row.uuidRowId).toSet();
|
|
|
|
|
if (trackedRowIds.isNotEmpty) {
|
2026-08-07 13:01:29 -03:00
|
|
|
final ownerValues = await _context.readDomainColumnValues(
|
2026-06-18 01:05:24 -03:00
|
|
|
tableName,
|
|
|
|
|
trackedRowIds,
|
|
|
|
|
['scopeId'],
|
|
|
|
|
transaction,
|
|
|
|
|
);
|
|
|
|
|
for (final rowId in trackedRowIds) {
|
|
|
|
|
final values = ownerValues[rowId];
|
|
|
|
|
domainOwners[(tableName, rowId)] = values == null
|
|
|
|
|
? (exists: false, scopeId: null)
|
|
|
|
|
: (exists: true, scopeId: values['scopeId'] as int?);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-07 00:42:23 -03:00
|
|
|
final columnNames = columnNamesByTable[tableName];
|
|
|
|
|
if (columnNames == null || columnNames.isEmpty || loadedRows.isEmpty) continue;
|
|
|
|
|
|
|
|
|
|
final rowPks = loadedRows.map((row) => row.id).whereType<int>().toSet();
|
|
|
|
|
if (rowPks.length != loadedRows.length) {
|
|
|
|
|
throw StateError(
|
|
|
|
|
'Some merge metadata rows for table $tableName are missing '
|
|
|
|
|
'persisted identifiers.',
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-07 13:01:29 -03:00
|
|
|
final columnIdsByName = _context.schemaColumnIds(tableName, columnNames);
|
2026-06-10 17:31:05 -03:00
|
|
|
if (columnIdsByName.isEmpty) continue;
|
2026-05-07 00:42:23 -03:00
|
|
|
|
|
|
|
|
final loadedFields = await CrdtDataField.db.find(
|
|
|
|
|
_session,
|
2026-06-10 17:31:05 -03:00
|
|
|
where: (t) =>
|
|
|
|
|
t.rowId.inSet(rowPks) & t.columnId.inSet(columnIdsByName.values.toSet()),
|
2026-05-07 00:42:23 -03:00
|
|
|
include: CrdtDataField.include(
|
|
|
|
|
column: CrdtSchemaColumn.include(),
|
|
|
|
|
node: CrdtNode.include(),
|
|
|
|
|
),
|
|
|
|
|
transaction: transaction,
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
for (final field in loadedFields) {
|
|
|
|
|
final row = loadedRows.firstWhere((loadedRow) => loadedRow.id == field.rowId);
|
|
|
|
|
fields[(tableName, row.uuidRowId, field.column!.name)] = field;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return (
|
|
|
|
|
rows: rows,
|
|
|
|
|
fields: fields,
|
2026-06-06 00:55:10 -03:00
|
|
|
incomingFieldHlcs: incomingFieldHlcs,
|
2026-05-07 00:42:23 -03:00
|
|
|
tombstones: tombstones,
|
2026-06-18 01:05:24 -03:00
|
|
|
domainOwners: domainOwners,
|
2026-05-07 00:42:23 -03:00
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Future<void> _applyMergeInsert(
|
|
|
|
|
CrdtMergeInsert insert,
|
|
|
|
|
Map<UuidValue, CrdtNode> remoteNodes,
|
2026-08-07 13:01:29 -03:00
|
|
|
MergeContext context,
|
2026-05-07 00:42:23 -03:00
|
|
|
Transaction transaction,
|
|
|
|
|
) async {
|
|
|
|
|
final rowKey = (insert.tableName, insert.uuidRowId);
|
|
|
|
|
final incomingHlc = insert.hlc;
|
|
|
|
|
final remoteNode = _requireRemoteNode(remoteNodes, insert.uuidNodeId);
|
|
|
|
|
|
2026-06-06 00:55:10 -03:00
|
|
|
final currentRow = context.rows[rowKey];
|
2026-05-07 00:42:23 -03:00
|
|
|
if (currentRow != null && incomingHlc <= currentRow.hlc) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
final data = _sanitizeMergeRowData(insert.tableName, insert.databaseColumns);
|
|
|
|
|
|
|
|
|
|
if (currentRow == null) {
|
2026-08-07 13:01:29 -03:00
|
|
|
final mergingScope = _context.effectiveScopeFor(transaction);
|
2026-06-18 01:05:24 -03:00
|
|
|
final mergingScopeId = mergingScope.id!;
|
|
|
|
|
try {
|
|
|
|
|
// Insert-first inside a savepoint: the domain primary key resolves
|
|
|
|
|
// creation races atomically, and `_applyMergeInsertForMissingRow`
|
|
|
|
|
// raises `_ForeignScopeRowCollision` when the row turns out to be owned
|
|
|
|
|
// by another scope. Rolling the savepoint back then leaves no CRDT
|
|
|
|
|
// metadata, released unique values, or foreign key attempts behind.
|
|
|
|
|
context.rows[rowKey] = await DatabaseUtil.runInTransactionOrSavepoint(
|
|
|
|
|
_db,
|
|
|
|
|
transaction,
|
|
|
|
|
(savepoint) async {
|
2026-08-07 13:01:29 -03:00
|
|
|
final resolvedInsert = await _uniqueResolver.resolveForIncomingInsert(
|
|
|
|
|
insert,
|
|
|
|
|
data,
|
|
|
|
|
context,
|
|
|
|
|
savepoint,
|
|
|
|
|
);
|
2026-06-18 01:05:24 -03:00
|
|
|
|
2026-08-07 13:01:29 -03:00
|
|
|
final safeInsert = await _foreignKeyProjector.safeIncomingData(
|
2026-06-18 01:05:24 -03:00
|
|
|
insert.tableName,
|
|
|
|
|
insert.uuidRowId,
|
|
|
|
|
resolvedInsert.data,
|
|
|
|
|
savepoint,
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
final insertedRow = await _applyMergeInsertForMissingRow(
|
|
|
|
|
insert,
|
|
|
|
|
remoteNode,
|
|
|
|
|
incomingHlc,
|
|
|
|
|
safeInsert.data,
|
|
|
|
|
savepoint,
|
|
|
|
|
);
|
2026-08-07 13:01:29 -03:00
|
|
|
await _foreignKeyProjector.recordInsertAttempts(
|
2026-06-18 01:05:24 -03:00
|
|
|
insert.tableName,
|
|
|
|
|
{insert.uuidRowId},
|
|
|
|
|
savepoint,
|
|
|
|
|
safeInsert.attempts,
|
|
|
|
|
);
|
|
|
|
|
return insertedRow;
|
|
|
|
|
},
|
|
|
|
|
);
|
|
|
|
|
// The row is now owned by the merging scope (freshly inserted, or a
|
|
|
|
|
// same-scope recovery), so same-merge field updates resolve ownership
|
|
|
|
|
// from the cache instead of re-reading the domain row.
|
|
|
|
|
context.domainOwners[rowKey] = (exists: true, scopeId: mergingScopeId);
|
|
|
|
|
} on _ForeignScopeRowCollision catch (collision) {
|
|
|
|
|
await _throwOwnershipCollision(
|
|
|
|
|
operation: CrdtSyncViolationOperation.mergeInsert,
|
|
|
|
|
tableName: insert.tableName,
|
|
|
|
|
rowId: insert.uuidRowId,
|
|
|
|
|
owningScopeId: collision.owningScopeId,
|
|
|
|
|
incomingScope: mergingScope,
|
|
|
|
|
metadataRowId: null,
|
|
|
|
|
node: remoteNode,
|
|
|
|
|
hlc: insert.hlc,
|
|
|
|
|
transaction: transaction,
|
|
|
|
|
);
|
|
|
|
|
}
|
2026-05-07 00:42:23 -03:00
|
|
|
} else {
|
|
|
|
|
await _applyMergeInsertForExistingRow(
|
|
|
|
|
insert,
|
|
|
|
|
currentRow,
|
|
|
|
|
remoteNode,
|
|
|
|
|
incomingHlc,
|
|
|
|
|
data,
|
2026-06-06 00:55:10 -03:00
|
|
|
context,
|
2026-05-07 00:42:23 -03:00
|
|
|
transaction,
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Future<void> _applyMergeUpdate(
|
|
|
|
|
CrdtMergeUpdate update,
|
|
|
|
|
Map<UuidValue, CrdtNode> remoteNodes,
|
2026-08-07 13:01:29 -03:00
|
|
|
MergeContext context,
|
2026-05-07 00:42:23 -03:00
|
|
|
Transaction transaction,
|
|
|
|
|
) async {
|
|
|
|
|
final rowKey = (update.tableName, update.uuidRowId);
|
2026-06-06 00:55:10 -03:00
|
|
|
final row = context.rows[rowKey];
|
2026-05-07 00:42:23 -03:00
|
|
|
if (row == null) return;
|
2026-06-18 01:05:24 -03:00
|
|
|
final remoteNode = _requireRemoteNode(remoteNodes, update.uuidNodeId);
|
|
|
|
|
if (!await _domainRowOwnedByEffectiveScope(
|
|
|
|
|
operation: CrdtSyncViolationOperation.mergeUpdate,
|
|
|
|
|
tableName: update.tableName,
|
|
|
|
|
rowId: update.uuidRowId,
|
|
|
|
|
context: context,
|
|
|
|
|
transaction: transaction,
|
|
|
|
|
metadataRowId: row.id,
|
|
|
|
|
node: remoteNode,
|
|
|
|
|
hlc: update.hlc,
|
|
|
|
|
)) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
2026-05-07 00:42:23 -03:00
|
|
|
|
|
|
|
|
final shouldApply = await _shouldMergeFieldMetadataIfNewer(
|
|
|
|
|
tableName: update.tableName,
|
|
|
|
|
rowId: update.uuidRowId,
|
|
|
|
|
columnName: update.columnName,
|
|
|
|
|
row: row,
|
2026-06-18 01:05:24 -03:00
|
|
|
remoteNode: remoteNode,
|
2026-05-07 00:42:23 -03:00
|
|
|
incomingHlc: update.hlc,
|
2026-06-06 00:55:10 -03:00
|
|
|
fields: context.fields,
|
2026-05-07 00:42:23 -03:00
|
|
|
transaction: transaction,
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
if (!shouldApply) return;
|
2026-06-06 00:55:10 -03:00
|
|
|
|
2026-08-07 13:01:29 -03:00
|
|
|
final resolvedUpdates = await _uniqueResolver.resolveForIncomingUpdate(
|
2026-06-06 00:55:10 -03:00
|
|
|
update,
|
|
|
|
|
row,
|
|
|
|
|
context,
|
|
|
|
|
transaction,
|
|
|
|
|
);
|
2026-08-07 13:01:29 -03:00
|
|
|
final safeUpdate = await _foreignKeyProjector.safeIncomingData(
|
2026-06-10 17:31:05 -03:00
|
|
|
update.tableName,
|
|
|
|
|
update.uuidRowId,
|
|
|
|
|
resolvedUpdates,
|
|
|
|
|
transaction,
|
|
|
|
|
);
|
2026-08-07 13:01:29 -03:00
|
|
|
await _context.updateDomainRows(
|
2026-05-07 00:42:23 -03:00
|
|
|
update.tableName,
|
|
|
|
|
{update.uuidRowId},
|
2026-06-10 17:31:05 -03:00
|
|
|
safeUpdate.data,
|
|
|
|
|
transaction,
|
|
|
|
|
);
|
2026-08-07 13:01:29 -03:00
|
|
|
await _foreignKeyProjector.recordAttemptsForRows(
|
2026-06-10 17:31:05 -03:00
|
|
|
update.tableName,
|
|
|
|
|
{update.uuidRowId},
|
|
|
|
|
resolvedUpdates.keys.toSet(),
|
2026-05-07 00:42:23 -03:00
|
|
|
transaction,
|
2026-06-10 17:31:05 -03:00
|
|
|
attemptedValues: safeUpdate.attempts,
|
2026-05-07 00:42:23 -03:00
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Future<void> _applyMergeDelete(
|
|
|
|
|
CrdtMergeDelete delete,
|
|
|
|
|
Map<UuidValue, CrdtNode> remoteNodes,
|
2026-08-07 13:01:29 -03:00
|
|
|
MergeContext context,
|
2026-05-07 00:42:23 -03:00
|
|
|
Transaction transaction,
|
|
|
|
|
) async {
|
|
|
|
|
final rowKey = (delete.tableName, delete.uuidRowId);
|
2026-06-06 00:55:10 -03:00
|
|
|
final row = context.rows[rowKey];
|
2026-05-07 00:42:23 -03:00
|
|
|
if (row == null) return;
|
2026-06-10 17:31:05 -03:00
|
|
|
if (!delete.reason.isSynced) return;
|
2026-06-18 01:05:24 -03:00
|
|
|
final remoteNode = _requireRemoteNode(remoteNodes, delete.uuidNodeId);
|
|
|
|
|
if (!await _domainRowOwnedByEffectiveScope(
|
|
|
|
|
operation: CrdtSyncViolationOperation.mergeDelete,
|
|
|
|
|
tableName: delete.tableName,
|
|
|
|
|
rowId: delete.uuidRowId,
|
|
|
|
|
context: context,
|
|
|
|
|
transaction: transaction,
|
|
|
|
|
metadataRowId: row.id,
|
|
|
|
|
node: remoteNode,
|
|
|
|
|
hlc: delete.hlc,
|
|
|
|
|
)) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
2026-05-07 00:42:23 -03:00
|
|
|
|
2026-06-06 00:55:10 -03:00
|
|
|
final currentTombstone = context.tombstones[rowKey];
|
2026-05-31 14:17:59 -03:00
|
|
|
final currentClFlag = currentTombstone?.clFlag ?? 1;
|
|
|
|
|
final currentHlc = currentTombstone?.hlc ?? row.hlc;
|
|
|
|
|
if (delete.clFlag < currentClFlag) return;
|
|
|
|
|
if (delete.clFlag == currentClFlag && delete.hlc <= currentHlc) return;
|
2026-05-07 00:42:23 -03:00
|
|
|
|
2026-06-06 00:55:10 -03:00
|
|
|
context.tombstones[rowKey] = await _upsertMergeTombstone(
|
2026-05-07 00:42:23 -03:00
|
|
|
row,
|
2026-06-18 01:05:24 -03:00
|
|
|
remoteNode,
|
2026-05-31 14:17:59 -03:00
|
|
|
delete.hlc,
|
|
|
|
|
delete.clFlag,
|
|
|
|
|
delete.reason,
|
2026-05-07 00:42:23 -03:00
|
|
|
currentTombstone,
|
|
|
|
|
transaction,
|
|
|
|
|
);
|
2026-06-10 17:31:05 -03:00
|
|
|
|
|
|
|
|
if (delete.reason.isSynced) {
|
2026-08-07 13:01:29 -03:00
|
|
|
await _context.applyRowVisibilityFromUserTombstone(
|
2026-06-10 17:31:05 -03:00
|
|
|
row,
|
|
|
|
|
context.tombstones[rowKey]!,
|
|
|
|
|
transaction,
|
|
|
|
|
);
|
|
|
|
|
}
|
2026-05-07 00:42:23 -03:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Future<CrdtDataRow> _upsertMergeRow(
|
|
|
|
|
String tableName,
|
|
|
|
|
UuidValue rowId,
|
|
|
|
|
CrdtNode remoteNode,
|
|
|
|
|
Hlc incomingHlc,
|
|
|
|
|
CrdtDataRow? currentRow,
|
|
|
|
|
Transaction transaction,
|
|
|
|
|
) async {
|
|
|
|
|
if (currentRow == null) {
|
2026-08-07 13:01:29 -03:00
|
|
|
final (tableId, _) = _context.schema[tableName]!;
|
2026-05-07 00:42:23 -03:00
|
|
|
final insertedRow = await CrdtDataRow.db.insertRow(
|
|
|
|
|
_session,
|
|
|
|
|
CrdtDataRow(
|
2026-08-07 13:01:29 -03:00
|
|
|
scopeId: _context.hlcManagerFor(transaction).normalizedScopeId,
|
2026-05-07 00:42:23 -03:00
|
|
|
tblId: tableId,
|
|
|
|
|
uuidRowId: rowId,
|
|
|
|
|
nodeId: remoteNode.id!,
|
|
|
|
|
hlcDatetime: incomingHlc.datetime,
|
|
|
|
|
hlcCounter: incomingHlc.counter,
|
|
|
|
|
),
|
|
|
|
|
transaction: transaction,
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
return insertedRow.copyWith(node: remoteNode);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
final updatedRow = currentRow.copyWith(
|
|
|
|
|
nodeId: remoteNode.id,
|
|
|
|
|
node: remoteNode,
|
|
|
|
|
hlcDatetime: incomingHlc.datetime,
|
|
|
|
|
hlcCounter: incomingHlc.counter,
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
await CrdtDataRow.db.update(
|
|
|
|
|
_session,
|
|
|
|
|
[updatedRow],
|
|
|
|
|
columns: (t) => [t.nodeId, t.hlcDatetime, t.hlcCounter],
|
|
|
|
|
transaction: transaction,
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
return updatedRow;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Future<CrdtDataField> _upsertMergeField(
|
|
|
|
|
CrdtDataRow row,
|
|
|
|
|
CrdtSchemaColumn column,
|
|
|
|
|
CrdtNode remoteNode,
|
|
|
|
|
Hlc incomingHlc,
|
|
|
|
|
CrdtDataField? currentField,
|
|
|
|
|
Transaction transaction,
|
|
|
|
|
) async {
|
|
|
|
|
if (currentField == null) {
|
|
|
|
|
final insertedField = await CrdtDataField.db.insertRow(
|
|
|
|
|
_session,
|
|
|
|
|
CrdtDataField(
|
|
|
|
|
rowId: row.id!,
|
|
|
|
|
columnId: column.id!,
|
|
|
|
|
nodeId: remoteNode.id!,
|
|
|
|
|
hlcDatetime: incomingHlc.datetime,
|
|
|
|
|
hlcCounter: incomingHlc.counter,
|
|
|
|
|
),
|
|
|
|
|
transaction: transaction,
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
return insertedField.copyWith(
|
|
|
|
|
row: row,
|
|
|
|
|
column: column,
|
|
|
|
|
node: remoteNode,
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
final updatedField = currentField.copyWith(
|
|
|
|
|
row: row,
|
|
|
|
|
column: column,
|
|
|
|
|
nodeId: remoteNode.id,
|
|
|
|
|
node: remoteNode,
|
|
|
|
|
hlcDatetime: incomingHlc.datetime,
|
|
|
|
|
hlcCounter: incomingHlc.counter,
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
await CrdtDataField.db.update(
|
|
|
|
|
_session,
|
|
|
|
|
[updatedField],
|
|
|
|
|
columns: (t) => [t.nodeId, t.hlcDatetime, t.hlcCounter],
|
|
|
|
|
transaction: transaction,
|
|
|
|
|
);
|
|
|
|
|
return updatedField;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Future<CrdtDataDeleted> _upsertMergeTombstone(
|
|
|
|
|
CrdtDataRow row,
|
|
|
|
|
CrdtNode remoteNode,
|
|
|
|
|
Hlc incomingHlc,
|
2026-05-31 14:17:59 -03:00
|
|
|
int clFlag,
|
|
|
|
|
CrdtDataDeletedReason reason,
|
2026-05-07 00:42:23 -03:00
|
|
|
CrdtDataDeleted? currentTombstone,
|
|
|
|
|
Transaction transaction,
|
|
|
|
|
) async {
|
|
|
|
|
if (currentTombstone == null) {
|
|
|
|
|
final insertedTombstone = await CrdtDataDeleted.db.insertRow(
|
|
|
|
|
_session,
|
|
|
|
|
CrdtDataDeleted(
|
|
|
|
|
rowId: row.id!,
|
|
|
|
|
nodeId: remoteNode.id!,
|
|
|
|
|
hlcDatetime: incomingHlc.datetime,
|
|
|
|
|
hlcCounter: incomingHlc.counter,
|
2026-05-31 14:17:59 -03:00
|
|
|
clFlag: clFlag,
|
|
|
|
|
reason: reason,
|
2026-05-07 00:42:23 -03:00
|
|
|
),
|
|
|
|
|
transaction: transaction,
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
return insertedTombstone.copyWith(
|
|
|
|
|
row: row,
|
|
|
|
|
node: remoteNode,
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
final updatedTombstone = currentTombstone.copyWith(
|
|
|
|
|
row: row,
|
|
|
|
|
nodeId: remoteNode.id,
|
|
|
|
|
node: remoteNode,
|
|
|
|
|
hlcDatetime: incomingHlc.datetime,
|
|
|
|
|
hlcCounter: incomingHlc.counter,
|
2026-05-31 14:17:59 -03:00
|
|
|
clFlag: clFlag,
|
|
|
|
|
reason: reason,
|
2026-05-07 00:42:23 -03:00
|
|
|
);
|
|
|
|
|
|
|
|
|
|
await CrdtDataDeleted.db.update(
|
|
|
|
|
_session,
|
|
|
|
|
[updatedTombstone],
|
2026-05-31 14:17:59 -03:00
|
|
|
columns: (t) => [t.nodeId, t.hlcDatetime, t.hlcCounter, t.clFlag, t.reason],
|
2026-05-07 00:42:23 -03:00
|
|
|
transaction: transaction,
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
return updatedTombstone;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Future<CrdtDataRow> _applyMergeInsertForMissingRow(
|
|
|
|
|
CrdtMergeInsert insert,
|
|
|
|
|
CrdtNode remoteNode,
|
|
|
|
|
Hlc incomingHlc,
|
|
|
|
|
Map<String, Object?> data,
|
|
|
|
|
Transaction transaction,
|
|
|
|
|
) async {
|
|
|
|
|
final insertedCrdtRow = await _upsertMergeRow(
|
|
|
|
|
insert.tableName,
|
|
|
|
|
insert.uuidRowId,
|
|
|
|
|
remoteNode,
|
|
|
|
|
incomingHlc,
|
|
|
|
|
null,
|
|
|
|
|
transaction,
|
|
|
|
|
);
|
|
|
|
|
|
2026-06-06 00:55:10 -03:00
|
|
|
final tableRow = _requireMergeInsertTableRow(insert);
|
|
|
|
|
final patchedRow = _db.serializationManager.patchTableRow(tableRow, data);
|
2026-08-07 13:01:29 -03:00
|
|
|
final mergingScopeId = _context.hlcManagerFor(transaction).normalizedScopeId;
|
|
|
|
|
final scopedRow = patchedRow.copyWithScopeId(mergingScopeId);
|
2026-05-07 00:42:23 -03:00
|
|
|
try {
|
2026-06-18 01:05:24 -03:00
|
|
|
// Insert first: the domain primary key resolves creation races
|
|
|
|
|
// atomically. The inner savepoint keeps a violation from poisoning the
|
|
|
|
|
// surrounding transaction so the recovery update below can still run.
|
|
|
|
|
await DatabaseUtil.runInTransactionOrSavepoint(
|
|
|
|
|
_db,
|
|
|
|
|
transaction,
|
|
|
|
|
(savepoint) => _db.insertRow(scopedRow, transaction: savepoint),
|
|
|
|
|
);
|
|
|
|
|
} on DatabaseQueryException {
|
|
|
|
|
final owner = await _readDomainRowOwner(
|
|
|
|
|
insert.tableName,
|
|
|
|
|
insert.uuidRowId,
|
|
|
|
|
transaction,
|
|
|
|
|
);
|
|
|
|
|
// No row means the violation came from something other than the
|
|
|
|
|
// primary key (e.g. a racing unique value); preserve the failure.
|
|
|
|
|
if (!owner.exists) rethrow;
|
|
|
|
|
if (owner.scopeId != mergingScopeId) {
|
|
|
|
|
throw _ForeignScopeRowCollision(owner.scopeId);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Same-scope recovery (a tracked row whose metadata was lost, or a
|
|
|
|
|
// race between this scope's own merges). scopeId is immutable and rows
|
|
|
|
|
// are only soft-deleted, so ownership observed here cannot change for
|
|
|
|
|
// the rest of the transaction and the update is safe.
|
2026-05-07 00:42:23 -03:00
|
|
|
await _db.updateRow(
|
2026-06-18 01:05:24 -03:00
|
|
|
scopedRow,
|
|
|
|
|
columns: scopedRow.table.managedColumns
|
2026-05-07 00:42:23 -03:00
|
|
|
.where((c) => data.containsKey(c.columnName))
|
|
|
|
|
.toList(),
|
|
|
|
|
transaction: transaction,
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return insertedCrdtRow;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Future<void> _applyMergeInsertForExistingRow(
|
|
|
|
|
CrdtMergeInsert insert,
|
|
|
|
|
CrdtDataRow currentRow,
|
|
|
|
|
CrdtNode remoteNode,
|
|
|
|
|
Hlc incomingHlc,
|
|
|
|
|
Map<String, Object?> data,
|
2026-08-07 13:01:29 -03:00
|
|
|
MergeContext context,
|
2026-05-07 00:42:23 -03:00
|
|
|
Transaction transaction,
|
|
|
|
|
) async {
|
2026-06-18 01:05:24 -03:00
|
|
|
if (!await _domainRowOwnedByEffectiveScope(
|
|
|
|
|
operation: CrdtSyncViolationOperation.mergeInsert,
|
|
|
|
|
tableName: insert.tableName,
|
|
|
|
|
rowId: insert.uuidRowId,
|
|
|
|
|
context: context,
|
|
|
|
|
transaction: transaction,
|
|
|
|
|
metadataRowId: currentRow.id,
|
|
|
|
|
node: remoteNode,
|
|
|
|
|
hlc: insert.hlc,
|
|
|
|
|
)) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-07 13:01:29 -03:00
|
|
|
final (_, columnsByName) = _context.schema[insert.tableName]!;
|
2026-05-07 00:42:23 -03:00
|
|
|
final updatedValues = <String, Object?>{};
|
|
|
|
|
for (final MapEntry(key: columnName, value: schemaColumn)
|
|
|
|
|
in columnsByName.entries) {
|
|
|
|
|
if (columnName == 'id') continue;
|
|
|
|
|
|
|
|
|
|
final shouldApply = await _shouldMergeFieldMetadataIfNewer(
|
|
|
|
|
tableName: insert.tableName,
|
|
|
|
|
rowId: insert.uuidRowId,
|
|
|
|
|
columnName: columnName,
|
|
|
|
|
row: currentRow,
|
|
|
|
|
remoteNode: remoteNode,
|
|
|
|
|
incomingHlc: incomingHlc,
|
2026-06-06 00:55:10 -03:00
|
|
|
fields: context.fields,
|
2026-05-07 00:42:23 -03:00
|
|
|
transaction: transaction,
|
|
|
|
|
schemaColumn: schemaColumn,
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
if (!shouldApply) continue;
|
|
|
|
|
updatedValues[columnName] = data[columnName];
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-06 00:55:10 -03:00
|
|
|
var updatesToApply = updatedValues;
|
|
|
|
|
if (updatesToApply.isNotEmpty) {
|
2026-08-07 13:01:29 -03:00
|
|
|
updatesToApply = await _uniqueResolver.resolveForIncomingUpdates(
|
2026-06-06 00:55:10 -03:00
|
|
|
tableName: insert.tableName,
|
|
|
|
|
row: currentRow,
|
|
|
|
|
updates: updatesToApply,
|
|
|
|
|
context: context,
|
|
|
|
|
transaction: transaction,
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (updatesToApply.isNotEmpty) {
|
2026-08-07 13:01:29 -03:00
|
|
|
final safeUpdate = await _foreignKeyProjector.safeIncomingData(
|
2026-06-10 17:31:05 -03:00
|
|
|
insert.tableName,
|
|
|
|
|
insert.uuidRowId,
|
|
|
|
|
updatesToApply,
|
|
|
|
|
transaction,
|
|
|
|
|
);
|
2026-08-07 13:01:29 -03:00
|
|
|
await _context.updateDomainRows(
|
2026-05-07 00:42:23 -03:00
|
|
|
insert.tableName,
|
|
|
|
|
{insert.uuidRowId},
|
2026-06-10 17:31:05 -03:00
|
|
|
safeUpdate.data,
|
2026-05-07 00:42:23 -03:00
|
|
|
transaction,
|
|
|
|
|
);
|
2026-08-07 13:01:29 -03:00
|
|
|
await _foreignKeyProjector.recordAttemptsForRows(
|
2026-06-10 17:31:05 -03:00
|
|
|
insert.tableName,
|
|
|
|
|
{insert.uuidRowId},
|
|
|
|
|
updatesToApply.keys.toSet(),
|
|
|
|
|
transaction,
|
|
|
|
|
attemptedValues: safeUpdate.attempts,
|
|
|
|
|
);
|
2026-05-07 00:42:23 -03:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
final rowKey = (insert.tableName, insert.uuidRowId);
|
2026-06-06 00:55:10 -03:00
|
|
|
final currentTombstone = context.tombstones[rowKey];
|
2026-05-31 14:17:59 -03:00
|
|
|
if ((currentTombstone?.clFlag ?? 1) == 1 &&
|
|
|
|
|
incomingHlc > (currentTombstone?.hlc ?? currentRow.hlc)) {
|
2026-06-06 00:55:10 -03:00
|
|
|
context.tombstones[rowKey] = await _upsertMergeTombstone(
|
2026-05-07 00:42:23 -03:00
|
|
|
currentRow,
|
|
|
|
|
remoteNode,
|
|
|
|
|
incomingHlc,
|
2026-05-31 14:17:59 -03:00
|
|
|
1,
|
|
|
|
|
CrdtDataDeletedReason.userInsert,
|
2026-05-07 00:42:23 -03:00
|
|
|
currentTombstone,
|
|
|
|
|
transaction,
|
|
|
|
|
);
|
2026-08-07 13:01:29 -03:00
|
|
|
await _context.applyRowVisibilityFromUserTombstone(
|
2026-06-10 17:31:05 -03:00
|
|
|
currentRow,
|
|
|
|
|
context.tombstones[rowKey]!,
|
|
|
|
|
transaction,
|
|
|
|
|
);
|
2026-05-07 00:42:23 -03:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Future<bool> _shouldMergeFieldMetadataIfNewer({
|
|
|
|
|
required String tableName,
|
|
|
|
|
required UuidValue rowId,
|
|
|
|
|
required String columnName,
|
|
|
|
|
required CrdtDataRow row,
|
|
|
|
|
required CrdtNode remoteNode,
|
|
|
|
|
required Hlc incomingHlc,
|
2026-08-07 13:01:29 -03:00
|
|
|
required Map<MergeFieldKey, CrdtDataField> fields,
|
2026-05-07 00:42:23 -03:00
|
|
|
required Transaction transaction,
|
|
|
|
|
CrdtSchemaColumn? schemaColumn,
|
|
|
|
|
}) async {
|
2026-06-10 17:31:05 -03:00
|
|
|
final resolvedSchemaColumn =
|
2026-08-07 13:01:29 -03:00
|
|
|
schemaColumn ?? _context.schemaColumn(tableName, columnName);
|
2026-05-07 00:42:23 -03:00
|
|
|
if (resolvedSchemaColumn == null) return false;
|
|
|
|
|
|
|
|
|
|
final fieldKey = (tableName, rowId, columnName);
|
|
|
|
|
final currentField = fields[fieldKey];
|
|
|
|
|
final currentHlc = currentField?.hlc ?? row.hlc;
|
|
|
|
|
if (incomingHlc <= currentHlc) return false;
|
|
|
|
|
|
|
|
|
|
fields[fieldKey] = await _upsertMergeField(
|
|
|
|
|
row,
|
|
|
|
|
resolvedSchemaColumn,
|
|
|
|
|
remoteNode,
|
|
|
|
|
incomingHlc,
|
|
|
|
|
currentField,
|
|
|
|
|
transaction,
|
|
|
|
|
);
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
TableRow _requireMergeInsertTableRow(CrdtMergeInsert insert) {
|
|
|
|
|
final row = insert.data;
|
|
|
|
|
if (row is TableRow) return row;
|
|
|
|
|
|
|
|
|
|
throw StateError(
|
|
|
|
|
'Unsupported merge insert payload type for "${insert.tableName}": '
|
|
|
|
|
'${row.runtimeType}. Expected subclass of TableRow.',
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
CrdtNode _requireRemoteNode(
|
|
|
|
|
Map<UuidValue, CrdtNode> remoteNodes,
|
|
|
|
|
UuidValue uuidNodeId,
|
|
|
|
|
) {
|
|
|
|
|
return remoteNodes[uuidNodeId] ??
|
|
|
|
|
(throw StateError(
|
|
|
|
|
'Remote node $uuidNodeId not found for merge.',
|
|
|
|
|
));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Map<String, Object?> _sanitizeMergeRowData(
|
|
|
|
|
String tableName,
|
|
|
|
|
Map<String, Object?> data,
|
|
|
|
|
) {
|
2026-08-07 13:01:29 -03:00
|
|
|
final columns = _context.columnsByTableAndName[tableName];
|
2026-05-07 00:42:23 -03:00
|
|
|
if (columns == null) return {};
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
for (final MapEntry(key: columnName, value: value) in data.entries)
|
2026-06-18 01:05:24 -03:00
|
|
|
if (columnName != 'id' &&
|
|
|
|
|
columnName != 'scopeId' &&
|
|
|
|
|
columns.containsKey(columnName))
|
2026-06-10 17:31:05 -03:00
|
|
|
columnName: columns[columnName]!.columnType == ColumnType.uuid
|
2026-08-07 13:01:29 -03:00
|
|
|
? value.toUuidValue()
|
2026-06-10 17:31:05 -03:00
|
|
|
: value,
|
2026-05-07 00:42:23 -03:00
|
|
|
};
|
|
|
|
|
}
|
2026-06-18 01:05:24 -03:00
|
|
|
|
2026-08-07 13:01:29 -03:00
|
|
|
Future<DomainRowOwner> _readDomainRowOwner(
|
2026-06-18 01:05:24 -03:00
|
|
|
String tableName,
|
|
|
|
|
UuidValue rowId,
|
|
|
|
|
Transaction transaction,
|
|
|
|
|
) async {
|
2026-08-07 13:01:29 -03:00
|
|
|
final values = await _context.readDomainColumnValues(
|
2026-06-18 01:05:24 -03:00
|
|
|
tableName,
|
|
|
|
|
{rowId},
|
|
|
|
|
['scopeId'],
|
|
|
|
|
transaction,
|
|
|
|
|
);
|
|
|
|
|
final row = values[rowId];
|
|
|
|
|
if (row == null) return (exists: false, scopeId: null);
|
|
|
|
|
return (exists: true, scopeId: row['scopeId'] as int?);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Returns the owning scope of [rowId] from the merge snapshot taken in
|
|
|
|
|
/// [_loadMergeContext], reading the domain row only if it was not captured
|
|
|
|
|
/// there (e.g. a row a concurrent operation added since the snapshot).
|
2026-08-07 13:01:29 -03:00
|
|
|
Future<DomainRowOwner> _resolveDomainOwner(
|
|
|
|
|
MergeContext context,
|
2026-06-18 01:05:24 -03:00
|
|
|
String tableName,
|
|
|
|
|
UuidValue rowId,
|
|
|
|
|
Transaction transaction,
|
|
|
|
|
) async {
|
|
|
|
|
final key = (tableName, rowId);
|
|
|
|
|
final cached = context.domainOwners[key];
|
|
|
|
|
if (cached != null) return cached;
|
|
|
|
|
final owner = await _readDomainRowOwner(tableName, rowId, transaction);
|
|
|
|
|
context.domainOwners[key] = owner;
|
|
|
|
|
return owner;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Future<bool> _domainRowOwnedByEffectiveScope({
|
|
|
|
|
required CrdtSyncViolationOperation operation,
|
|
|
|
|
required String tableName,
|
|
|
|
|
required UuidValue rowId,
|
2026-08-07 13:01:29 -03:00
|
|
|
required MergeContext context,
|
2026-06-18 01:05:24 -03:00
|
|
|
required Transaction transaction,
|
|
|
|
|
int? metadataRowId,
|
|
|
|
|
CrdtNode? node,
|
|
|
|
|
Hlc? hlc,
|
|
|
|
|
}) async {
|
|
|
|
|
final owner = await _resolveDomainOwner(context, tableName, rowId, transaction);
|
2026-08-07 13:01:29 -03:00
|
|
|
final mergingScope = _context.effectiveScopeFor(transaction);
|
2026-06-18 01:05:24 -03:00
|
|
|
if (owner.exists && owner.scopeId == mergingScope.id) return true;
|
|
|
|
|
if (!owner.exists) return false;
|
|
|
|
|
|
|
|
|
|
await _throwOwnershipCollision(
|
|
|
|
|
operation: operation,
|
|
|
|
|
tableName: tableName,
|
|
|
|
|
rowId: rowId,
|
|
|
|
|
owningScopeId: owner.scopeId,
|
|
|
|
|
incomingScope: mergingScope,
|
|
|
|
|
metadataRowId: metadataRowId,
|
|
|
|
|
node: node,
|
|
|
|
|
hlc: hlc,
|
|
|
|
|
transaction: transaction,
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Future<Never> _throwOwnershipCollision({
|
|
|
|
|
required CrdtSyncViolationOperation operation,
|
|
|
|
|
required String tableName,
|
|
|
|
|
required UuidValue rowId,
|
|
|
|
|
required int? owningScopeId,
|
|
|
|
|
required CrdtScope incomingScope,
|
|
|
|
|
required int? metadataRowId,
|
|
|
|
|
required Transaction transaction,
|
|
|
|
|
CrdtNode? node,
|
|
|
|
|
Hlc? hlc,
|
|
|
|
|
}) async {
|
|
|
|
|
final now = DateTime.now().toUtc();
|
|
|
|
|
throw CrdtSyncIntegrityViolationException(
|
|
|
|
|
CrdtSyncIntegrityViolation(
|
|
|
|
|
type: CrdtSyncViolationType.ownershipCollision,
|
|
|
|
|
domainTableName: tableName,
|
|
|
|
|
uuidRowId: rowId,
|
|
|
|
|
ownerScopeUuid: await _scopeUuidForNormalizedId(owningScopeId, transaction),
|
|
|
|
|
incomingScopeUuid: incomingScope.uuidScopeId,
|
|
|
|
|
operation: operation,
|
|
|
|
|
uuidNodeId: node?.uuidNodeId,
|
|
|
|
|
crdtDataRowId: metadataRowId,
|
|
|
|
|
hlcDatetime: hlc?.datetime,
|
|
|
|
|
hlcCounter: hlc?.counter,
|
|
|
|
|
firstSeenAt: now,
|
|
|
|
|
lastSeenAt: now,
|
|
|
|
|
occurrences: 1,
|
|
|
|
|
),
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Future<UuidValue?> _scopeUuidForNormalizedId(
|
|
|
|
|
int? scopeId,
|
|
|
|
|
Transaction transaction,
|
|
|
|
|
) async {
|
|
|
|
|
if (scopeId == null) return null;
|
|
|
|
|
|
|
|
|
|
final scope = await CrdtScope.db.findById(
|
|
|
|
|
_session,
|
|
|
|
|
scopeId,
|
|
|
|
|
transaction: transaction,
|
|
|
|
|
);
|
|
|
|
|
return scope?.uuidScopeId;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Signals that a merge insert lost a primary-key race to a row owned by
|
|
|
|
|
/// another scope, so the savepoint around the insert application must be
|
|
|
|
|
/// rolled back before the sync violation is recorded and thrown.
|
|
|
|
|
class _ForeignScopeRowCollision implements Exception {
|
|
|
|
|
_ForeignScopeRowCollision(this.owningScopeId);
|
|
|
|
|
|
|
|
|
|
final int? owningScopeId;
|
2026-05-07 00:42:23 -03:00
|
|
|
}
|
2026-06-06 00:55:10 -03:00
|
|
|
|
|
|
|
|
extension on DatabaseSerializationManager {
|
|
|
|
|
/// Patches a [TableRow] with the given data.
|
|
|
|
|
T patchTableRow<T extends TableRow>(T row, Map<String, Object?> data) {
|
|
|
|
|
final rowJson = Map<String, dynamic>.from(row.toJson() as Map);
|
2026-08-07 13:01:29 -03:00
|
|
|
for (final column in row.table.crdtSyncableColumns) {
|
|
|
|
|
if (data.containsKey(column.columnName)) {
|
2026-06-06 00:55:10 -03:00
|
|
|
rowJson[column.fieldName] = data[column.columnName];
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return deserialize<T>(rowJson);
|
|
|
|
|
}
|
|
|
|
|
}
|