overleaf/services/document-updater/app/coffee/PersistenceManager.coffee

80 lines
2.7 KiB
CoffeeScript
Raw Normal View History

2014-02-12 05:40:42 -05:00
request = require "request"
Settings = require "settings-sharelatex"
Errors = require "./Errors"
Metrics = require "./Metrics"
logger = require "logger-sharelatex"
2014-02-12 05:40:42 -05:00
# We have to be quick with HTTP calls because we're holding a lock that
# expires after 30 seconds. We can't let any errors in the rest of the stack
# hold us up, and need to bail out quickly if there is a problem.
MAX_HTTP_REQUEST_LENGTH = 5000 # 5 seconds
2014-02-12 05:40:42 -05:00
module.exports = PersistenceManager =
getDoc: (project_id, doc_id, _callback = (error, lines, version, track_changes, track_changes_entries) ->) ->
2014-02-12 05:40:42 -05:00
timer = new Metrics.Timer("persistenceManager.getDoc")
callback = (args...) ->
timer.done()
_callback(args...)
url = "#{Settings.apis.web.url}/project/#{project_id}/doc/#{doc_id}"
request {
url: url
method: "GET"
headers:
"accept": "application/json"
auth:
user: Settings.apis.web.user
pass: Settings.apis.web.pass
sendImmediately: true
jar: false
timeout: MAX_HTTP_REQUEST_LENGTH
2014-02-12 05:40:42 -05:00
}, (error, res, body) ->
return callback(error) if error?
if res.statusCode >= 200 and res.statusCode < 300
try
body = JSON.parse body
catch e
return callback(e)
2016-11-29 12:13:16 -05:00
if !body.lines?
return callback(new Error("web API response had no doc lines"))
if !body.version? or not body.version instanceof Number
return callback(new Error("web API response had no valid doc version"))
2016-11-28 05:14:42 -05:00
return callback null, body.lines, body.track_changes, body.track_changes_entries
2014-02-12 05:40:42 -05:00
else if res.statusCode == 404
return callback(new Errors.NotFoundError("doc not not found: #{url}"))
else
return callback(new Error("error accessing web API: #{url} #{res.statusCode}"))
setDoc: (project_id, doc_id, lines, version, track_changes, track_changes_entries, _callback = (error) ->) ->
2014-02-12 05:40:42 -05:00
timer = new Metrics.Timer("persistenceManager.setDoc")
callback = (args...) ->
timer.done()
_callback(args...)
url = "#{Settings.apis.web.url}/project/#{project_id}/doc/#{doc_id}"
request {
url: url
method: "POST"
body: JSON.stringify
lines: lines
2016-11-28 05:14:42 -05:00
track_changes: track_changes
track_changes_entries: track_changes_entries
version: version
2014-02-12 05:40:42 -05:00
headers:
"content-type": "application/json"
auth:
user: Settings.apis.web.user
pass: Settings.apis.web.pass
sendImmediately: true
jar: false
timeout: MAX_HTTP_REQUEST_LENGTH
2014-02-12 05:40:42 -05:00
}, (error, res, body) ->
return callback(error) if error?
if res.statusCode >= 200 and res.statusCode < 300
return callback null
else if res.statusCode == 404
return callback(new Errors.NotFoundError("doc not not found: #{url}"))
else
return callback(new Error("error accessing web API: #{url} #{res.statusCode}"))