PackManager.coffee 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. async = require "async"
  2. _ = require "underscore"
  3. {db, ObjectId, BSON} = require "./mongojs"
  4. logger = require "logger-sharelatex"
  5. LockManager = require "./LockManager"
  6. MongoAWS = require "./MongoAWS"
  7. Metrics = require "./Metrics"
  8. ProjectIterator = require "./ProjectIterator"
  9. # Sharejs operations are stored in a 'pack' object
  10. #
  11. # e.g. a single sharejs update looks like
  12. #
  13. # {
  14. # "doc_id" : 549dae9e0a2a615c0c7f0c98,
  15. # "project_id" : 549dae9c0a2a615c0c7f0c8c,
  16. # "op" : [ {"p" : 6981, "d" : "?" } ],
  17. # "meta" : { "user_id" : 52933..., "start_ts" : 1422310693931, "end_ts" : 1422310693931 },
  18. # "v" : 17082
  19. # }
  20. #
  21. # and a pack looks like this
  22. #
  23. # {
  24. # "doc_id" : 549dae9e0a2a615c0c7f0c98,
  25. # "project_id" : 549dae9c0a2a615c0c7f0c8c,
  26. # "pack" : [ U1, U2, U3, ...., UN],
  27. # "meta" : { "user_id" : 52933..., "start_ts" : 1422310693931, "end_ts" : 1422310693931 },
  28. # "v" : 17082
  29. # "v_end" : ...
  30. # }
  31. #
  32. # where U1, U2, U3, .... are single updates stripped of their
  33. # doc_id and project_id fields (which are the same for all the
  34. # updates in the pack).
  35. #
  36. # The pack itself has v and meta fields, this makes it possible to
  37. # treat packs and single updates in a similar way.
  38. #
  39. # The v field of the pack itself is from the first entry U1, the
  40. # v_end field from UN. The meta.end_ts field of the pack itself is
  41. # from the last entry UN, the meta.start_ts field from U1.
  42. DAYS = 24 * 3600 * 1000 # one day in milliseconds
  43. module.exports = PackManager =
  44. MAX_SIZE: 1024*1024 # make these configurable parameters
  45. MAX_COUNT: 1024
  46. insertCompressedUpdates: (project_id, doc_id, lastUpdate, newUpdates, temporary, callback = (error) ->) ->
  47. return callback() if newUpdates.length == 0
  48. # never append permanent ops to a pack that will expire
  49. lastUpdate = null if lastUpdate?.expiresAt? and not temporary
  50. updatesToFlush = []
  51. updatesRemaining = newUpdates.slice()
  52. n = lastUpdate?.n || 0
  53. sz = lastUpdate?.sz || 0
  54. while updatesRemaining.length and n < PackManager.MAX_COUNT and sz < PackManager.MAX_SIZE
  55. nextUpdate = updatesRemaining[0]
  56. nextUpdateSize = BSON.calculateObjectSize(nextUpdate)
  57. if nextUpdateSize + sz > PackManager.MAX_SIZE and n > 0
  58. break
  59. n++
  60. sz += nextUpdateSize
  61. updatesToFlush.push updatesRemaining.shift()
  62. PackManager.flushCompressedUpdates project_id, doc_id, lastUpdate, updatesToFlush, temporary, (error) ->
  63. return callback(error) if error?
  64. PackManager.insertCompressedUpdates project_id, doc_id, null, updatesRemaining, temporary, callback
  65. flushCompressedUpdates: (project_id, doc_id, lastUpdate, newUpdates, temporary, callback = (error) ->) ->
  66. return callback() if newUpdates.length == 0
  67. canAppend = false
  68. # check if it is safe to append to an existing pack
  69. if lastUpdate?
  70. if not temporary and not lastUpdate.expiresAt?
  71. # permanent pack appends to permanent pack
  72. canAppend = true
  73. age = Date.now() - lastUpdate.meta?.start_ts
  74. if temporary and lastUpdate.expiresAt? and age < 1 * DAYS
  75. # temporary pack appends to temporary pack if same day
  76. canAppend = true
  77. if canAppend
  78. PackManager.appendUpdatesToExistingPack project_id, doc_id, lastUpdate, newUpdates, temporary, callback
  79. else
  80. PackManager.insertUpdatesIntoNewPack project_id, doc_id, newUpdates, temporary, callback
  81. insertUpdatesIntoNewPack: (project_id, doc_id, newUpdates, temporary, callback = (error) ->) ->
  82. first = newUpdates[0]
  83. last = newUpdates[newUpdates.length - 1]
  84. n = newUpdates.length
  85. sz = BSON.calculateObjectSize(newUpdates)
  86. newPack =
  87. project_id: ObjectId(project_id.toString())
  88. doc_id: ObjectId(doc_id.toString())
  89. pack: newUpdates
  90. n: n
  91. sz: sz
  92. meta:
  93. start_ts: first.meta.start_ts
  94. end_ts: last.meta.end_ts
  95. v: first.v
  96. v_end: last.v
  97. temporary: temporary
  98. if temporary
  99. newPack.expiresAt = new Date(Date.now() + 7 * DAYS)
  100. newPack.last_checked = new Date(Date.now() + 30 * DAYS) # never check temporary packs
  101. logger.log {project_id, doc_id, newUpdates}, "inserting updates into new pack"
  102. db.docHistory.save newPack, (err, result) ->
  103. return callback(err) if err?
  104. Metrics.inc("insert-pack-" + if temporary then "temporary" else "permanent")
  105. if temporary
  106. return callback()
  107. else
  108. PackManager.updateIndex project_id, doc_id, callback
  109. appendUpdatesToExistingPack: (project_id, doc_id, lastUpdate, newUpdates, temporary, callback = (error) ->) ->
  110. first = newUpdates[0]
  111. last = newUpdates[newUpdates.length - 1]
  112. n = newUpdates.length
  113. sz = BSON.calculateObjectSize(newUpdates)
  114. query =
  115. _id: lastUpdate._id
  116. project_id: ObjectId(project_id.toString())
  117. doc_id: ObjectId(doc_id.toString())
  118. pack: {$exists: true}
  119. update =
  120. $push:
  121. "pack": {$each: newUpdates}
  122. $inc:
  123. "n": n
  124. "sz": sz
  125. $set:
  126. "meta.end_ts": last.meta.end_ts
  127. "v_end": last.v
  128. if lastUpdate.expiresAt and temporary
  129. update.$set.expiresAt = new Date(Date.now() + 7 * DAYS)
  130. logger.log {project_id, doc_id, lastUpdate, newUpdates}, "appending updates to existing pack"
  131. db.docHistory.findAndModify {query, update, new:true, fields:{meta:1,v_end:1}}, callback
  132. # Retrieve all changes for a document
  133. getOpsByVersionRange: (project_id, doc_id, fromVersion, toVersion, callback = (error, updates) ->) ->
  134. PackManager.loadPacksByVersionRange project_id, doc_id, fromVersion, toVersion, (error) ->
  135. query = {doc_id:ObjectId(doc_id.toString())}
  136. query.v = {$lte:toVersion} if toVersion?
  137. query.v_end = {$gte:fromVersion} if fromVersion?
  138. #console.log "query:", query
  139. db.docHistory.find(query).sort {v:-1}, (err, result) ->
  140. return callback(err) if err?
  141. #console.log "getOpsByVersionRange:", err, result
  142. updates = []
  143. opInRange = (op, from, to) ->
  144. return false if fromVersion? and op.v < fromVersion
  145. return false if toVersion? and op.v > toVersion
  146. return true
  147. for docHistory in result
  148. #console.log 'adding', docHistory.pack
  149. for op in docHistory.pack.reverse() when opInRange(op, fromVersion, toVersion)
  150. op.project_id = docHistory.project_id
  151. op.doc_id = docHistory.doc_id
  152. #console.log "added op", op.v, fromVersion, toVersion
  153. updates.push op
  154. callback(null, updates)
  155. loadPacksByVersionRange: (project_id, doc_id, fromVersion, toVersion, callback) ->
  156. PackManager.getIndex doc_id, (err, indexResult) ->
  157. return callback(err) if err?
  158. indexPacks = indexResult?.packs or []
  159. packInRange = (pack, from, to) ->
  160. return false if fromVersion? and pack.v_end < fromVersion
  161. return false if toVersion? and pack.v > toVersion
  162. return true
  163. neededIds = (pack._id for pack in indexPacks when packInRange(pack, fromVersion, toVersion))
  164. if neededIds.length
  165. PackManager.fetchPacksIfNeeded project_id, doc_id, neededIds, callback
  166. else
  167. callback()
  168. fetchPacksIfNeeded: (project_id, doc_id, pack_ids, callback) ->
  169. db.docHistory.find {_id: {$in: (ObjectId(id) for id in pack_ids)}}, {_id:1}, (err, loadedPacks) ->
  170. return callback(err) if err?
  171. allPackIds = (id.toString() for id in pack_ids)
  172. loadedPackIds = (pack._id.toString() for pack in loadedPacks)
  173. packIdsToFetch = _.difference allPackIds, loadedPackIds
  174. logger.log {project_id, doc_id, loadedPackIds, allPackIds, packIdsToFetch}, "analysed packs"
  175. return callback() if packIdsToFetch.length is 0
  176. async.eachLimit packIdsToFetch, 4, (pack_id, cb) ->
  177. MongoAWS.unArchivePack project_id, doc_id, pack_id, cb
  178. , (err) ->
  179. return callback(err) if err?
  180. logger.log {project_id, doc_id}, "done unarchiving"
  181. callback()
  182. # Retrieve all changes across a project
  183. makeProjectIterator: (project_id, before, callback) ->
  184. # get all the docHistory Entries
  185. db.docHistory.find({project_id: ObjectId(project_id)},{pack:false}).sort {"meta.end_ts":-1}, (err, packs) ->
  186. return callback(err) if err?
  187. allPacks = []
  188. seenIds = {}
  189. for pack in packs
  190. allPacks.push pack
  191. seenIds[pack._id] = true
  192. db.docHistoryIndex.find {project_id: ObjectId(project_id)}, (err, indexes) ->
  193. return callback(err) if err?
  194. for index in indexes
  195. for pack in index.packs when not seenIds[pack._id]
  196. pack.project_id = index.project_id
  197. pack.doc_id = index._id
  198. pack.fromIndex = true
  199. allPacks.push pack
  200. seenIds[pack._id] = true
  201. callback(null, new ProjectIterator(allPacks, before, PackManager.getPackById))
  202. getPackById: (project_id, doc_id, pack_id, callback) ->
  203. db.docHistory.findOne {_id: pack_id}, (err, pack) ->
  204. return callback(err) if err?
  205. if not pack?
  206. MongoAWS.unArchivePack project_id, doc_id, pack_id, callback
  207. else if pack.expiresAt? and pack.temporary is false
  208. # we only need to touch the TTL when listing the changes in the project
  209. # because diffs on individual documents are always done after that
  210. PackManager.increaseTTL pack, callback
  211. # only do this for cached packs, not temporary ones to avoid older packs
  212. # being kept longer than newer ones (which messes up the last update version)
  213. else
  214. callback(null, pack)
  215. increaseTTL: (pack, callback) ->
  216. if pack.expiresAt < new Date(Date.now() + 6 * DAYS)
  217. # update cache expiry since we are using this pack
  218. db.docHistory.findAndModify {
  219. query: {_id: pack._id}
  220. update: {$set: {expiresAt: new Date(Date.now() + 7 * DAYS)}}
  221. }, (err) ->
  222. return callback(err, pack)
  223. else
  224. callback(null, pack)
  225. # Manage docHistoryIndex collection
  226. getIndex: (doc_id, callback) ->
  227. db.docHistoryIndex.findOne {_id:ObjectId(doc_id.toString())}, callback
  228. getPackFromIndex: (doc_id, pack_id, callback) ->
  229. db.docHistoryIndex.findOne {_id:ObjectId(doc_id.toString()), "packs._id": pack_id}, {"packs.$":1}, callback
  230. getLastPackFromIndex: (doc_id, callback) ->
  231. db.docHistoryIndex.findOne {_id: ObjectId(doc_id.toString())}, {packs:{$slice:-1}}, (err, indexPack) ->
  232. return callback(err) if err?
  233. return callback() if not indexPack?
  234. callback(null,indexPack[0])
  235. getIndexWithKeys: (doc_id, callback) ->
  236. PackManager.getIndex doc_id, (err, index) ->
  237. return callback(err) if err?
  238. return callback() if not index?
  239. for pack in index?.packs or []
  240. index[pack._id] = pack
  241. callback(null, index)
  242. initialiseIndex: (project_id, doc_id, callback) ->
  243. PackManager.findCompletedPacks project_id, doc_id, (err, packs) ->
  244. #console.log 'err', err, 'packs', packs, packs?.length
  245. return callback(err) if err?
  246. return callback() if not packs?
  247. PackManager.insertPacksIntoIndexWithLock project_id, doc_id, packs, callback
  248. updateIndex: (project_id, doc_id, callback) ->
  249. # find all packs prior to current pack
  250. PackManager.findUnindexedPacks project_id, doc_id, (err, newPacks) ->
  251. return callback(err) if err?
  252. return callback() if not newPacks? or newPacks.length is 0
  253. PackManager.insertPacksIntoIndexWithLock project_id, doc_id, newPacks, (err) ->
  254. return callback(err) if err?
  255. logger.log {project_id, doc_id, newPacks}, "added new packs to index"
  256. callback()
  257. findCompletedPacks: (project_id, doc_id, callback) ->
  258. query = { doc_id: ObjectId(doc_id.toString()), expiresAt: {$exists:false} }
  259. db.docHistory.find(query, {pack:false}).sort {v:1}, (err, packs) ->
  260. return callback(err) if err?
  261. return callback() if not packs?
  262. return callback() if not packs?.length
  263. last = packs.pop() # discard the last pack, if it's still in progress
  264. packs.push(last) if last.finalised # it's finalised so we push it back to archive it
  265. callback(null, packs)
  266. findPacks: (project_id, doc_id, callback) ->
  267. query = { doc_id: ObjectId(doc_id.toString()), expiresAt: {$exists:false} }
  268. db.docHistory.find(query, {pack:false}).sort {v:1}, (err, packs) ->
  269. return callback(err) if err?
  270. return callback() if not packs?
  271. return callback() if not packs?.length
  272. callback(null, packs)
  273. findUnindexedPacks: (project_id, doc_id, callback) ->
  274. PackManager.getIndexWithKeys doc_id, (err, indexResult) ->
  275. return callback(err) if err?
  276. PackManager.findCompletedPacks project_id, doc_id, (err, historyPacks) ->
  277. return callback(err) if err?
  278. return callback() if not historyPacks?
  279. # select only the new packs not already in the index
  280. newPacks = (pack for pack in historyPacks when not indexResult?[pack._id]?)
  281. newPacks = (_.omit(pack, 'doc_id', 'project_id', 'n', 'sz', 'last_checked', 'finalised') for pack in newPacks)
  282. if newPacks.length
  283. logger.log {project_id, doc_id, n: newPacks.length}, "found new packs"
  284. callback(null, newPacks)
  285. insertPacksIntoIndexWithLock: (project_id, doc_id, newPacks, callback) ->
  286. LockManager.runWithLock(
  287. "HistoryIndexLock:#{doc_id}",
  288. (releaseLock) ->
  289. PackManager._insertPacksIntoIndex project_id, doc_id, newPacks, releaseLock
  290. callback
  291. )
  292. _insertPacksIntoIndex: (project_id, doc_id, newPacks, callback) ->
  293. db.docHistoryIndex.findAndModify {
  294. query: {_id:ObjectId(doc_id.toString())}
  295. update:
  296. $setOnInsert: project_id: ObjectId(project_id.toString())
  297. $push:
  298. packs: {$each: newPacks, $sort: {v: 1}}
  299. upsert: true
  300. }, callback
  301. # Archiving packs to S3
  302. archivePack: (project_id, doc_id, pack_id, callback) ->
  303. clearFlagOnError = (err, cb) ->
  304. if err? # clear the inS3 flag on error
  305. PackManager.clearPackAsArchiveInProgress project_id, doc_id, pack_id, (err2) ->
  306. return cb(err2) if err2?
  307. return cb(err)
  308. else
  309. cb()
  310. async.series [
  311. (cb) ->
  312. PackManager.checkArchiveNotInProgress project_id, doc_id, pack_id, cb
  313. (cb) ->
  314. PackManager.markPackAsArchiveInProgress project_id, doc_id, pack_id, cb
  315. (cb) ->
  316. MongoAWS.archivePack project_id, doc_id, pack_id, (err) ->
  317. clearFlagOnError(err, cb)
  318. (cb) ->
  319. PackManager.checkArchivedPack project_id, doc_id, pack_id, (err) ->
  320. clearFlagOnError(err, cb)
  321. (cb) ->
  322. PackManager.markPackAsArchived project_id, doc_id, pack_id, cb
  323. (cb) ->
  324. PackManager.setTTLOnArchivedPack project_id, doc_id, pack_id, callback
  325. ], callback
  326. checkArchivedPack: (project_id, doc_id, pack_id, callback) ->
  327. db.docHistory.findOne {_id: pack_id}, (err, pack) ->
  328. return callback(err) if err?
  329. return callback new Error("pack not found") if not pack?
  330. MongoAWS.readArchivedPack project_id, doc_id, pack_id, (err, result) ->
  331. delete result.last_checked
  332. delete pack.last_checked
  333. # need to compare ids as ObjectIds with .equals()
  334. for key in ['_id', 'project_id', 'doc_id']
  335. result[key] = pack[key] if result[key].equals(pack[key])
  336. for op, i in result.pack
  337. op._id = pack.pack[i]._id if op._id? and op._id.equals(pack.pack[i]._id)
  338. if _.isEqual pack, result
  339. callback()
  340. else
  341. logger.err {pack, result, jsondiff: JSON.stringify(pack) is JSON.stringify(result)}, "difference when comparing packs"
  342. callback new Error("pack retrieved from s3 does not match pack in mongo")
  343. # Extra methods to test archive/unarchive for a doc_id
  344. pushOldPacks: (project_id, doc_id, callback) ->
  345. PackManager.findPacks project_id, doc_id, (err, packs) ->
  346. return callback(err) if err?
  347. return callback() if not packs?.length
  348. PackManager.processOldPack project_id, doc_id, packs[0]._id, callback
  349. pullOldPacks: (project_id, doc_id, callback) ->
  350. PackManager.loadPacksByVersionRange project_id, doc_id, null, null, callback
  351. # Processing old packs via worker
  352. processOldPack: (project_id, doc_id, pack_id, callback) ->
  353. markAsChecked = (err) ->
  354. PackManager.markPackAsChecked project_id, doc_id, pack_id, (err2) ->
  355. return callback(err2) if err2?
  356. callback(err)
  357. logger.log {project_id, doc_id}, "processing old packs"
  358. db.docHistory.findOne {_id:pack_id}, (err, pack) ->
  359. return markAsChecked(err) if err?
  360. return markAsChecked() if not pack?
  361. return callback() if pack.expiresAt? # return directly
  362. PackManager.finaliseIfNeeded project_id, doc_id, pack._id, pack, (err) ->
  363. return markAsChecked(err) if err?
  364. PackManager.updateIndexIfNeeded project_id, doc_id, (err) ->
  365. return markAsChecked(err) if err?
  366. PackManager.findUnarchivedPacks project_id, doc_id, (err, unarchivedPacks) ->
  367. return markAsChecked(err) if err?
  368. if not unarchivedPacks?.length
  369. logger.log {project_id, doc_id}, "no packs need archiving"
  370. return markAsChecked()
  371. async.eachSeries unarchivedPacks, (pack, cb) ->
  372. PackManager.archivePack project_id, doc_id, pack._id, cb
  373. , (err) ->
  374. return markAsChecked(err) if err?
  375. logger.log {project_id, doc_id}, "done processing"
  376. markAsChecked()
  377. finaliseIfNeeded: (project_id, doc_id, pack_id, pack, callback) ->
  378. sz = pack.sz / (1024 * 1024) # in fractions of a megabyte
  379. n = pack.n / 1024 # in fraction of 1024 ops
  380. age = (Date.now() - pack.meta.end_ts) / DAYS
  381. if age < 30 # always keep if less than 1 month old
  382. logger.log {project_id, doc_id, pack_id, age}, "less than 30 days old"
  383. return callback()
  384. # compute an archiving threshold which decreases for each month of age
  385. archive_threshold = 30 / age
  386. if sz > archive_threshold or n > archive_threshold or age > 90
  387. logger.log {project_id, doc_id, pack_id, age, archive_threshold, sz, n}, "meets archive threshold"
  388. PackManager.markPackAsFinalisedWithLock project_id, doc_id, pack_id, callback
  389. else
  390. logger.log {project_id, doc_id, pack_id, age, archive_threshold, sz, n}, "does not meet archive threshold"
  391. callback()
  392. markPackAsFinalisedWithLock: (project_id, doc_id, pack_id, callback) ->
  393. LockManager.runWithLock(
  394. "HistoryLock:#{doc_id}",
  395. (releaseLock) ->
  396. PackManager._markPackAsFinalised project_id, doc_id, pack_id, releaseLock
  397. callback
  398. )
  399. _markPackAsFinalised: (project_id, doc_id, pack_id, callback) ->
  400. logger.log {project_id, doc_id, pack_id}, "marking pack as finalised"
  401. db.docHistory.findAndModify {
  402. query: {_id: pack_id}
  403. update: {$set: {finalised: true}}
  404. }, callback
  405. updateIndexIfNeeded: (project_id, doc_id, callback) ->
  406. logger.log {project_id, doc_id}, "archiving old packs"
  407. PackManager.getIndexWithKeys doc_id, (err, index) ->
  408. return callback(err) if err?
  409. if not index?
  410. PackManager.initialiseIndex project_id, doc_id, callback
  411. else
  412. PackManager.updateIndex project_id, doc_id, callback
  413. markPackAsChecked: (project_id, doc_id, pack_id, callback) ->
  414. logger.log {project_id, doc_id, pack_id}, "marking pack as checked"
  415. db.docHistory.findAndModify {
  416. query: {_id: pack_id}
  417. update: {$currentDate: {"last_checked":true}}
  418. }, callback
  419. findUnarchivedPacks: (project_id, doc_id, callback) ->
  420. PackManager.getIndex doc_id, (err, indexResult) ->
  421. return callback(err) if err?
  422. indexPacks = indexResult?.packs or []
  423. unArchivedPacks = (pack for pack in indexPacks when not pack.inS3?)
  424. if unArchivedPacks.length
  425. logger.log {project_id, doc_id, n: unArchivedPacks.length}, "find unarchived packs"
  426. callback(null, unArchivedPacks)
  427. # Archive locking flags
  428. checkArchiveNotInProgress: (project_id, doc_id, pack_id, callback) ->
  429. logger.log {project_id, doc_id, pack_id}, "checking if archive in progress"
  430. PackManager.getPackFromIndex doc_id, pack_id, (err, result) ->
  431. return callback(err) if err?
  432. return callback new Error("pack not found in index") if not result?
  433. if result.inS3
  434. return callback new Error("pack archiving already done")
  435. else if result.inS3?
  436. return callback new Error("pack archiving already in progress")
  437. else
  438. return callback()
  439. markPackAsArchiveInProgress: (project_id, doc_id, pack_id, callback) ->
  440. logger.log {project_id, doc_id}, "marking pack as archive in progress status"
  441. db.docHistoryIndex.findAndModify {
  442. query: {_id:ObjectId(doc_id.toString()), packs: {$elemMatch: {"_id": pack_id, inS3: {$exists:false}}}}
  443. fields: { "packs.$": 1 }
  444. update: {$set: {"packs.$.inS3":false}}
  445. }, (err, result) ->
  446. return callback(err) if err?
  447. return callback new Error("archive is already in progress") if not result?
  448. logger.log {project_id, doc_id, pack_id}, "marked as archive in progress"
  449. callback()
  450. clearPackAsArchiveInProgress: (project_id, doc_id, pack_id, callback) ->
  451. logger.log {project_id, doc_id, pack_id}, "clearing as archive in progress"
  452. db.docHistoryIndex.findAndModify {
  453. query: {_id:ObjectId(doc_id.toString()), "packs" : {$elemMatch: {"_id": pack_id, inS3: false}}}
  454. fields: { "packs.$": 1 }
  455. update: {$unset: {"packs.$.inS3":true}}
  456. }, callback
  457. markPackAsArchived: (project_id, doc_id, pack_id, callback) ->
  458. logger.log {project_id, doc_id, pack_id}, "marking pack as archived"
  459. db.docHistoryIndex.findAndModify {
  460. query: {_id:ObjectId(doc_id.toString()), "packs" : {$elemMatch: {"_id": pack_id, inS3: false}}}
  461. fields: { "packs.$": 1 }
  462. update: {$set: {"packs.$.inS3":true}}
  463. }, (err, result) ->
  464. return callback(err) if err?
  465. return callback new Error("archive is not marked as progress") if not result?
  466. logger.log {project_id, doc_id, pack_id}, "marked as archived"
  467. callback()
  468. setTTLOnArchivedPack: (project_id, doc_id, pack_id, callback) ->
  469. db.docHistory.findAndModify {
  470. query: {_id: pack_id}
  471. update: {$set: {expiresAt: new Date(Date.now() + 1*DAYS)}}
  472. }, (err) ->
  473. logger.log {project_id, doc_id, pack_id}, "set expiry on pack"
  474. callback()