-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstorage.coffee
350 lines (306 loc) · 12.5 KB
/
storage.coffee
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
http = require 'http'
CoffeeScript = require 'coffee-script'
util = require 'util'
cradle = require 'cradle'
express = require 'express'
url = require 'url'
rest = require './rest'
shareserver = require('share').server
shareclient = require('share').client
fs = require 'fs'
class exports.Storage
constructor: (@bootstrapping = false) ->
attachServer: (@app= null, dbinfo = {}, cb = () ->) ->
@documents = []
@singletons = []
if not @app?
@app = express()
@app.use (req, res, next) ->
res.header 'Access-Control-Allow-Origin', '*'
next()
@app.use(express.bodyParser())
@app.get '/Types', (req, res) =>
names = []
for document in @documents
names.push document.name
res.send names
@app.get '/Singletons', (req, res) =>
names = []
for singleton in @singletons
names.push singleton.name
res.send names
@app.get '/storage/client.js', (req, res) =>
fs.readFile __dirname+'/client/client.coffee', 'utf-8', (error, data) =>
try
res.contentType 'application/javascript'
cs = CoffeeScript.compile data
res.send cs
catch error
console.log "Failed compiling client.coffee"
console.log error
res.statusCode = 500
res.send {"error":"server error", "reason":"storage server could not compile storage client!"}
getShareHost = (req) ->
host = req.headers.host.split ":"
return 'http://' + host[0] + ":8001"
@app.get '/storage/share/share.js', (req, res) =>
sharehost = getShareHost req
res.redirect sharehost + '/share/share.js'
@app.get '/storage/share/json.js', (req, res) =>
sharehost = getShareHost req
res.redirect sharehost + '/share/json.js'
@app.get '/storage/channel/bcsocket.js', (req, res) =>
sharehost = getShareHost req
res.redirect sharehost + '/channel/bcsocket.js'
@app.get '/storage/live.js', (req, res) =>
fs.readFile __dirname+'/live/live.coffee', 'utf-8', (error, data) =>
try
res.contentType 'application/javascript'
cs = CoffeeScript.compile data
res.send cs
catch error
console.log "Failed compiling client.coffee"
console.log error
res.statusCode = 500
res.send {"error":"server error", "reason":"storage server could not compile live client!"}
dbhost = if dbinfo.host? then dbinfo.host else 'localhost'
dbport = if dbinfo.port? then dbinfo.port else 5984
@dbname = if dbinfo.name? then dbinfo.name else "storage"
@_connectToDb dbhost, dbport, @dbname, () =>
@_setupShareJs()
cb @app
_createShareJSDB: (db, cb) ->
db.exists (err, exist) =>
if err?
console.log err
if not exist
console.log "ShareJS database does not exist, creating it now..."
db.create () =>
console.log "Creating ShareJS design docs..."
@dbShare.save '_design/sharejs', {
operations: {
map: (doc) ->
if doc.docName
emit([doc.docName, doc.v], {op:doc.op, meta:doc.meta})
}
},
(err, res) =>
if err?
console.log err
else
cb()
else
cb()
_connectToDb: (host, port, name, cb) ->
@db = new(cradle.Connection)(host, port, {cache: true,raw: false}).database(name)
@dbShare = new(cradle.Connection)(host, port, {cache: true,raw: false}).database(name+"-sharejs")
@db.exists (err, exist) =>
if err?
console.log err
if not exist
console.log "Database " + name + " does not exist, creating it now..."
@db.create () =>
@_createShareJSDB @dbShare, () ->
cb()
else
@_createShareJSDB @dbShare, () ->
cb()
_setupShareJs: () ->
@shareApp = express()
@shareApp.use (req, res, next) ->
res.header 'Access-Control-Allow-Origin', '*'
next()
options = { db: { type: 'couchdb', uri: 'http://localhost:5984/'+ @dbname + '-sharejs' }, port: 5984 };
shareserver.attach(@shareApp, options)
@shareApp.listen(8001)
console.log('Share running at http://127.0.0.1:8001/')
@shareClient = shareclient
@shareREST = http.createClient(8001, 'localhost')
registerSingleton: (name, validation=null) ->
singleton = new rest.Singleton(name, this)
@singletons.push singleton
registerDocument: (name, cb, validation=null) ->
document = new rest.Document(name, this)
@documents.push document
if not validation?
validation = (newDoc, oldDoc, usrCtx) ->
return
#To anyone reading this code: Sorry about the ugly hack below!
viewStr = '(doc) ->\n\tif (doc.type && doc.type == "'+name+'")\n\t\temit(null, doc)'
viewWithName = () ->
return CoffeeScript.eval viewStr
view = viewWithName()
@db.save '_design/'+name, {
views: {
list: {
map: view
}
}
validate_doc_update: validation
}, () =>
@_registerDocumentMonitor name, (error) ->
if cb?
cb error
#Register a singleton that will contain a list of all documents of a type
_registerDocumentMonitor: (name, cb) ->
singletonName = name+"Monitor"
@registerSingleton singletonName
@_setDocumentNames name, (error) ->
cb error
#Get all documents of @param type and save list of doc names in
#[DocType]Monitor singleton
_setDocumentNames: (type, cb) ->
@getCollection type, (error, results) =>
if error?
cb error
return
nameList = []
for docu in results
nameList.push docu.value._id
shareclient.open type+'Monitor', 'json', 'http://localhost:8001/channel', (error, monitor) =>
doc = monitor.at()
monitor.set nameList, (error, rev) ->
if error?
cb error
else
cb null
_addToMonitor: (type, id, cb) ->
shareclient.open type+'Monitor', 'json', 'http://localhost:8001/channel', (error, monitor) =>
if not monitor.snapshot?
monitor.set [id], (error, rev) =>
cb error
else
list = monitor.at([])
list.push id, (error, rev) =>
cb error
###
#REST INTERFACE FOR DATABASE ACCESS
###
getCollection: (name, cb) ->
@db.view(
name+'/list',
(error, result) =>
if error?
console.log error + "No documents of type "+name
cb error, null
else
cb null, result
)
getElement: (id, name, cb) ->
@db.get id, (error, doc) =>
console.log error
if (error || doc.type != name)
cb error, null
else
cb null, doc
postCollection: (collectionBody, name, cb) ->
doc = collectionBody
body = null
bodytype = doc.bodytype ? 'json'
if doc.body?
body = doc.body
delete doc.body
doc.type = name
@db.save doc, (err, res) =>
if err?
throw err
else
@_addToMonitor name, doc._id, (error) =>
if error?
throw err
@db.get res.id, (err, savedDoc) =>
if err?
throw err
else
@_createBody bodytype, res.id, (err) =>
if err?
console.log "Body already exists?"
if body?
@_insertInBody bodytype, res.id, body, (err) =>
if err?
throw err
cb savedDoc
else
cb savedDoc
postElement: (id, body, name, cb) ->
@db.get id, (error, doc) =>
if (error || doc.type != name)
throw error
docChanges = body
for key, value of docChanges
doc[key] = value
@db.save doc, (err, res) =>
if err?
throw err
else
@db.get id, (err, changedDoc) =>
if err?
throw err
else
cb changedDoc
deleteElement: (id, mame, cb) ->
@db.get id, (error, doc) =>
if (error? || doc.type != name)
throw error
@db.remove doc._id, doc._rev, (error, res1) =>
if error?
throw error
else
cb "Success"
#optional parameter restReq - uses responseCallBack to
#send information about share rest call status
getBody: (id, name, cb, restReq=false, res) ->
@db.get id, (error, doc) =>
if (error? || doc.type != name)
throw error
else
request = @shareREST.request('GET', '/doc/'+id, {'host': 'localhost'});
request.end()
request.on 'response', (response) =>
if restReq
for key, val of response.headers
res.header(key, val)
response.on 'data', (chunk) =>
res.send(chunk, response.statusCode)
return null
else
response.on 'data', (chunk) =>
cb chunk
###
#MISSING IMPLEMENTATION OF POSTBODY - STILL IN REST.COFFEE
###
_createBody: (bodytype, id, cb) ->
headers = {}
headers['content-type'] = 'application/json'
headers['X-OT-version'] = '0'
request = @shareREST.request("PUT", "/doc/" + id,"host": "localhost", "headers": headers)
request.write JSON.stringify({"type": bodytype})
request.end()
request.on "error", (e) ->
cb new Error(e.message)
request.on "response", (response) ->
if response.statusCode is 500
cb new Error("Body already exist")
return
response.on "data", (chunk) ->
cb null
_insertInBody: (bodytype, id, body_data, cb) ->
headers = {}
headers['content-type'] = 'application/json';
version = 0
request = @shareREST.request("POST", "/doc/" + id + "?v=" + version, {"host": "localhost", "headers": headers})
if bodytype == 'json'
op = [{"p": [],"oi": body_data }]
else if bodytype == 'text'
op = [{"p":0,"i":body_data}]
request.write JSON.stringify(op)
request.end()
request.on "error", (e) ->
console.log('error')
cb new Error(e.message)
request.on "response", (response) ->
if response.statusCode is 500
cb new Error("Body already exist")
return
response.on "data", (chunk) ->
cb null