-
Notifications
You must be signed in to change notification settings - Fork 12
/
ddoc.js
313 lines (245 loc) · 7.71 KB
/
ddoc.js
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
// Queue design document
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
require('defaultable')(module,
{
}, function(module, exports, DEFS, require) {
var fs = require('fs')
, lib = require('./lib')
, path = require('path')
, util = require('util')
, debug = require('debug')
, assert = require('assert')
, browserify = require('browserify')
;
module.exports = { "DDoc" : DDoc
// For importing and unit testing.
, 'validate_doc_update': validate_doc_update
, 'visible_at' : visible_at
, 'enqueue_message' : enqueue_message
}
//
// Constants
//
var TEMPLATE =
// _id
// _rev
{ 'queues': {}
, updates: {"queue": enqueue_message}
, views: { "visible_at": { map: visible_at
, reduce: '_count'
}
}
, "validate_doc_update": validate_doc_update
}
function enqueue_message(doc, req) {
if(req.method != 'POST')
return resp(400, {'error':'Only POST is allowed'})
if(doc)
return resp(400, {'error':'Only creating new messages is allowed'})
try {
var body = JSON.parse(req.body)
} catch (er) {
return resp(400, {'error':'Bad JSON body'})
}
// Figure out the queue to update, from .../_update/this_function/queue_name
var i = req.path.indexOf('_update')
var queue = req.path[i+2]
var now = new Date
doc =
{ _id: 'CQS/' + queue + '/' + req.uuid
, ApproximateFirstReceiveTimestamp: null
, ApproximateReceiveCount : 0
, Body : body
, SenderId : req.userCtx.name
, SentTimestamp : now
, visible_at : now
}
//log('Create CQS document: ' + JSON.stringify(doc))
return resp(201, doc)
function resp(code, body) {
if(code != 201)
doc = null
return [doc,
{ 'code' : code
, 'headers': {'content-type':'application/json'}
, 'body' : JSON.stringify(body) + "\n"
}
]
}
}
function validate_doc_update(newDoc, oldDoc, userCtx, secObj) {
var ddoc = this
var msg_id_re = /^CQS\/(.+?)\/([0-9a-f]{32})($|\/(.*)$)/
var match = newDoc._id.match(msg_id_re)
if(!match && ddoc.allow_foreign_docs)
return // Ignore this non-CQS document.
if(!match)
throw {'forbidden': 'This database is for CQS only; bad message ID: ' + newDoc._id}
var queue_id = match[1]
, msg_id = match[2]
if(! (queue_id in ddoc.queues))
throw {'forbidden':'Queue does not exist: '+queue_id}
var IS_DB_ADMIN = false;
secObj.admins = secObj.admins || {};
secObj.admins.names = secObj.admins.names || [];
secObj.admins.roles = secObj.admins.roles || [];
if(userCtx.roles.indexOf('_admin') !== -1)
IS_DB_ADMIN = true;
if(secObj.admins.names.indexOf(userCtx.name) !== -1)
IS_DB_ADMIN = true;
for(i = 0; i < userCtx.roles; i++)
if(secObj.admins.roles.indexOf(userCtx.roles[i]) !== -1)
IS_DB_ADMIN = true;
var good_keys = [ "_id", "_rev", "_revisions", "_deleted"
, 'SenderId'
, 'SentTimestamp'
, 'visible_at'
, 'ApproximateReceiveCount'
, 'ApproximateFirstReceiveTimestamp'
, 'MD5OfMessageBody'
, 'Body'
// Some extensions
, 'ReceiverId'
];
var key;
for (key in newDoc)
if(good_keys.indexOf(key) === -1)
throw({forbidden: "Invalid field: " + key});
if(! newDoc._deleted) {
if(newDoc.Body === null || newDoc.Body === undefined)
throw {forbidden: 'Invalid .Body: ' + JSON.stringify(newDoc.Body)};
} else {
if(!oldDoc || oldDoc.ReceiverId !== userCtx.name) {
if(IS_DB_ADMIN)
log('Allowing db admin "'+userCtx.name+'" to delete: ' + newDoc._id);
else
throw {forbidden: 'You may not delete this document'};
}
return;
}
if(!newDoc.visible_at)
throw {forbidden: 'Must set visible_at'};
if(oldDoc) {
// Checkout ("receive")
if(newDoc.ReceiverId !== userCtx.name && !IS_DB_ADMIN)
throw({forbidden: 'Must set ReceiverId to your name: ' + JSON.stringify(userCtx.name)});
} else {
// Message send
if(newDoc.SenderId !== userCtx.name && !IS_DB_ADMIN)
throw({forbidden: 'Must set SenderId to your name: ' + JSON.stringify(userCtx.name)});
}
}
function visible_at(doc) {
var msg_id_re = /^CQS\/(.+?)\/([0-9a-f]{32})($|\/(.*)$)/
var match = doc._id.match(msg_id_re)
if(!match || !doc.visible_at)
return
var queue_id = match[1]
, msg_id = match[2]
// The client must be able to check out ("receive") the message using this view data,
// which means MVCC stuff and anything else necessary.
var val = {"_id":doc._id, "_rev":doc._rev};
for(var a in doc)
if(a.match(/^[A-Z]/))
val[a] = doc[a]
var key = [queue_id, doc.visible_at]
emit(key, val)
}
//
// API
//
function DDoc () {
var self = this;
self.copy_template();
self._id = "_design/cqs"
}
// One common logger for them all, just so it won't get stored in couch.
DDoc.prototype.log = debug('cqs:ddoc');
DDoc.prototype.copy_template = function() {
var self = this;
// if(self.name.length < 1 || self.name.length > 80)
// throw new Error("Queue name exceeds length max of 80: " + self.name.length)
var ddoc = templated_ddoc()
lib.copy(ddoc, self);
}
// Attach the web browser port.
DDoc.prototype.add_browser = function(callback) {
if(!browserify){
return callback(); //we're running in a browser (skip)
}
var counter = 1
, self = this
this._attachments = this._attachments || {}
;['showlist.js', 'index.html']
.forEach(function(name) {
counter++
fs.readFile(__dirname + '/browser/' + name, function(err, data) {
if(err) {
handleError(err)
} else {
var content_type = name.substr(-3) === '.js' ? 'text/javascript' : 'text/html'
addFile(name, data, content_type)
}
})
})
var file = ''
browserify('./') // browserify the current module
.require('./', {expose: 'cqs'})
.bundle()
.on('data', function(data){
file += data
})
.on('error', handleError)
.on('end', function(){
addFile('index.js', new Buffer(file), 'text/javascript')
})
function handleError(err){
counter = -1
callback(err)
}
function addFile(name, data, content_type){
self._attachments[name] = { content_type: content_type
, data : data.toString('base64')
}
if(!--counter)
callback()
}
}
//
// Utilities
//
function templated_ddoc(name) {
return stringify_functions(TEMPLATE)
function stringify_functions(obj) {
var copy = {};
if(Array.isArray(obj))
return obj.map(stringify_functions)
else if(typeof obj === 'object' && obj !== null) {
Object.keys(obj).forEach(function(key) {
copy[key] = stringify_functions(obj[key]);
})
return copy;
}
else if(typeof obj === 'function')
return func_from_template(obj)
else
return lib.JDUP(obj);
}
}
function func_from_template(func) {
var src = func.toString();
src = src.replace(/^function.*?\(/, 'function (');
return src;
}
}, require) // defaultable