/* This file is part of Ezra Bible App.
Copyright (C) 2019 - 2026 Ezra Bible App Development Team <contact@ezrabibleapp.net>
Ezra Bible App is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
Ezra Bible App is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Ezra Bible App. See the file LICENSE.
If not, see <http://www.gnu.org/licenses/>. */
const fs = require('fs');
const path = require('path');
const MAX_RETRIES = 3;
const INITIAL_RETRY_DELAY_MS = 1000;
const DEFAULT_RATE_LIMIT_DELAY_MS = 60000;
const RETRYABLE_NETWORK_ERRORS = ['EAI_AGAIN', 'ETIMEDOUT', 'ECONNRESET', 'ENOTFOUND', 'ECONNREFUSED'];
/**
* Provider-agnostic base class for two-way synchronization of a single file with a remote storage.
*
* Subclasses implement the primitives (getRemoteFileInfo, downloadFile, uploadFile, isFileSynced,
* getLocalFileHash, testAuthentication, listFolderEntries). The sync decision logic lives in syncFileTwoWay().
*
* syncFileTwoWay() return codes:
* 0 already in sync
* 1 downloaded remote file
* 2 uploaded local file
* -1 download failed
* -2 upload failed
* -3 not in sync after operation (reserved; mapped to 'SYNC FAILED' by ipc_db_handler)
* -4 uploaded, but not in sync afterwards (remote file may be corrupted)
* -5 local file missing
* -6 could not determine sync status
*/
class RemoteFileSync {
constructor() {
this.providerName = 'remote storage';
}
// ---------- Primitives to be implemented by subclasses ----------
// eslint-disable-next-line no-unused-vars
async getRemoteFileInfo(remotePath) { throw new Error('getRemoteFileInfo not implemented'); }
// eslint-disable-next-line no-unused-vars
async downloadFile(remotePath, localDir) { throw new Error('downloadFile not implemented'); }
// eslint-disable-next-line no-unused-vars
async uploadFile(localPath, remotePath) { throw new Error('uploadFile not implemented'); }
// eslint-disable-next-line no-unused-vars
async isFileSynced(localPath, remotePath) { throw new Error('isFileSynced not implemented'); }
// eslint-disable-next-line no-unused-vars
async getLocalFileHash(localPath) { throw new Error('getLocalFileHash not implemented'); }
async testAuthentication() { throw new Error('testAuthentication not implemented'); }
/**
* List the direct children of a remote folder.
* @param {string} remotePath folder path ('' or '/' for the root), in the same form as accepted by downloadFile()
* @returns {Promise<Array<{name: string, path: string, isFolder: boolean, size: number}>>}
* `path` of each entry can be passed to listFolderEntries() / downloadFile() again.
* @throws an error with `notFound = true` if the folder does not exist
*/
// eslint-disable-next-line no-unused-vars
async listFolderEntries(remotePath) { throw new Error('listFolderEntries not implemented'); }
/**
* Refresh the access credentials if the provider uses expiring tokens. No-op by default.
*/
async refreshAccessToken() { return null; }
// ---------- Retry handling ----------
_sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
_isRetryableError(error) {
if (!error) {
return false;
}
if (error.status === 429) {
return true;
}
if (error.status >= 500 && error.status < 600) {
return true;
}
return RETRYABLE_NETWORK_ERRORS.includes(error.code);
}
_getRetryDelay(error, attempt) {
if (error.status === 429) {
if (error.headers && error.headers['retry-after']) {
return parseInt(error.headers['retry-after'], 10) * 1000;
}
return DEFAULT_RATE_LIMIT_DELAY_MS;
}
return INITIAL_RETRY_DELAY_MS * Math.pow(2, attempt - 1);
}
/**
* Execute an API call with retry logic and exponential backoff.
* @param {Function} apiCall - Async function that performs the API call
* @param {string} operationName - Name of the operation for logging
* @param {boolean} trackRetries - Whether to return {result, retryCount} instead of the plain result
*/
async _withRetry(apiCall, operationName = 'API call', trackRetries = false) {
let lastError = null;
let retryCount = 0;
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
try {
const result = await apiCall();
return trackRetries ? { result, retryCount } : result;
} catch (error) {
lastError = error;
if (this._isRetryableError(error) && attempt < MAX_RETRIES) {
retryCount++;
const delay = this._getRetryDelay(error, attempt);
console.log(`${operationName} failed (attempt ${attempt}/${MAX_RETRIES}). ` +
`Retrying in ${delay}ms... Error: ${error.message || error.status || error.code}`);
await this._sleep(delay);
continue;
}
throw error;
}
}
throw lastError;
}
// ---------- Sync logic ----------
async syncFileTwoWay(filePath, remotePath, prioritizeRemote = false) {
const provider = this.providerName;
if (!fs.existsSync(filePath)) {
console.warn(`File ${filePath} does not exist!`);
return -5;
}
let isSynced = null;
try {
isSynced = await this.isFileSynced(filePath, remotePath);
} catch (e) {
console.log(e);
console.warn(`Could not determine sync status for ${filePath}`);
return -6;
}
if (isSynced) {
console.log(`File ${filePath} is already in sync with ${provider} file at ${remotePath}. Not doing anything!`);
return 0;
}
console.log(`File ${filePath} is different from file in ${provider} at ${remotePath}.`);
let remoteInfo = null;
try {
remoteInfo = await this.getRemoteFileInfo(remotePath);
} catch (e) {
console.log(e);
console.warn(`Could not retrieve remote file information for ${remotePath}`);
return -6;
}
const remoteFileExisting = remoteInfo != null;
let remoteFileNewer = false;
let remoteFileLarger = false;
if (remoteFileExisting) {
const localStat = fs.statSync(filePath);
remoteFileNewer = new Date(remoteInfo.modified) > new Date(localStat.mtime);
remoteFileLarger = remoteInfo.size > localStat.size;
if (remoteFileLarger) {
console.log(`Remote file (${remoteInfo.size} bytes) is larger than local file (${localStat.size} bytes). Will prioritize remote.`);
}
}
let returnValue = null;
if (remoteFileExisting && (remoteFileNewer || prioritizeRemote || remoteFileLarger)) {
if (prioritizeRemote) {
console.log(`We are going to prioritize the remote file ${remotePath} and download it!`);
} else if (remoteFileLarger) {
console.log('The remote file is larger than the local file. Downloading the remote file to prevent data loss.');
} else {
console.log(`The ${provider} file at ${remotePath} is newer than the local file at ${filePath}. Downloading it.`);
}
try {
await this.downloadFile(remotePath, path.dirname(filePath));
returnValue = 1;
} catch (e) {
console.log(`Got an exception while trying to download the ${provider} file ${remotePath} to replace the local file ${filePath}.`);
console.log(e);
returnValue = -1;
}
} else {
console.log(`The local file at ${filePath} is newer than the ${provider} file at ${remotePath}. Uploading local file.`);
try {
await this.uploadFile(filePath, remotePath);
returnValue = 2;
} catch (e) {
console.log(`Got an exception while trying to upload local file ${filePath} to ${provider}.`);
console.log(e);
returnValue = -2;
}
}
let syncedAfterwards = false;
try {
syncedAfterwards = await this.isFileSynced(filePath, remotePath);
} catch (e) {
console.log(e);
}
if (syncedAfterwards) {
console.log(`Local file ${filePath} in sync with ${provider} file at ${remotePath}.`);
} else {
console.warn(`Error syncing local file ${filePath} to ${provider} file at ${remotePath}`);
if (returnValue == 2 || returnValue == -2) {
// An upload was performed (or attempted) and afterwards the file is not in sync.
// This indicates a serious issue while uploading. The remote file may be corrupted.
returnValue = -4;
}
}
return returnValue;
}
}
module.exports = RemoteFileSync;
Source