<commit_before>/* global cozy emit */
import { clientRevokedMsg } from './cozy-helper'

export const startReplication = async (
  hasIndexes,
  hasFinishedFirstReplication,
  firstReplicationFinished,
  refreshFolder,
  revokeClient,
  indexesCreated
) => {
  try {
    if (!hasIndexes) {
      const db = cozy.client.offline.getDatabase('io.cozy.files')
      const folderIndex = await db.createIndex({
        index: { fields: ['dir_id', 'type', 'name'] }
      })
      const ddoc = {
        _id: '_design/my_index',
        views: {
          recent_files: {
            map: function(doc) {
              if (!doc.trashed) emit(doc.updated_at)
            }.toString()
          }
        }
      }
      await db.put(ddoc)
      indexesCreated({
        folders: folderIndex.id,
        recent: 'my_index/recent_files'
      })
    }

    if (!hasFinishedFirstReplication) {
      await startFirstReplication()
      console.log('End of first replication')
      firstReplicationFinished()
    }

    /* const docsWritten = */ await startRepeatedReplication()
    cozy.client.settings.updateLastSync()
    // NB: this refresh breaks the recent view if it is displayed during replication
    // if (docsWritten !== 0) refreshFolder()
  } catch (err) {
    if (
      err.message === clientRevokedMsg ||
      err.error === 'code=400, message=Invalid JWT token'
    ) {
      console.warn('The device is not connected to your server anymore')
      revokeClient()
    } else if (err.message === 'ETIMEDOUT') {
      console.log('replcation timed out')
    } else {
      console.warn(err)
    }<commit_msg>fix: Warming up the Pouch indexes before querying results in a better UX<commit_after>/* global cozy emit */
import { clientRevokedMsg } from './cozy-helper'

export const startReplication = async (
  hasIndexes,
  hasFinishedFirstReplication,
  firstReplicationFinished,
  refreshFolder,
  revokeClient,
  indexesCreated
) => {
  try {
    let db, folderIndex
    if (!hasIndexes) {
      db = cozy.client.offline.getDatabase('io.cozy.files')
      folderIndex = await db.createIndex({
        index: { fields: ['dir_id', 'type', 'name'] }
      })
      const ddoc = {
        _id: '_design/my_index',
        views: {
          recent_files: {
            map: function(doc) {
              if (!doc.trashed) emit(doc.updated_at)
            }.toString()
          }
        }
      }
      await db.put(ddoc)
      indexesCreated({
        folders: folderIndex.id,
        recent: 'my_index/recent_files'
      })
    }

    if (!hasFinishedFirstReplication) {
      await startFirstReplication()
      console.log('End of first replication, warming up indexes')
      // we execute a first query so that the index is really created
      await db.query('my_index/recent_files', {
        limit: 0
      })
      // not sure this one is really necessary...
      await db.find({
        selector: {
          dir_id: { $gte: null },
          name: { $gte: null },
          type: { $gte: null }
        },
        use_index: folderIndex.id,
        limit: 0
      })
      console.log('indexes ready')
      firstReplicationFinished()
    }

    /* const docsWritten = */ await startRepeatedReplication()
    cozy.client.settings.updateLastSync()
    // NB: this refresh breaks the recent view if it is displayed during replication
    // if (docsWritten !== 0) refreshFolder()
  } catch (err) {
    if (
      err.message === clientRevokedMsg ||
      err.error === 'code=400, message=Invalid JWT token'
    ) {
      console.warn('The device is not connected to your server anymore')
      revokeClient()
    } else if (err.message === 'ETIMEDOUT') {
      console.log('replcation timed out')
    } else {
      console.warn(err)
    }
{'fraction_non_alphanumeric': 0.11697308819610978, 'fraction_numerical': 0.002664535038635758, 'mean_word_length': 2.290096406660824, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5377806', 'n_tokens_mistral': 1153, 'n_tokens_neox': 1116, 'n_words': 281}