Google Drive Sync
Relevant source files
The following files were used as context for generating this wiki page:
- src/utils/google-drive/sync.ts
- src/utils/google-drive/api.ts
- src/utils/google-drive/auth.ts
- src/entrypoints/options/pages/config/google-drive-sync/index.tsx
- src/entrypoints/options/pages/config/google-drive-sync/components/conflict-resolution-dialog.tsx
- src/utils/google-drive/conflict-merge.ts
- wxt.config.ts
- src/utils/google-drive/tests/sync.test.ts
The Google Drive Sync feature enables users to back up and synchronize their Read Frog extension configuration across multiple devices. It leverages the Google Drive App Data folder, a special sandboxed folder that is only accessible by the application, ensuring user privacy as the data does not appear in their visible Google Drive files. The system is designed to handle initial syncs, one-way updates, and complex concurrent modifications through a user-driven conflict resolution mechanism.
This feature is composed of several key modules: authentication, API interaction, core synchronization logic, and a user interface for triggering sync and resolving conflicts.
Architecture
The Google Drive Sync architecture is divided into UI components, core logic services, and API wrappers. The user initiates a sync from the options page, which triggers the syncConfig function. This function orchestrates the entire process, from fetching local and remote states to handling conflicts and updating data.
The following diagram illustrates the high-level component interaction.
Authentication
Authentication is handled by the browser's identity API. The extension requests the necessary permissions in its manifest file.
OAuth2 Scopes
The extension requests a specific, restricted scope to access only its own application data folder in Google Drive. This is configured in the project's manifest.
- Scope:
https://www.googleapis.com/auth/drive.appdata
This ensures the extension cannot access any other files in the user's Google Drive.
Sources: wxt.config.ts:41-44
Access Token Management
The auth.ts module is responsible for managing the OAuth2 token.
getValidAccessToken(): This function is the central point for obtaining a valid token. It likely usesbrowser.identity.getAuthToken()to retrieve a cached token or initiate an interactive sign-in flow if no valid token is available.clearAccessToken(): If an API call fails with a 401 Unauthorized error, this function is called to clear the invalid token, forcing a re-authentication on the next attempt.
Sources: src/utils/google-drive/auth.ts, src/utils/google-drive/api.ts:36-38
Core Synchronization Logic
The main synchronization logic resides in syncConfig() within sync.ts. It follows a state-based decision tree to determine the correct action (upload, download, merge, or prompt for conflict resolution).
This flowchart shows the decision process within the syncConfig function.
Key Data Structures
The sync process relies on several pieces of data stored locally and remotely.
| Key / Filename | Location | Description |
|---|---|---|
read-frog-config.json | Google Drive | The JSON file stored in the App Data folder, containing the config and metadata. |
LAST_SYNC_TIME_STORAGE_KEY | localstorage | A timestamp of the last successful sync operation. Used to detect concurrent changes. |
LAST_SYNCED_CONFIG_STORAGE_KEY | localstorage | A snapshot of the configuration object at the time of the last sync. This serves as the "base" for 3-way merges. |
Sources: src/utils/google-drive/sync.ts:12,71,83
The data stored in Google Drive has a specific structure, ModifiedConfigData.
export interface ModifiedConfigData extends ConfigBackup {
lastModified: number
}
// ConfigBackup contains:
// {
// 'read-frog-config': Config;
// 'read-frog-config-schema-version': number;
// }
Sources: src/utils/google-drive/sync.ts:14-17
Conflict Detection and Resolution
A conflict occurs when both the local and remote configurations have been modified since the last sync. The system is designed to automatically merge non-conflicting changes and prompt the user to resolve fields that have been changed in both places.
Conflict Detection
- The
syncConfigfunction checks iflocal.lastModified > lastSyncTimeandremote.lastModified > lastSyncTime. - If true, it retrieves the
LAST_SYNCED_CONFIG_STORAGE_KEYto use as the common ancestor (base). - It calls
detectConflicts(base, local, remote)fromconflict-merge.tsto perform a 3-way comparison. - If
detectConflictsreturns an emptyconflictsarray, an auto-merge is performed. - If conflicts exist, a
ConfigConflictErroris thrown, containing thebase,local, andremoteconfig objects.
Sources: src/utils/google-drive/sync.ts:271-309, src/utils/google-drive/conflict-merge.ts
Conflict Resolution Flow
When a ConfigConflictError is caught by the UI, it initiates a user-driven resolution process.
This sequence diagram shows the flow from a user-initiated sync to a resolved state.
The ConflictResolutionDialog component provides a UI for the user to select which version (local or remote) to keep for each conflicting field. It offers options to "Use All Local" or "Use All Remote" for quick resolution. Once all conflicts are resolved, the user can confirm, which triggers syncMergedConfig to upload the final, merged configuration.
Google Drive API Interaction
All direct communication with the Google Drive API is encapsulated in src/utils/google-drive/api.ts. These functions handle constructing the request, adding the auth header, and making the fetch call. All file operations are targeted at the appDataFolder.
| Function | HTTP Method | Endpoint | Description |
|---|---|---|---|
findFileInAppData | GET | /drive/v3/files | Searches for the read-frog-config.json file in the app data folder. |
downloadFile | GET | /drive/v3/files/{fileId}?alt=media | Downloads the content of a file by its ID. |
uploadFile (Create) | POST | /upload/drive/v3/files?uploadType=multipart | Creates a new file with content in the app data folder. |
uploadFile (Update) | PATCH | /upload/drive/v3/files/{fileId}?uploadType=multipart | Updates the content and metadata of an existing file. |
deleteFile | DELETE | /drive/v3/files/{fileId} | Deletes a file by its ID. |
Sources: src/utils/google-drive/api.ts
User Interface
The user interacts with the sync feature through the options page.
GoogleDriveSyncCard: A React component on the settings page that contains the "Sync to Google Drive" button. It manages theisSyncingstate and displays the last sync time. It is responsible for callingsyncConfigand catching aConfigConflictErrorto launch the resolution dialog.
Sources: [src/entrypoints/options/pages/config/google-drive-sync/index.tsx]ConflictResolutionDialog: A modal dialog that appears when conflicts are detected. It uses aJsonTreeViewcomponent to render the configuration object, highlighting conflicting fields and allowing the user to choose between local and remote values. The state of user resolutions is managed via Jotai atoms (conflictResolutionsAtom).
Sources: [src/entrypoints/options/pages/config/google-drive-sync/components/conflict-resolution-dialog.tsx]