summaryrefslogtreecommitdiff
path: root/lib/workers/dmpWorker.js
blob: 7b5439c7d5ec7b880530def8e1a1b667b2b6ba93 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
'use strict'
// external modules
const DiffMatchPatch = require('diff-match-patch')
const dmp = new DiffMatchPatch()

// core
const logger = require('../logger')

process.on('message', function (data) {
  if (!data || !data.msg || !data.cacheKey) {
    return logger.error('dmp worker error: not enough data')
  }
  switch (data.msg) {
    case 'create patch':
      if (
        !Object.prototype.hasOwnProperty.call(data, 'lastDoc') ||
        !Object.prototype.hasOwnProperty.call(data, 'currDoc')
      ) {
        return logger.error(
          'dmp worker error: not enough data on create patch'
        )
      }
      try {
        const patch = createPatch(data.lastDoc, data.currDoc)
        process.send({
          msg: 'check',
          result: patch,
          cacheKey: data.cacheKey
        })
      } catch (err) {
        logger.error('dmp worker error', err)
        process.send({
          msg: 'error',
          error: err,
          cacheKey: data.cacheKey
        })
      }
      break
    case 'get revision':
      if (
        !Object.prototype.hasOwnProperty.call(data, 'revisions') ||
        !Object.prototype.hasOwnProperty.call(data, 'count')
      ) {
        return logger.error(
          'dmp worker error: not enough data on get revision'
        )
      }
      try {
        const result = getRevision(data.revisions, data.count)
        process.send({
          msg: 'check',
          result: result,
          cacheKey: data.cacheKey
        })
      } catch (err) {
        logger.error('dmp worker error', err)
        process.send({
          msg: 'error',
          error: err,
          cacheKey: data.cacheKey
        })
      }
      break
  }
})

function createPatch (lastDoc, currDoc) {
  const msStart = new Date().getTime()
  const diff = dmp.diff_main(lastDoc, currDoc)
  let patch = dmp.patch_make(lastDoc, diff)
  patch = dmp.patch_toText(patch)
  const msEnd = new Date().getTime()
  logger.debug(patch)
  logger.debug(msEnd - msStart + 'ms')
  return patch
}

function getRevision (revisions, count) {
  const msStart = new Date().getTime()
  let startContent = null
  let lastPatch = []
  let applyPatches = []
  let authorship = []
  if (count <= Math.round(revisions.length / 2)) {
    // start from top to target
    for (let i = 0; i < count; i++) {
      const revision = revisions[i]
      if (i === 0) {
        startContent = revision.content || revision.lastContent
      }
      if (i !== count - 1) {
        const patch = dmp.patch_fromText(revision.patch)
        applyPatches = applyPatches.concat(patch)
      }
      lastPatch = revision.patch
      authorship = revision.authorship
    }
    // swap DIFF_INSERT and DIFF_DELETE to achieve unpatching
    for (let i = 0, l = applyPatches.length; i < l; i++) {
      for (let j = 0, m = applyPatches[i].diffs.length; j < m; j++) {
        const diff = applyPatches[i].diffs[j]
        if (diff[0] === DiffMatchPatch.DIFF_INSERT) {
          diff[0] = DiffMatchPatch.DIFF_DELETE
        } else if (diff[0] === DiffMatchPatch.DIFF_DELETE) {
          diff[0] = DiffMatchPatch.DIFF_INSERT
        }
      }
    }
  } else {
    // start from bottom to target
    const l = revisions.length - 1
    for (let i = l; i >= count - 1; i--) {
      const revision = revisions[i]
      if (i === l) {
        startContent = revision.lastContent
        authorship = revision.authorship
      }
      if (revision.patch) {
        const patch = dmp.patch_fromText(revision.patch)
        applyPatches = applyPatches.concat(patch)
      }
      lastPatch = revision.patch
      authorship = revision.authorship
    }
  }
  try {
    const finalContent = dmp.patch_apply(applyPatches, startContent)[0]
    const data = {
      content: finalContent,
      patch: dmp.patch_fromText(lastPatch),
      authorship: authorship
    }
    const msEnd = new Date().getTime()
    logger.debug(msEnd - msStart + 'ms')
    return data
  } catch (err) {
    throw new Error(err)
  }
}

// log uncaught exception
process.on('uncaughtException', function (err) {
  logger.error('An uncaught exception has occured.')
  logger.error(err)
  logger.error('Process will exit now.')
  process.exit(1)
})