couchdb.coffee 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. # OT storage for CouchDB
  2. # Author: Max Ogden (@maxogden)
  3. #
  4. # The couchdb database contains two kinds of documents:
  5. #
  6. # - Document snapshots have a key which is doc:the document name
  7. # - Document ops have a random key, but docName: defined.
  8. request = require('request').defaults json: true
  9. # Helper method to parse errors out of couchdb. There's way more ways
  10. # things can go wrong, but I think this catches all the ones I care about.
  11. #
  12. # callback(error) or callback()
  13. parseError = (err, resp, body, callback) ->
  14. body = body[0] if Array.isArray body and body.length >= 1
  15. if err
  16. # This indicates an HTTP error
  17. callback err
  18. else if resp.statusCode is 404
  19. callback 'Document does not exist'
  20. else if resp.statusCode is 403
  21. callback 'forbidden'
  22. else if typeof body is 'object'
  23. if body.error is 'conflict'
  24. callback 'Document already exists'
  25. else if body.error
  26. callback "#{body.error} reason: #{body.reason}"
  27. else
  28. callback()
  29. else
  30. callback()
  31. module.exports = (options) ->
  32. options ?= {}
  33. db = options.uri or "http://localhost:5984/sharejs"
  34. uriForDoc = (docName) -> "#{db}/doc:#{encodeURIComponent docName}"
  35. uriForOps = (docName, start, end, include_docs) ->
  36. startkey = encodeURIComponent(JSON.stringify [docName, start])
  37. # {} is sorted after all numbers - so this will get all ops in the case that end is null.
  38. endkey = encodeURIComponent(JSON.stringify [docName, end ? {}])
  39. # Another way to write this method would be to use node's builtin uri-encoder.
  40. extra = if include_docs then '&include_docs=true' else ''
  41. "#{db}/_design/sharejs/_view/operations?startkey=#{startkey}&endkey=#{endkey}&inclusive_end=false#{extra}"
  42. # Helper method to get the revision of a document snapshot.
  43. getRev = (docName, dbMeta, callback) ->
  44. if dbMeta?.rev
  45. callback null, dbMeta.rev
  46. else
  47. # JSON defaults to true, and that makes request think I'm trying to sneak a request
  48. # body in. Ugh.
  49. request.head {uri:uriForDoc(docName), json:false}, (err, resp, body) ->
  50. parseError err, resp, body, (error) ->
  51. if error
  52. callback error
  53. else
  54. # The etag is the rev in quotes.
  55. callback null, JSON.parse(resp.headers.etag)
  56. writeSnapshotInternal = (docName, data, rev, callback) ->
  57. body = data
  58. body.fieldType = 'Document'
  59. body._rev = rev if rev?
  60. request.put uri:(uriForDoc docName), body:body, (err, resp, body) ->
  61. parseError err, resp, body, (error) ->
  62. if error
  63. #console.log 'create error'
  64. # This will send write conflicts as 'document already exists'. Thats kinda wierd, but
  65. # it shouldn't happen anyway
  66. callback? error
  67. else
  68. # We pass the document revision back to the db cache so it can give it back to couchdb on subsequent requests.
  69. callback? null, {rev: body.rev}
  70. # getOps returns all ops between start and end. end can be null.
  71. getOps: (docName, start, end, callback) ->
  72. return callback null, [] if start == end
  73. # Its a bit gross having this end parameter here....
  74. endkey = if end? then [docName, end - 1]
  75. request uriForOps(docName, start, end), (err, resp, body) ->
  76. # Rows look like this:
  77. # {"id":"<uuid>","key":["doc name",0],"value":{"op":[{"p":0,"i":"hi"}],"meta":{}}}
  78. data = ({op: row.value.op, meta: row.value.meta} for row in body.rows)
  79. callback null, data
  80. # callback(error, db metadata)
  81. create: (docName, data, callback) ->
  82. writeSnapshotInternal docName, data, null, callback
  83. delete: del = (docName, dbMeta, callback) ->
  84. getRev docName, dbMeta, (error, rev) ->
  85. return callback? error if error
  86. docs = [{_id:"doc:#{docName}", _rev:rev, _deleted:true}]
  87. # Its annoying, but we need to get the revision from the document. I don't think there's a simple way to do this.
  88. # This request will get all the ops twice.
  89. request uriForOps(docName, 0, null, true), (err, resp, body) ->
  90. # Rows look like this:
  91. # {"id":"<uuid>","key":["doc name",0],"value":{"op":[{"p":0,"i":"hi"}],"meta":{}},
  92. # "doc":{"_id":"<uuid>","_rev":"1-21a40c56ebd5d424ffe56950e77bc847","op":[{"p":0,"i":"hi"}],"v":0,"meta":{},"docName":"doc6"}}
  93. for row in body.rows
  94. row.doc._deleted = true
  95. docs.push row.doc
  96. request.post url: "#{db}/_bulk_docs", body: {docs}, (err, resp, body) ->
  97. if body[0].error is 'conflict'
  98. # Somebody has edited the document since we did a GET on the revision information. Recurse.
  99. # By passing null to dbMeta I'm forcing the revision information to be reacquired.
  100. del docName, null, callback
  101. else
  102. parseError err, resp, body, (error) -> callback? error
  103. writeOp: (docName, opData, callback) ->
  104. body =
  105. docName: docName
  106. op: opData.op
  107. v: opData.v
  108. meta: opData.meta
  109. request.post url:db, body:body, (err, resp, body) ->
  110. parseError err, resp, body, callback
  111. writeSnapshot: (docName, docData, dbMeta, callback) ->
  112. getRev docName, dbMeta, (error, rev) ->
  113. return callback? error if error
  114. writeSnapshotInternal docName, docData, rev, callback
  115. getSnapshot: (docName, callback) ->
  116. request uriForDoc(docName), (err, resp, body) ->
  117. parseError err, resp, body, (error) ->
  118. if error
  119. callback error
  120. else
  121. callback null,
  122. snapshot: body.snapshot
  123. type: body.type
  124. meta: body.meta
  125. v: body.v
  126. , {rev: body._rev} # dbMeta
  127. close: ->