-
Notifications
You must be signed in to change notification settings - Fork 2
/
start.js
416 lines (331 loc) · 8.15 KB
/
start.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
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
/**
* New node file
*/
var Mongodb = require("mongodb");
var MongoClient = Mongodb.MongoClient;
var querystring = require("querystring");
var EventEmitter = require('events').EventEmitter;
var _extend = require('util')._extend;
var inherits = require('util').inherits;
var inspect = require('util').inspect;
var log = GLOBAL.log || console;
if(log == console){
log.dev = console.log;
}
/**
* format an object to the uriString;
*
* the Reference of MongoDB connection URI
* [http://docs.mongodb.org/manual/reference/connection-string/]
*
* to use the url from returns , make sure the value of the option [uri_decode_auth] for the MongoClient.connect(urlStr,option) is true;
*
* @param {Object}
* @return {String}
* format : mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
*/
var connectObjToUri = function(obj){
var uriStr = "mongodb://";
var hostStr;
// process the default values;
if(typeof(obj) == "object"){
obj.host = obj.host || "localhost";
obj.dbname = obj.dbname || "test";
}
if(obj.username !== undefined){
uriStr += encodeURIComponent(obj.username);
if(obj.password){
uriStr += ":" + encodeURIComponent(obj.password);
}
uriStr += "@";
}
if(Array.isArray(obj.hosts) === true){
hostStr = [];
obj.hosts.forEach(function(item){
var str = ""
if(item.host){
str = item.host;
if(item.port != undefined){
str += ":" + item.port;
}
}
hostStr.push(str);
});
uriStr += hostStr.join(",");
}else if(obj.host){
uriStr += obj.host;
if(obj.port != undefined){
uriStr += ":" + obj.port;
}
}
uriStr += "/" + obj.dbname;
if(obj.opts){
uriStr += "?" + querystring.stringify(obj.opts);
}
return uriStr;
}
/**
* 短链代理..
* 由于多数公共数据库都有连接数及空闲时间限制,
* 所以直接使用mongodb driver需要做重连控制与认证控制
* 这里直接对以上行为进行包装处理.自动进行连接及重连控制.
*
* 基本策略:
* 1. 无查询时不连接
* 2. 有查询结果时不断开
* 3. 空闲超时自动断开
* 4. 重连时自动认证
* 5. 只有最常用的数据操作方法.
*/
var sortAgent = function(dburl,opts){
opts = opts || {};
var idle = opts.idle || 1000 * 30; // 空闲时间. 超时将自动关闭连接.
var waitingCount = 0;
var db = null , isConnect = false , isConnecting = false;
var __dburl = "";
var operations = [];
var collectionCache = {};
var idleTimer = false;
var me = this;
switch(typeof(dburl)){
case "string" :
__dburl = dburl;
break;
case "object" :
// 如果是object,表示未使用url的方式, 需要转为dburl
__dburl = connectObjToUri(dburl);
break;
default:
throw new Error("dburl mast be a connection uri or connection object");
}
var reconnect = 0;
var connect = this.__connect = function(){
if(isConnecting == true || isConnect == true){
// 连接中,或已有连接,则跳过.
return;
}
isConnecting = true;
MongoClient.connect(__dburl,opts || {} ,function(err,_db){
if(err){
isConnecting = false;
if(reconnect++ < 10){
log.err("reconnect : " + err.message + ", " + reconnect);
setTimeout(connect,4000);
}else{
me.emit("error",err);
}
return;
}
log.info("connect to mongodb, %s" , __dburl);
isConnect = true;
isConnecting = false;
reconnect = 0;
db = _db;
setImmediate(doJob);
});
};
var close = this.__close = function(){
log.info("close!!");
db.close();
for(var key in collectionCache){
delete collectionCache[key];
}
db = isConnect = idleTimer = false;
};
var doJob = function(){
// 无工作内容,等待超时
if(operations.length != 0){
// 无连接,等待连接;
if(isConnect != true){
connect();
return;
}
debugger;
// 有工作,有连接..干活.
var cname , collection , args;
// 一但执行就直接从数组中移除.
while(item = operations.pop()){
log.dev( "do job , \n\t %s \n", inspect(item) );
cname = item.cname;
collection = collectionCache[cname];
if(!collection){
collection = collectionCache[cname] = db.collection(cname);
}
args = item.args.concat((function(cb){
// 代理回调方法, 用于记数及关闭db连接
return function(err,rs){
waitingCount--;
log.dev("execute ok!! [%d]" , waitingCount);
cb.apply(null,arguments);
if(waitingCount <= 0 && idleTimer == false){
log.info("waiting idle!");
idleTimer = setTimeout(function(){
close();
},idle);
}
};
})(item.cb));
// create async;
setImmediate((function(type,collection,args){
collection[type].apply(collection,args);
})(item.type,collection,args));
waitingCount++;
}
return;
}
};
this.getDbUrl = function(){
return __dburl;
};
this.__done = function(){
};
this.__push = function(cname,type,args,cb){
var job = {
cname : cname,
type : type,
args: args,
cb:cb
};
operations.push(job);
clearTimeout(idleTimer);
idleTimer = false;
setImmediate(doJob);
};
EventEmitter.call(this);
};
/**
* 仅支持常用的增删改查.
*/
sortAgent.prototype = _extend({
find:function(cname,selector,opts,cb){
var _cb = cb || opts || selector;
var args;
if(_cb instanceof Function){
if(_cb == cb){
args = [selector,opts];
}else if(_cb == opts){
args = [selector];
}else{
args = [];
}
this.__push(cname,"find",args,function(err,rs){
if(err){
_cb(err);
return;
}
rs.toArray(_cb);
});
}else{
throw new Error("missing arguments!");
}
},
findOne:function(cname,selector,opts,cb){
var _cb = cb || opts || selector;
var args;
if(_cb instanceof Function){
if(_cb == cb){
args = [selector,opts];
}else if(_cb == opts){
args = [selector];
}else{
args = [];
}
this.__push(cname,"findOne", args , _cb);
}else{
throw new Error("missing arguments!");
}
},
insert:function(cname,doc,opts,cb){
var _cb = cb || opts;
var args;
if(_cb instanceof Function){
if(_cb == cb){
args = [doc,opts];
}else if(_cb == opts){
args = [doc];
}
this.__push(cname,"insert", args , _cb);
}else{
throw new Error("missing arguments!");
}
},
remove:function(cname,selector,opts,cb){
var _cb = cb || opts;
var args;
if(_cb instanceof Function){
if(_cb == cb){
args = [selector,opts];
}else if(_cb == opts){
args = [selector];
}
this.__push(cname,"remove", args , _cb);
}else{
throw new Error("missing arguments!");
}
},
save:function(cname,docs,opts,cb){
var _cb = cb || opts;
var args;
if(_cb instanceof Function){
if(_cb == cb){
args = [docs,opts];
}else if(_cb == opts){
args = [docs];
}
this.__push(cname,"save", args , _cb);
}else{
throw new Error("missing arguments!");
}
},
update:function(cname,selector,doc,opts,cb){
var _cb = cb || opts;
var args;
if(_cb instanceof Function){
if(_cb == cb){
args = [selector,doc,opts];
}else if(_cb == opts){
args = [selector,doc];
}else{
throw new Error("missing arguments!");
}
this.__push(cname,"update", args , _cb);
}else{
throw new Error("missing arguments!");
}
},
count:function(cname,selector,opts,cb){
var _cb = cb || opts;
var args;
if(_cb instanceof Function){
if(_cb == cb){
args = [selector,opts];
}else if(_cb == opts){
args = [selector];
}
this.__push(cname,"count", args , _cb);
}else{
throw new Error("missing arguments!");
}
}
},EventEmitter.prototype);
var exports = {
// 包装一个短链查询的agent.
getAgent:function(dburl,opts){
return new sortAgent(dburl,opts);
},
//原始包装
connect:function(dbUrl,cb){
MongoClient.connect(dbUrl,cb);
},
getMongodb:function(){
return Mongodb;
}
};
if(GLOBAL.rapid){
rapid.plugin.define("rapid-simple-mongo",["rapid-log"],function(mylog,cb){
log = mylog;
cb(null,exports);
});
}else{
module.exports = exports;
}