src/app/core/database/pouchdb/pouchdb-corruption-recovery.service.ts
Handles user-facing recovery flows when PouchDB IndexedDB corruption is detected. Shows targeted dialogs and optionally resets the local database to a clean state.
| providedIn | root |
Methods |
| Async handleKnownMultiTabCorruption | ||||||||||||||||||||
handleKnownMultiTabCorruption(err: unknown, logMessage: string, context?: Record
|
||||||||||||||||||||
|
occurrences of the problem in one issue (see
Parameters :
Returns :
Promise<boolean>
whether it was a known corruption (and so is reported) |
| Async promptMultiTabWarningDialog |
promptMultiTabWarningDialog()
|
|
Returns :
Promise<void>
|
| Async promptResetApplicationDialog |
promptResetApplicationDialog()
|
|
Returns :
Promise<void>
|
import { Injectable, inject } from "@angular/core";
import { ConfirmationDialogService } from "#src/app/core/common-components/confirmation-dialog/confirmation-dialog.service";
import {
CustomYesNoButtons,
OkButton,
} from "#src/app/core/common-components/confirmation-dialog/confirmation-dialog/confirmation-dialog.component";
import { LocalDeviceResetService } from "../local-device-reset.service";
import { Logging } from "../../logging/logging.service";
import { environment } from "../../../../environments/environment";
import { SessionType } from "../../session/session-type";
import {
hasOutdatedSequenceCounter,
isAbortedTransaction,
} from "./indexeddb-sequence-check";
/**
* Handles user-facing recovery flows when PouchDB IndexedDB corruption is detected.
* Shows targeted dialogs and optionally resets the local database to a clean state.
*/
@Injectable({ providedIn: "root" })
export class PouchdbCorruptionRecoveryService {
private readonly confirmationDialog = inject(ConfirmationDialogService);
private readonly localDeviceReset = inject(LocalDeviceResetService);
private warningDialogOpen = false;
private resetDialogOpen = false;
/**
* Shared closing line of both recovery dialogs.
* Must stay a getter: this service is in the eagerly imported graph of main.ts, so a
* module-level `$localize` would run before `initLanguage()` and never be translated.
*/
private get improvementsPlannedHint(): string {
return $localize`:local db corruption dialog improvements hint:We are working on improvements to allow this in the future.`;
}
async promptMultiTabWarningDialog(): Promise<void> {
if (environment.session_type === SessionType.online) {
return;
}
if (this.warningDialogOpen) {
return;
}
this.warningDialogOpen = true;
try {
await this.confirmationDialog.getConfirmation(
$localize`:multi-tab warning dialog title:Multiple Tabs Open`,
$localize`:multi-tab warning dialog text:The app is open in multiple tabs, which can break the local database.
Please close the other tabs and try again to avoid local database corruption.` +
"\n\n" +
this.improvementsPlannedHint,
OkButton,
false,
);
} finally {
this.warningDialogOpen = false;
}
}
async promptResetApplicationDialog(): Promise<void> {
if (this.resetDialogOpen) {
return;
}
this.resetDialogOpen = true;
try {
const shouldReset = await this.confirmationDialog.getConfirmation(
$localize`:local db corruption dialog title:Local Database Needs Reset`,
$localize`:local db corruption dialog text:The local database appears corrupted and saving is no longer reliable.
This can happen after using multiple tabs in parallel.` +
"\n" +
this.improvementsPlannedHint,
CustomYesNoButtons(
$localize`:local db corruption dialog button reset:Reset Application`,
$localize`:Confirmation dialog Cancel:Cancel`,
),
false,
);
if (shouldReset === true) {
this.resetApplication();
}
} finally {
this.resetDialogOpen = false;
}
}
private resetApplication() {
// deleting ALL local data (incl. possibly unsynced docs) - log for traceability of possible data loss
Logging.warn(
"Resetting application data after suspected local database corruption (user confirmed)",
);
this.localDeviceReset.markResetPendingAndReload();
}
/**
* @param err the error to check and, if it is a known corruption, report
* @param logMessage what failed - static, so that remote monitoring keeps all
* occurrences of the problem in one issue (see `core/logging/README.md`)
* @param context which database and other varying details, reported as
* structured data alongside the message rather than interpolated into it
* @param localDb the local database that failed: checked for the corruption
* if PouchDB only reports an aborted transaction (see `indexeddb-sequence-check.ts`)
* @returns whether it was a known corruption (and so is reported)
*/
async handleKnownMultiTabCorruption(
err: unknown,
logMessage: string,
context?: Record<string, unknown>,
localDb?: PouchDB.Database,
): Promise<boolean> {
if (
!isKnownMultiTabDatabaseCorruption(err) &&
!(
localDb &&
isAbortedTransaction(err) &&
(await hasOutdatedSequenceCounter(localDb))
)
) {
return false;
}
Logging.warn(logMessage, err, ...(context ? [context] : []));
this.promptResetApplicationDialog().catch((callbackError) =>
Logging.warn("onKnownMultiTabCorruption callback failed", callbackError),
);
return true;
}
}
/**
* Detect IndexedDB/PouchDB corruption symptoms commonly observed when the app
* is used in multiple tabs with concurrent writes.
*
* Only signals specific to this corruption are matched, as it leads to offering
* a reset of the local data: a "transaction was aborted" or an `unknown_error`
* also follows other failures, e.g. a document too deeply nested to store.
* For those, the database itself is checked (see `hasOutdatedSequenceCounter`).
*/
export function isKnownMultiTabDatabaseCorruption(error: unknown): boolean {
const text = errorToText(error).toLowerCase();
return (
text.includes("database has a global failure") ||
(text.includes("constrainterror") && text.includes("seq"))
);
}
/**
* The whole error serialized, not only its name, message and reason (as
* `errorText` of `backend-response.ts`): the IndexedDB failure may be in nested
* properties, e.g. in the result array of a `bulkDocs`.
*/
function errorToText(error: unknown): string {
if (typeof error === "string") return error;
const prefix =
error instanceof Error ? `${error.name} ${error.message} ` : "";
try {
return prefix + JSON.stringify(error ?? "");
} catch {
// e.g. a circular structure: classified without its extra properties
return prefix;
}
}