diff --git a/src/db-admin/health-legacy.ts b/src/db-admin/health-legacy.ts index 3601606..ad4fef5 100644 --- a/src/db-admin/health-legacy.ts +++ b/src/db-admin/health-legacy.ts @@ -26,13 +26,12 @@ export const watchDbLegacy = async () => { const [status, setStatus] = createSignal({}); const [syncState, setSyncState] = createSignal({}); + const [remoteUrl, setRemoteUrl] = createSignal(); const updateStatus = async () => { const dbInfo = await db.info(); const localDbInfo = await localDb.info(); - const remoteDbInfo = remoteDb - ? await remoteDb.info() - : undefined; + const remoteDbInfo = remoteDb ? await remoteDb.info() : undefined; const tasks = PouchDB.activeTasks.list(); const newStatus = { ...status(), @@ -107,6 +106,59 @@ export const watchDbLegacy = async () => { const timerId = setInterval(updateStatus, 15000); + const findDocumentsWithoutOrigin = async () => { + const allDocs = await db.allDocs({ include_docs: true }); + return allDocs.rows + .filter((row: any) => !row.doc.origin) + .map((row: any) => row.doc._id); + }; + + createEffect(async () => { + if (!!state().remoteUrl && remoteUrl() !== state().remoteUrl) { + setRemoteUrl(state().remoteUrl); + // Check documents and update without origin + const documentsWithoutOrigin = await findDocumentsWithoutOrigin(); + console.log({ + caller: 'watchDbLegacy / addOrigin', + remoteUrl: remoteUrl(), + nbDocumentsWithoutOrigin: documentsWithoutOrigin.length, + }); + for (const docId of documentsWithoutOrigin) { + while (true) { + await sleep(100); + const doc = await db.get(docId); + console.log({ + caller: 'watchDbLegacy / addOrigin', + remoteUrl: remoteUrl(), + docId, + doc, + }); + try { + db.put({ ...doc, origin: remoteUrl() }); + break; + } catch (error) { + if (error.name === 'conflict') { + console.log({ + caller: 'watchDbLegacy / addOrigin', + docId, + doc, + error, + }); + } else { + console.error({ + caller: 'watchDbLegacy / addOrigin', + docId, + doc, + error, + }); + break; + } + } + } + } + } + }); + // db.compact(); const openIDb = (name: string) => new Promise((resolve, reject) => { diff --git a/src/db/lib.ts b/src/db/lib.ts index c32e273..11adfe7 100644 --- a/src/db/lib.ts +++ b/src/db/lib.ts @@ -1,4 +1,5 @@ import { cloneDeep } from 'lodash'; +import { state } from '../db-admin/health-legacy'; declare global { var localDb: any; @@ -25,6 +26,8 @@ export const put = async ( _id, _rev: current._rev, type, + shared: current.shared, + origin: current.origin ?? state().remoteUrl, doc: update(current.doc), }; await targetDb.put(putDoc);