Manejar errores de sincronización
While developing an application that uses Device Sync, you should set an error handler. This error handler detects and can respond to any failed sync-related API calls.
Establezca un controlador de errores en el sync_config. Cuando se produce un error, el SDK de C++ llama al controlador de errores con el objeto sync_error y la sesión de sincronización donde se produjo el error.
auto appConfig = realm::App::configuration(); appConfig.app_id = APP_ID; auto app = realm::App(appConfig); auto user = app.login(realm::App::credentials::anonymous()).get(); auto dbConfig = user.flexible_sync_configuration(); // Setting an error handler on the sync_config gives you access to // sync_session and sync_error dbConfig.sync_config().set_error_handler( [](const realm::sync_session &session, const realm::internal::bridge::sync_error &error) { std::cerr << "A sync error occurred. Message: " << error.message() << std::endl; }); auto syncRealm = realm::db(dbConfig);
Tip
For a list of common Device Sync errors and how to handle them, refer to Sync Errors in the App Services Device Sync documentation.
Restablecimiento del cliente
Al usar la Sincronización de Dispositivos, el restablecimiento del cliente es una tarea de recuperación de errores que la aplicación cliente debe realizar cuando el servidor ya no puede sincronizarse con la base de datos del dispositivo. En este caso, el dispositivo debe restablecer su base de datos a un estado que coincida con el del servidor para poder restablecer la sincronización.
When this occurs, the unsyncable database on the device may contain data that has not yet synced to the server. The SDK can attempt to recover or discard that data during the client reset process.
Para obtener más información sobre qué podría provocar que se restablezca un cliente, vaya a Restablecimientos de cliente en la documentación de Servicios de aplicaciones.
Automatic vs. Manual Client Reset
El SDK ofrece modos de restablecimiento de cliente que gestionan automáticamente la mayoría de los errores de restablecimiento de cliente. Los modos automáticos de restablecimiento de cliente restauran el archivo de base de datos del dispositivo a un estado sincronizable sin cerrar la base de datos ni perder notificaciones.
Todos los modos de reinicio del cliente excepto manual() Realizar un restablecimiento automático del cliente. Las diferencias entre los modos se basan en cómo gestionan los cambios en el dispositivo que aún no se han sincronizado con el backend.
Elige recover_unsynced_changes() para gestionar automáticamente la mayoría de los escenarios de restablecimiento del cliente. Esto intenta recuperar los cambios no sincronizados cuando ocurre un restablecimiento del cliente.
In some cases, you may want or need to set a manual client reset handler. You may want to do this if your app requires specific client reset logic that can't be handled automatically.
Specify a Client Reset Mode
El SDK de C++ proporciona la opción de especificar un manejador de restablecimiento del cliente en tu configuración de base de datos. Este gestor de restablecimiento del cliente puede tomar un client_reset_mode_base. Esta estructura te permite especificar:
Un bloque para ejecutar antes del reinicio del cliente
A block to execute after the client reset
El modo a utilizar al gestionar el restablecimiento del cliente
auto user = app.login(realm::App::credentials::anonymous()).get(); auto syncConfig = user.flexible_sync_configuration(); // Set the client reset handler with your preferred client reset mode. syncConfig.set_client_reset_handler( realm::client_reset::recover_unsynced_changes(beforeReset, afterReset)); auto syncedRealm = realm::db(syncConfig);
You can use one of the available client reset modes to specify how the SDK should attempt to resolve any unsynced data on the device during a client reset:
recover_unsynced_changes()recover_or_discard_unsynced_changes()discard_unsynced_changes()manual()
You can specify a before and after block to execute during the automatic client reset process. You might use this to perform recovery logic that is important to your application.
/* You can define blocks to call before and after the client reset occur if you need to execute specific logic, such as reporting or debugging. */ auto beforeReset = [&](realm::db before) { /* A block called after a client reset error is detected, but before the client recovery process is executed. You could use this block for any custom logic, reporting, debugging etc. You have access to the database before the client reset occurs in this block. */ }; auto afterReset = [&](realm::db device, realm::db server) { /* A block called after the client recovery process has executed. This block could be used for custom recovery, reporting, debugging etc. You have access to the database that is currently on the device - the one that can no longer sync - and the new database that has been restored from the server. */ };
Si su aplicación tiene necesidades específicas de recuperación de clientes, puede especificar el manual() modo de restablecimiento de cliente y configurar un controlador manual de restablecimiento de cliente. Puede hacerlo si su aplicación debe ejecutar una lógica personalizada específica durante un restablecimiento de cliente o si las reglas de recuperación de cliente no funcionan.
Handle Schema Changes
Client Recovery is a feature that is enabled by default when you configure Device Sync. When Client Recovery is enabled, the SDK can automatically manage the client reset process in most cases. When you make schema changes:
The client can recover unsynced changes when there are no schema changes, or non-breaking schema changes.
Al realizar cambios de esquema disruptivos, los modos de restablecimiento automático del cliente recurren a un gestor de errores manual. Puede configurar un gestor de errores de restablecimiento manual del cliente para este caso. La recuperación automática del cliente no puede ocurrir cuando su aplicación realiza cambios de esquema disruptivos.
For information on breaking vs. non-breaking schema changes, see Breaking vs. Non-Breaking Change Quick Reference.
Recuperar cambios no sincronizados
During a client reset, client applications can attempt to recover data in the synced database on the device that has not yet synced to the backend. To recover unsynced changes, Client Recovery must be enabled in your App Services App, which it is by default.
Si tu aplicación necesita recuperar cambios que no se han sincronizado, utiliza uno de estos modos de recuperación del cliente:
recover_unsynced_changes(): El cliente intenta recuperar los cambios no sincronizados. Elija esta moda cuando no desee continuar y descartar los cambios no sincronizados.recover_or_discard_unsynced_changes()El cliente primero intenta recuperar los cambios que aún no se han sincronizado. Si no puede recuperar los datos no sincronizados, descarta los cambios no sincronizados, pero continúa reiniciando el cliente automáticamente. Seleccione este modo si desea habilitar la recuperación automática del cliente para descartar los cambios no sincronizados.
auto user = app.login(realm::App::credentials::anonymous()).get(); auto syncConfig = user.flexible_sync_configuration(); // Set the client reset handler with your preferred client reset mode. syncConfig.set_client_reset_handler( realm::client_reset::recover_unsynced_changes(beforeReset, afterReset)); auto syncedRealm = realm::db(syncConfig);
There may be times when the client reset operation cannot complete in recover_unsynced_changes() mode, like when there are breaking schema changes or Client Recovery is disabled in the Device Sync configuration. To handle this case, your app can handle a client reset error in the Sync error handler. For more information, refer to the manual client reset mode section on this page.
Client Recovery Rules
Cuando la Recuperación de Cliente está habilitada, estas reglas determinan cómo se integran los objetos, incluyendo la resolución de conflictos cuando tanto el backend como el cliente realizan cambios en el mismo objeto:
Objects created locally that were not synced before client reset are synced.
Si se elimina un objeto en el servidor, pero se modifica en el cliente en recuperación, la eliminación tiene prioridad y el cliente descarta la actualización.
If an object is deleted on the recovering client, but not the server, then the client applies the server's delete instruction.
En el caso de actualizaciones conflictivas en el mismo campo, se aplica la actualización del cliente.
Descartar cambios no sincronizados
The discard_unsynced_changes() client reset mode permanently deletes all unsynced changes on the device since the last successful sync. You might use this mode when your app requires client recovery logic that is not consistent with the Device Sync client recovery rules, or when you don't want to recover unsynced data.
Do not use discard unsynced changes mode if your application cannot lose device data that has not yet synced to the backend.
To perform an automatic client reset that discards unsynced changes, use the discard_unsynced_changes() client reset mode.
auto user = app.login(realm::App::credentials::anonymous()).get(); auto syncConfig = user.flexible_sync_configuration(); // Set the client reset handler with your preferred client reset mode. syncConfig.set_client_reset_handler( realm::client_reset::discard_unsynced_changes(beforeReset, afterReset)); auto syncedRealm = realm::db(syncConfig);
Nota
Descartar con Recuperación
If you'd like to attempt to recover unsynced changes, but discard any changes that cannot be recovered, refer to the recover_or_discard_unsynced_changes() documentation in the Recover Unsynced Changes section on this page.
Es posible que, en ocasiones, la operación de restablecimiento del cliente no pueda completarse en discard_unsynced_changes() modo, como cuando se producen cambios de esquema importantes. Para solucionar este problema, la aplicación puede gestionar un error de restablecimiento del cliente en el controlador de errores de sincronización. Para obtener más información, consulte la sección "Modo de restablecimiento manual del cliente" en esta página.
Modo de restablecimiento manual del cliente
Al manual() usar el modo de restablecimiento de cliente, debe implementar un controlador de restablecimiento de cliente personalizado en el controlador de errores de sincronización. Recomendamos usar los modos de recuperación automática de cliente siempre que sea posible y elegir el manual() modo solo si la lógica de recuperación automática no es adecuada para su aplicación.
auto user = app.login(realm::App::credentials::anonymous()).get(); auto syncConfig = user.flexible_sync_configuration(); // Set the client reset handler to manual client reset mode. syncConfig.set_client_reset_handler(realm::client_reset::manual()); // Define a Sync error handler for handling the client reset. syncConfig.sync_config().set_error_handler( [&](realm::sync_session session, realm::sync_error error) { if (error.is_client_reset_requested()) { /* You might use this for reporting or to instruct the user to delete and re-install the app. */ }; }); auto syncedRealm = realm::db(syncConfig);
Si la operación de restablecimiento del cliente no puede completarse automáticamente, como cuando hay cambios de esquema disruptivos, el proceso de restablecimiento del cliente recae en el manejador de errores manual. Esto puede ocurrir en cualquiera de estos modos automáticos de restablecimiento de cliente:
recover_unsynced_changes()recover_or_discard_unsynced_changes()discard_unsynced_changes()
Recomendamos tratar el controlador manual como una herramienta para situaciones de recuperación de errores fatales en las que se recomienda a los usuarios que actualicen la aplicación o realicen alguna otra acción.
Test Client Reset Handling
Puede probar manualmente el manejo de restablecimiento del cliente de su aplicación finalizando y volviendo a habilitar la sincronización del dispositivo.
When you terminate and re-enable Sync, clients that have previously connected with Sync are unable to connect until after they perform a client reset. Terminating Sync deletes the metadata from the server that allows the client to synchronize. The client must download a new copy of the realm from the server. The server sends a client reset error to these clients. So, when you terminate Sync, you trigger the client reset condition.
To test client reset handling:
Write data from a client application and wait for it to synchronize.
Termina y vuelve a habilitar Device Sync.
Ejecuta la aplicación cliente nuevamente. La aplicación debería obtener un error de restablecimiento del cliente cuando intente conectarse al servidor.
Advertencia
Mientras itera sobre la gestión del restablecimiento de clientes en su aplicación cliente, es posible que tenga que finalizar y volver a habilitar la sincronización repetidamente. Esto impide que todos los clientes existentes puedan sincronizar hasta después de completar un restablecimiento. Para evitar esto en producción, pruebe la gestión del restablecimiento de clientes en un entorno de desarrollo.