summaryrefslogtreecommitdiff
path: root/lib/models/revision.js
blob: 69a2bf96705f80766f6fa8d437597738a0199c66 (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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
'use strict'
// external modules
var Sequelize = require('sequelize')
var async = require('async')
var moment = require('moment')
var childProcess = require('child_process')
var shortId = require('shortid')
var path = require('path')

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

var dmpWorker = createDmpWorker()
var dmpCallbackCache = {}

function createDmpWorker () {
  var worker = childProcess.fork(path.resolve(__dirname, '../workers/dmpWorker.js'), {
    stdio: 'ignore'
  })
  logger.debug('dmp worker process started')
  worker.on('message', function (data) {
    if (!data || !data.msg || !data.cacheKey) {
      return logger.error('dmp worker error: not enough data on message')
    }
    var cacheKey = data.cacheKey
    switch (data.msg) {
      case 'error':
        dmpCallbackCache[cacheKey](data.error, null)
        break
      case 'check':
        dmpCallbackCache[cacheKey](null, data.result)
        break
    }
    delete dmpCallbackCache[cacheKey]
  })
  worker.on('close', function (code) {
    dmpWorker = null
    logger.debug(`dmp worker process exited with code ${code}`)
  })
  return worker
}

function sendDmpWorker (data, callback) {
  if (!dmpWorker) dmpWorker = createDmpWorker()
  var cacheKey = Date.now() + '_' + shortId.generate()
  dmpCallbackCache[cacheKey] = callback
  data = Object.assign(data, {
    cacheKey: cacheKey
  })
  dmpWorker.send(data)
}

module.exports = function (sequelize, DataTypes) {
  var Revision = sequelize.define('Revision', {
    id: {
      type: DataTypes.UUID,
      primaryKey: true,
      defaultValue: Sequelize.UUIDV4
    },
    patch: {
      type: DataTypes.TEXT('long'),
      get: function () {
        return sequelize.processData(this.getDataValue('patch'), '')
      },
      set: function (value) {
        this.setDataValue('patch', sequelize.stripNullByte(value))
      }
    },
    lastContent: {
      type: DataTypes.TEXT('long'),
      get: function () {
        return sequelize.processData(this.getDataValue('lastContent'), '')
      },
      set: function (value) {
        this.setDataValue('lastContent', sequelize.stripNullByte(value))
      }
    },
    content: {
      type: DataTypes.TEXT('long'),
      get: function () {
        return sequelize.processData(this.getDataValue('content'), '')
      },
      set: function (value) {
        this.setDataValue('content', sequelize.stripNullByte(value))
      }
    },
    length: {
      type: DataTypes.INTEGER
    },
    authorship: {
      type: DataTypes.TEXT('long'),
      get: function () {
        return sequelize.processData(this.getDataValue('authorship'), [], JSON.parse)
      },
      set: function (value) {
        this.setDataValue('authorship', value ? JSON.stringify(value) : value)
      }
    }
  }, {
    classMethods: {
      associate: function (models) {
        Revision.belongsTo(models.Note, {
          foreignKey: 'noteId',
          as: 'note',
          constraints: false,
          onDelete: 'CASCADE',
          hooks: true
        })
      },
      getNoteRevisions: function (note, callback) {
        Revision.findAll({
          where: {
            noteId: note.id
          },
          order: [['createdAt', 'DESC']]
        }).then(function (revisions) {
          var data = []
          for (var i = 0, l = revisions.length; i < l; i++) {
            var revision = revisions[i]
            data.push({
              time: moment(revision.createdAt).valueOf(),
              length: revision.length
            })
          }
          callback(null, data)
        }).catch(function (err) {
          callback(err, null)
        })
      },
      getPatchedNoteRevisionByTime: function (note, time, callback) {
        // find all revisions to prepare for all possible calculation
        Revision.findAll({
          where: {
            noteId: note.id
          },
          order: [['createdAt', 'DESC']]
        }).then(function (revisions) {
          if (revisions.length <= 0) return callback(null, null)
          // measure target revision position
          Revision.count({
            where: {
              noteId: note.id,
              createdAt: {
                $gte: time
              }
            },
            order: [['createdAt', 'DESC']]
          }).then(function (count) {
            if (count <= 0) return callback(null, null)
            sendDmpWorker({
              msg: 'get revision',
              revisions: revisions,
              count: count
            }, callback)
          }).catch(function (err) {
            return callback(err, null)
          })
        }).catch(function (err) {
          return callback(err, null)
        })
      },
      checkAllNotesRevision: function (callback) {
        Revision.saveAllNotesRevision(function (err, notes) {
          if (err) return callback(err, null)
          if (!notes || notes.length <= 0) {
            return callback(null, notes)
          } else {
            Revision.checkAllNotesRevision(callback)
          }
        })
      },
      saveAllNotesRevision: function (callback) {
        sequelize.models.Note.findAll({
          // query all notes that need to save for revision
          where: {
            $and: [
              {
                lastchangeAt: {
                  $or: {
                    $eq: null,
                    $and: {
                      $ne: null,
                      $gt: sequelize.col('createdAt')
                    }
                  }
                }
              },
              {
                savedAt: {
                  $or: {
                    $eq: null,
                    $lt: sequelize.col('lastchangeAt')
                  }
                }
              }
            ]
          }
        }).then(function (notes) {
          if (notes.length <= 0) return callback(null, notes)
          var savedNotes = []
          async.each(notes, function (note, _callback) {
            // revision saving policy: note not been modified for 5 mins or not save for 10 mins
            if (note.lastchangeAt && note.savedAt) {
              var lastchangeAt = moment(note.lastchangeAt)
              var savedAt = moment(note.savedAt)
              if (moment().isAfter(lastchangeAt.add(5, 'minutes'))) {
                savedNotes.push(note)
                Revision.saveNoteRevision(note, _callback)
              } else if (lastchangeAt.isAfter(savedAt.add(10, 'minutes'))) {
                savedNotes.push(note)
                Revision.saveNoteRevision(note, _callback)
              } else {
                return _callback(null, null)
              }
            } else {
              savedNotes.push(note)
              Revision.saveNoteRevision(note, _callback)
            }
          }, function (err) {
            if (err) {
              return callback(err, null)
            }
            // return null when no notes need saving at this moment but have delayed tasks to be done
            var result = ((savedNotes.length === 0) && (notes.length > savedNotes.length)) ? null : savedNotes
            return callback(null, result)
          })
        }).catch(function (err) {
          return callback(err, null)
        })
      },
      saveNoteRevision: function (note, callback) {
        Revision.findAll({
          where: {
            noteId: note.id
          },
          order: [['createdAt', 'DESC']]
        }).then(function (revisions) {
          if (revisions.length <= 0) {
            // if no revision available
            Revision.create({
              noteId: note.id,
              lastContent: note.content ? note.content : '',
              length: note.content ? note.content.length : 0,
              authorship: note.authorship
            }).then(function (revision) {
              Revision.finishSaveNoteRevision(note, revision, callback)
            }).catch(function (err) {
              return callback(err, null)
            })
          } else {
            var latestRevision = revisions[0]
            var lastContent = latestRevision.content || latestRevision.lastContent
            var content = note.content
            sendDmpWorker({
              msg: 'create patch',
              lastDoc: lastContent,
              currDoc: content
            }, function (err, patch) {
              if (err) logger.error('save note revision error', err)
              if (!patch) {
                // if patch is empty (means no difference) then just update the latest revision updated time
                latestRevision.changed('updatedAt', true)
                latestRevision.update({
                  updatedAt: Date.now()
                }).then(function (revision) {
                  Revision.finishSaveNoteRevision(note, revision, callback)
                }).catch(function (err) {
                  return callback(err, null)
                })
              } else {
                Revision.create({
                  noteId: note.id,
                  patch: patch,
                  content: note.content,
                  length: note.content.length,
                  authorship: note.authorship
                }).then(function (revision) {
                  // clear last revision content to reduce db size
                  latestRevision.update({
                    content: null
                  }).then(function () {
                    Revision.finishSaveNoteRevision(note, revision, callback)
                  }).catch(function (err) {
                    return callback(err, null)
                  })
                }).catch(function (err) {
                  return callback(err, null)
                })
              }
            })
          }
        }).catch(function (err) {
          return callback(err, null)
        })
      },
      finishSaveNoteRevision: function (note, revision, callback) {
        note.update({
          savedAt: revision.updatedAt
        }).then(function () {
          return callback(null, revision)
        }).catch(function (err) {
          return callback(err, null)
        })
      }
    }
  })

  return Revision
}