Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 28 additions & 8 deletions src/core/sync/executeSync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,30 @@ import type { DB, QueryResult } from '@op-engineering/op-sqlite';
import type { Logger } from '../common/logger';

/**
* Extracts the number of changes from a CloudSync query result
* Extracts the number of received rows from a CloudSync query result.
*
* The result row contains a JSON string:
* {"status":"synced|syncing|out-of-sync","localVersion":N,"serverVersion":N,"rowsReceived":N}
*
* We only use rowsReceived since polling is for downloading remote changes.
* The status field relates to upload state and is not relevant here.
*/
const extractChangesFromResult = (result: QueryResult | undefined): number => {
const firstRow = result?.rows?.[0];
const value = firstRow ? Object.values(firstRow)[0] : 0;
return typeof value === 'number' ? value : 0;
if (!firstRow) return 0;

const raw = Object.values(firstRow)[0];

if (typeof raw === 'string') {
try {
const parsed = JSON.parse(raw);
return typeof parsed.rowsReceived === 'number' ? parsed.rowsReceived : 0;
} catch {
return 0;
}
}

return 0;
};

/**
Expand Down Expand Up @@ -68,7 +86,7 @@ export async function executeSync(
]);

changes = extractChangesFromResult(result);
logger.info(`🔄 Sync result: ${changes} changes`);
logger.info(`🔄 Sync result: ${changes} changes downloaded`);
} else {
/** JS RETRY MODE */
// Retry/delay in JS thread - better for foreground (doesn't block write connection)
Expand All @@ -87,24 +105,26 @@ export async function executeSync(
}

changes = extractChangesFromResult(result);
logger.info(`🔄 Sync attempt ${attempt + 1} result: ${changes} changes`);
logger.info(
`🔄 Sync attempt ${attempt + 1} result: ${changes} changes downloaded`
);

if (changes > 0) {
break;
}

// Wait before next attempt (except on last attempt)
if (attempt < maxAttempts - 1) {
await new Promise((resolve) => setTimeout(resolve, attemptDelay));
await new Promise<void>((resolve) => setTimeout(resolve, attemptDelay));
}
}
}

/** LOG RESULT */
if (changes > 0) {
logger.info(`✅ Sync completed: ${changes} changes synced`);
logger.info(`✅ Sync completed: ${changes} changes downloaded`);
} else {
logger.info('✅ Sync completed: no changes');
logger.info('✅ Sync completed: no changes downloaded');
}

return changes;
Expand Down