faye 0.6.1 → 0.6.2

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of faye might be problematic. Click here for more details.

@@ -1,3 +1,12 @@
1
+ === 0.6.2 / 2011-06-19
2
+
3
+ * Add authentication, database selection and namespacing to Redis engine
4
+ * Clean up all client data when removing clients from Redis
5
+ * Fix cross-origin-long-polling for OPTIONS-aware browsers
6
+ * Update secure WebSocket detection for recent Node versions
7
+ * Reinstate 'faye.client' field in Rack environment
8
+
9
+
1
10
  === 0.6.1 / 2011-06-06
2
11
  TestSwarm build: http://swarm.jcoglan.com/job/37/
3
12
 
@@ -42,7 +42,7 @@ should get you up and running:
42
42
  jake
43
43
 
44
44
  # Run tests
45
- redis-server
45
+ redis-server spec/redis.conf
46
46
  bundle exec rspec -c spec/
47
47
  node spec/node.js
48
48
 
@@ -1 +1 @@
1
- if(!this.Faye)Faye={};Faye.extend=function(a,b,c){if(!b)return a;for(var d in b){if(!b.hasOwnProperty(d))continue;if(a.hasOwnProperty(d)&&c===false)continue;if(a[d]!==b[d])a[d]=b[d]}return a};Faye.extend(Faye,{VERSION:'0.6.1',BAYEUX_VERSION:'1.0',ID_LENGTH:128,JSONP_CALLBACK:'jsonpcallback',CONNECTION_TYPES:['long-polling','cross-origin-long-polling','callback-polling','websocket','in-process'],MANDATORY_CONNECTION_TYPES:['long-polling','callback-polling','in-process'],ENV:(function(){return this})(),random:function(a){a=a||this.ID_LENGTH;if(a>32){var b=Math.ceil(a/32),c='';while(b--)c+=this.random(32);return c}var d=Math.pow(2,a)-1,f=d.toString(36).length,c=Math.floor(Math.random()*d).toString(36);while(c.length<f)c='0'+c;return c},commonElement:function(a,b){for(var c=0,d=a.length;c<d;c++){if(this.indexOf(b,a[c])!==-1)return a[c]}return null},indexOf:function(a,b){for(var c=0,d=a.length;c<d;c++){if(a[c]===b)return c}return-1},each:function(a,b,c){if(a instanceof Array){for(var d=0,f=a.length;d<f;d++){if(a[d]!==undefined)b.call(c||null,a[d],d)}}else{for(var g in a){if(a.hasOwnProperty(g))b.call(c||null,g,a[g])}}},map:function(a,b,c){var d=[];this.each(a,function(){d.push(b.apply(c||null,arguments))});return d},filter:function(a,b,c){var d=[];this.each(a,function(){if(b.apply(c,arguments))d.push(arguments[0])});return d},size:function(a){var b=0;this.each(a,function(){b+=1});return b},enumEqual:function(c,d){if(d instanceof Array){if(!(c instanceof Array))return false;var f=c.length;if(f!==d.length)return false;while(f--){if(c[f]!==d[f])return false}return true}else{if(!(c instanceof Object))return false;if(this.size(d)!==this.size(c))return false;var g=true;this.each(c,function(a,b){g=g&&(d[a]===b)});return g}},asyncEach:function(a,b,c,d){var f=a.length,g=-1,h=0,j=false;var i=function(){h-=1;g+=1;if(g===f)return c&&c.call(d);b(a[g],m)};var k=function(){if(j)return;j=true;while(h>0)i();j=false};var m=function(){h+=1;k()};m()},toJSON:function(a){if(this.stringify)return this.stringify(a,function(key,value){return(this[key]instanceof Array)?this[key]:value});return JSON.stringify(a)},timestamp:function(){var b=new Date(),c=b.getFullYear(),d=b.getMonth()+1,f=b.getDate(),g=b.getHours(),h=b.getMinutes(),j=b.getSeconds();var i=function(a){return a<10?'0'+a:String(a)};return i(c)+'-'+i(d)+'-'+i(f)+' '+i(g)+':'+i(h)+':'+i(j)}});Faye.Class=function(a,b){if(typeof a!=='function'){b=a;a=Object}var c=function(){if(!this.initialize)return this;return this.initialize.apply(this,arguments)||this};var d=function(){};d.prototype=a.prototype;c.prototype=new d();Faye.extend(c.prototype,b);return c};Faye.Namespace=Faye.Class({initialize:function(){this._c={}},exists:function(a){return this._c.hasOwnProperty(a)},generate:function(){var a=Faye.random();while(this._c.hasOwnProperty(a))a=Faye.random();return this._c[a]=a},release:function(a){delete this._c[a]}});Faye.Error=Faye.Class({initialize:function(a,b,c){this.code=a;this.params=Array.prototype.slice.call(b);this.message=c},toString:function(){return this.code+':'+this.params.join(',')+':'+this.message}});Faye.Error.parse=function(a){a=a||'';if(!Faye.Grammar.ERROR.test(a))return new this(null,[],a);var b=a.split(':'),c=parseInt(b[0]),d=b[1].split(','),a=b[2];return new this(c,d,a)};Faye.Error.versionMismatch=function(){return new this(300,arguments,"Version mismatch").toString()};Faye.Error.conntypeMismatch=function(){return new this(301,arguments,"Connection types not supported").toString()};Faye.Error.extMismatch=function(){return new this(302,arguments,"Extension mismatch").toString()};Faye.Error.badRequest=function(){return new this(400,arguments,"Bad request").toString()};Faye.Error.clientUnknown=function(){return new this(401,arguments,"Unknown client").toString()};Faye.Error.parameterMissing=function(){return new this(402,arguments,"Missing required parameter").toString()};Faye.Error.channelForbidden=function(){return new this(403,arguments,"Forbidden channel").toString()};Faye.Error.channelUnknown=function(){return new this(404,arguments,"Unknown channel").toString()};Faye.Error.channelInvalid=function(){return new this(405,arguments,"Invalid channel").toString()};Faye.Error.extUnknown=function(){return new this(406,arguments,"Unknown extension").toString()};Faye.Error.publishFailed=function(){return new this(407,arguments,"Failed to publish").toString()};Faye.Error.serverError=function(){return new this(500,arguments,"Internal server error").toString()};Faye.Deferrable={callback:function(a,b){if(!a)return;if(this._s==='succeeded')return a.apply(b,this._i);this._j=this._j||[];this._j.push([a,b])},errback:function(a,b){if(!a)return;if(this._s==='failed')return a.apply(b,this._i);this._k=this._k||[];this._k.push([a,b])},setDeferredStatus:function(){var a=Array.prototype.slice.call(arguments),b=a.shift(),c;this._s=b;this._i=a;if(b==='succeeded')c=this._j;else if(b==='failed')c=this._k;if(!c)return;var d;while(d=c.shift())d[0].apply(d[1],this._i)}};Faye.Publisher={countSubscribers:function(a){if(!this._3||!this._3[a])return 0;return this._3[a].length},addSubscriber:function(a,b,c){this._3=this._3||{};var d=this._3[a]=this._3[a]||[];d.push([b,c])},removeSubscriber:function(a,b,c){if(!this._3||!this._3[a])return;if(!b){delete this._3[a];return}var d=this._3[a],f=d.length;while(f--){if(b!==d[f][0])continue;if(c&&d[f][1]!==c)continue;d.splice(f,1)}},removeSubscribers:function(){this._3={}},publishEvent:function(){var b=Array.prototype.slice.call(arguments),c=b.shift();if(!this._3||!this._3[c])return;Faye.each(this._3[c],function(a){a[0].apply(a[1],b)})}};Faye.Timeouts={addTimeout:function(a,b,c,d){this._4=this._4||{};if(this._4.hasOwnProperty(a))return;var f=this;this._4[a]=Faye.ENV.setTimeout(function(){delete f._4[a];c.call(d)},1000*b)},removeTimeout:function(a){this._4=this._4||{};var b=this._4[a];if(!b)return;clearTimeout(b);delete this._4[a]}};Faye.Logging={LOG_LEVELS:{error:3,warn:2,info:1,debug:0},logLevel:'error',log:function(a,b){if(!Faye.logger)return;var c=Faye.Logging.LOG_LEVELS;if(c[Faye.Logging.logLevel]>c[b])return;var a=Array.prototype.slice.apply(a),d=' ['+b.toUpperCase()+'] [Faye',f=this.className,g=a.shift().replace(/\?/g,function(){try{return Faye.toJSON(a.shift())}catch(e){return'[Object]'}});for(var h in Faye){if(f)continue;if(typeof Faye[h]!=='function')continue;if(this instanceof Faye[h])f=h}if(f)d+='.'+f;d+='] ';Faye.logger(Faye.timestamp()+d+g)}};Faye.each(Faye.Logging.LOG_LEVELS,function(a,b){Faye.Logging[a]=function(){this.log(arguments,a)}});Faye.Grammar={LOWALPHA:/^[a-z]$/,UPALPHA:/^[A-Z]$/,ALPHA:/^([a-z]|[A-Z])$/,DIGIT:/^[0-9]$/,ALPHANUM:/^(([a-z]|[A-Z])|[0-9])$/,MARK:/^(\-|\_|\!|\~|\(|\)|\$|\@)$/,STRING:/^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*$/,TOKEN:/^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+$/,INTEGER:/^([0-9])+$/,CHANNEL_SEGMENT:/^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+$/,CHANNEL_SEGMENTS:/^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*$/,CHANNEL_NAME:/^\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*$/,WILD_CARD:/^\*{1,2}$/,CHANNEL_PATTERN:/^(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*\/\*{1,2}$/,VERSION_ELEMENT:/^(([a-z]|[A-Z])|[0-9])(((([a-z]|[A-Z])|[0-9])|\-|\_))*$/,VERSION:/^([0-9])+(\.(([a-z]|[A-Z])|[0-9])(((([a-z]|[A-Z])|[0-9])|\-|\_))*)*$/,CLIENT_ID:/^((([a-z]|[A-Z])|[0-9]))+$/,ID:/^((([a-z]|[A-Z])|[0-9]))+$/,ERROR_MESSAGE:/^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*$/,ERROR_ARGS:/^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*(,(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*)*$/,ERROR_CODE:/^[0-9][0-9][0-9]$/,ERROR:/^([0-9][0-9][0-9]:(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*(,(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*)*:(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*|[0-9][0-9][0-9]::(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*)$/};Faye.Extensible={addExtension:function(a){this._5=this._5||[];this._5.push(a);if(a.added)a.added()},removeExtension:function(a){if(!this._5)return;var b=this._5.length;while(b--){if(this._5[b]!==a)continue;this._5.splice(b,1);if(a.removed)a.removed()}},pipeThroughExtensions:function(c,d,f,g){this.debug('Passing through ? extensions: ?',c,d);if(!this._5)return f.call(g,d);var h=this._5.slice();var j=function(a){if(!a)return f.call(g,a);var b=h.shift();if(!b)return f.call(g,a);if(b[c])b[c](a,j);else j(a)};j(d)}};Faye.extend(Faye.Extensible,Faye.Logging);Faye.Channel=Faye.Class({initialize:function(a){this.id=this.name=a},push:function(a){this.publishEvent('message',a)},isUnused:function(){return this.countSubscribers('message')===0}});Faye.extend(Faye.Channel.prototype,Faye.Publisher);Faye.extend(Faye.Channel,{HANDSHAKE:'/meta/handshake',CONNECT:'/meta/connect',SUBSCRIBE:'/meta/subscribe',UNSUBSCRIBE:'/meta/unsubscribe',DISCONNECT:'/meta/disconnect',META:'meta',SERVICE:'service',expand:function(a){var b=this.parse(a),c=['/**',a];var d=b.slice();d[d.length-1]='*';c.push(this.unparse(d));for(var f=1,g=b.length;f<g;f++){d=b.slice(0,f);d.push('**');c.push(this.unparse(d))}return c},isValid:function(a){return Faye.Grammar.CHANNEL_NAME.test(a)||Faye.Grammar.CHANNEL_PATTERN.test(a)},parse:function(a){if(!this.isValid(a))return null;return a.split('/').slice(1)},unparse:function(a){return'/'+a.join('/')},isMeta:function(a){var b=this.parse(a);return b?(b[0]===this.META):null},isService:function(a){var b=this.parse(a);return b?(b[0]===this.SERVICE):null},isSubscribable:function(a){if(!this.isValid(a))return null;return!this.isMeta(a)&&!this.isService(a)},Set:Faye.Class({initialize:function(){this._2={}},getKeys:function(){var c=[];Faye.each(this._2,function(a,b){c.push(a)});return c},remove:function(a){delete this._2[a]},hasSubscription:function(a){return this._2.hasOwnProperty(a)},subscribe:function(c,d,f){if(!d)return;Faye.each(c,function(a){var b=this._2[a]=this._2[a]||new Faye.Channel(a);b.addSubscriber('message',d,f)},this)},unsubscribe:function(a,b,c){var d=this._2[a];if(!d)return false;d.removeSubscriber('message',b,c);if(d.isUnused()){this.remove(a);return true}else{return false}},distributeMessage:function(c){var d=Faye.Channel.expand(c.channel);Faye.each(d,function(a){var b=this._2[a];if(b)b.publishEvent('message',c.data)},this)}})});Faye.Subscription=Faye.Class({initialize:function(a,b,c,d){this._8=a;this._2=b;this._l=c;this._m=d;this._t=false},cancel:function(){if(this._t)return;this._8.unsubscribe(this._2,this._l,this._m);this._t=true},unsubscribe:function(){this.cancel()}});Faye.extend(Faye.Subscription.prototype,Faye.Deferrable);Faye.Client=Faye.Class({UNCONNECTED:1,CONNECTING:2,CONNECTED:3,DISCONNECTED:4,HANDSHAKE:'handshake',RETRY:'retry',NONE:'none',CONNECTION_TIMEOUT:60.0,DEFAULT_ENDPOINT:'/bayeux',INTERVAL:0.0,initialize:function(b,c){this.info('New client created for ?',b);this.endpoint=b||this.DEFAULT_ENDPOINT;this._u=c||{};Faye.Transport.get(this,Faye.MANDATORY_CONNECTION_TYPES,function(a){this._d=a},this);this._1=this.UNCONNECTED;this._2=new Faye.Channel.Set();this._y=new Faye.Namespace();this._n={};this._6={reconnect:this.RETRY,interval:1000*(this._u.interval||this.INTERVAL),timeout:1000*(this._u.timeout||this.CONNECTION_TIMEOUT)};if(Faye.Event)Faye.Event.on(Faye.ENV,'beforeunload',this.disconnect,this)},getClientId:function(){return this._0},getState:function(){switch(this._1){case this.UNCONNECTED:return'UNCONNECTED';case this.CONNECTING:return'CONNECTING';case this.CONNECTED:return'CONNECTED';case this.DISCONNECTED:return'DISCONNECTED'}},handshake:function(c,d){if(this._6.reconnect===this.NONE)return;if(this._1!==this.UNCONNECTED)return;this._1=this.CONNECTING;var f=this;this.info('Initiating handshake with ?',this.endpoint);this._9({channel:Faye.Channel.HANDSHAKE,version:Faye.BAYEUX_VERSION,supportedConnectionTypes:[this._d.connectionType]},function(b){if(b.successful){this._1=this.CONNECTED;this._0=b.clientId;Faye.Transport.get(this,b.supportedConnectionTypes,function(a){this._d=a},this);this.info('Handshake successful: ?',this._0);this.subscribe(this._2.getKeys(),true);if(c)c.call(d)}else{this.info('Handshake unsuccessful');Faye.ENV.setTimeout(function(){f.handshake(c,d)},this._6.interval);this._1=this.UNCONNECTED}},this)},connect:function(a,b){if(this._6.reconnect===this.NONE)return;if(this._1===this.DISCONNECTED)return;if(this._1===this.UNCONNECTED)return this.handshake(function(){this.connect(a,b)},this);this.callback(a,b);if(this._1!==this.CONNECTED)return;this.info('Calling deferred actions for ?',this._0);this.setDeferredStatus('succeeded');this.setDeferredStatus('deferred');if(this._o)return;this._o=true;this.info('Initiating connection for ?',this._0);this._9({channel:Faye.Channel.CONNECT,clientId:this._0,connectionType:this._d.connectionType},this._v,this)},disconnect:function(){if(this._1!==this.CONNECTED)return;this._1=this.DISCONNECTED;this.info('Disconnecting ?',this._0);this._9({channel:Faye.Channel.DISCONNECT,clientId:this._0});this.info('Clearing channel listeners for ?',this._0);this._2=new Faye.Channel.Set()},subscribe:function(c,d,f){if(c instanceof Array)return Faye.each(c,function(channel){this.subscribe(channel,d,f)},this);var g=new Faye.Subscription(this,c,d,f);var h=(d===true);if(!h&&this._2.hasSubscription(c)){this._2.subscribe([c],d,f);g.setDeferredStatus('succeeded');return g}this.connect(function(){this.info('Client ? attempting to subscribe to ?',this._0,c);this._9({channel:Faye.Channel.SUBSCRIBE,clientId:this._0,subscription:c},function(a){if(!a.successful)return g.setDeferredStatus('failed',Faye.Error.parse(a.error));var b=[].concat(a.subscription);this.info('Subscription acknowledged for ? to ?',this._0,b);this._2.subscribe(b,d,f);g.setDeferredStatus('succeeded')},this)},this);return g},unsubscribe:function(c,d,f){if(c instanceof Array)return Faye.each(c,function(channel){this.unsubscribe(channel,d,f)},this);var g=this._2.unsubscribe(c,d,f);if(!g)return;this.connect(function(){this.info('Client ? attempting to unsubscribe from ?',this._0,c);this._9({channel:Faye.Channel.UNSUBSCRIBE,clientId:this._0,subscription:c},function(a){if(!a.successful)return;var b=[].concat(a.subscription);this.info('Unsubscription acknowledged for ? from ?',this._0,b)},this)},this)},publish:function(a,b){if(!Faye.Grammar.CHANNEL_NAME.test(a))throw new Error("Cannot publish: '"+a+"' is not a valid channel name");this.connect(function(){this.info('Client ? queueing published message to ?: ?',this._0,a,b);this._9({channel:a,data:b,clientId:this._0})},this)},receiveMessage:function(c){this.pipeThroughExtensions('incoming',c,function(a){if(!a)return;if(a.advice)this._z(a.advice);var b=this._n[a.id];if(b){delete this._n[a.id];b[0].call(b[1],a)}this._A(a)},this)},_9:function(b,c,d){b.id=this._y.generate();if(c)this._n[b.id]=[c,d];this.pipeThroughExtensions('outgoing',b,function(a){if(!a)return;this._d.send(a,this._6.timeout/1000)},this)},_z:function(a){Faye.extend(this._6,a);if(this._6.reconnect===this.HANDSHAKE&&this._1!==this.DISCONNECTED){this._1=this.UNCONNECTED;this._0=null;this._v()}},_A:function(a){if(!a.channel||!a.data)return;this.info('Client ? calling listeners for ? with ?',this._0,a.channel,a.data);this._2.distributeMessage(a)},_B:function(){if(!this._o)return;this._o=null;this.info('Closed connection for ?',this._0)},_v:function(){this._B();var a=this;Faye.ENV.setTimeout(function(){a.connect()},this._6.interval)}});Faye.extend(Faye.Client.prototype,Faye.Deferrable);Faye.extend(Faye.Client.prototype,Faye.Logging);Faye.extend(Faye.Client.prototype,Faye.Extensible);Faye.Transport=Faye.extend(Faye.Class({MAX_DELAY:0.0,batching:true,initialize:function(a,b){this.debug('Created new ? transport for ?',this.connectionType,b);this._8=a;this._a=b;this._e=[]},send:function(a,b){this.debug('Client ? sending message to ?: ?',this._8._0,this._a,a);if(!this.batching)return this.request([a],b);this._e.push(a);this._7=b;if(a.channel===Faye.Channel.HANDSHAKE)return this.flush();if(a.channel===Faye.Channel.CONNECT)this._p=a;this.addTimeout('publish',this.MAX_DELAY,this.flush,this)},flush:function(){this.removeTimeout('publish');if(this._e.length>1&&this._p)this._p.advice={timeout:0};this.request(this._e,this._7);this._p=null;this._e=[]},receive:function(a){this.debug('Client ? received from ?: ?',this._8._0,this._a,a);Faye.each(a,this._8.receiveMessage,this._8)},retry:function(a,b){var c=this;return function(){Faye.ENV.setTimeout(function(){c.request(a,2*b)},1000*b)}}}),{get:function(g,h,j,i){var k=g.endpoint;if(h===undefined)h=this.supportedConnectionTypes();Faye.asyncEach(this._q,function(b,c){var d=b[0],f=b[1];if(Faye.indexOf(h,d)<0)return c();f.isUsable(k,function(a){if(a)j.call(i,new f(g,k));else c()})},function(){throw new Error('Could not find a usable connection type for '+k);})},register:function(a,b){this._q.push([a,b]);b.prototype.connectionType=a},_q:[],supportedConnectionTypes:function(){return Faye.map(this._q,function(a){return a[0]})}});Faye.extend(Faye.Transport.prototype,Faye.Logging);Faye.extend(Faye.Transport.prototype,Faye.Timeouts);Faye.Event={_f:[],on:function(a,b,c,d){var f=function(){c.call(d)};if(a.addEventListener)a.addEventListener(b,f,false);else a.attachEvent('on'+b,f);this._f.push({_g:a,_r:b,_l:c,_m:d,_w:f})},detach:function(a,b,c,d){var f=this._f.length,g;while(f--){g=this._f[f];if((a&&a!==g._g)||(b&&b!==g._r)||(c&&c!==g._l)||(d&&d!==g._m))continue;if(g._g.removeEventListener)g._g.removeEventListener(g._r,g._w,false);else g._g.detachEvent('on'+g._r,g._w);this._f.splice(f,1);g=null}}};Faye.Event.on(Faye.ENV,'unload',Faye.Event.detach,Faye.Event);Faye.URI=Faye.extend(Faye.Class({queryString:function(){var c=[],d;Faye.each(this.params,function(a,b){c.push(encodeURIComponent(a)+'='+encodeURIComponent(b))});return c.join('&')},isLocal:function(){var a=Faye.URI.parse(Faye.ENV.location.href);var b=(a.hostname!==this.hostname)||(a.port!==this.port)||(a.protocol!==this.protocol);return!b},toURL:function(){var a=this.queryString();return this.protocol+this.hostname+':'+this.port+this.pathname+(a?'?'+a:'')}}),{parse:function(d,f){if(typeof d!=='string')return d;var g=new this();var h=function(b,c){d=d.replace(c,function(a){if(a)g[b]=a;return''})};h('protocol',/^https?\:\/+/);h('hostname',/^[^\/\:]+/);h('port',/^:[0-9]+/);Faye.extend(g,{protocol:'http://',hostname:Faye.ENV.location.hostname,port:Faye.ENV.location.port},false);if(!g.port)g.port=(g.protocol==='https://')?'443':'80';g.port=g.port.replace(/\D/g,'');var j=d.split('?'),i=j.shift(),k=j.join('?'),m=k?k.split('&'):[],o=m.length,l={};while(o--){j=m[o].split('=');l[decodeURIComponent(j[0]||'')]=decodeURIComponent(j[1]||'')}if(typeof f==='object')Faye.extend(l,f);g.pathname=i;g.params=l;return g}});if(!this.JSON){JSON={}}(function(){function k(a){return a<10?'0'+a:a}if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(a){return this.getUTCFullYear()+'-'+k(this.getUTCMonth()+1)+'-'+k(this.getUTCDate())+'T'+k(this.getUTCHours())+':'+k(this.getUTCMinutes())+':'+k(this.getUTCSeconds())+'Z'};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(a){return this.valueOf()}}var m=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,o=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,l,p,s={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},n;function r(c){o.lastIndex=0;return o.test(c)?'"'+c.replace(o,function(a){var b=s[a];return typeof b==='string'?b:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+c+'"'}function q(a,b){var c,d,f,g,h=l,j,i=b[a];if(i&&typeof i==='object'&&typeof i.toJSON==='function'){i=i.toJSON(a)}if(typeof n==='function'){i=n.call(b,a,i)}switch(typeof i){case'string':return r(i);case'number':return isFinite(i)?String(i):'null';case'boolean':case'null':return String(i);case'object':if(!i){return'null'}l+=p;j=[];if(Object.prototype.toString.apply(i)==='[object Array]'){g=i.length;for(c=0;c<g;c+=1){j[c]=q(c,i)||'null'}f=j.length===0?'[]':l?'[\n'+l+j.join(',\n'+l)+'\n'+h+']':'['+j.join(',')+']';l=h;return f}if(n&&typeof n==='object'){g=n.length;for(c=0;c<g;c+=1){d=n[c];if(typeof d==='string'){f=q(d,i);if(f){j.push(r(d)+(l?': ':':')+f)}}}}else{for(d in i){if(Object.hasOwnProperty.call(i,d)){f=q(d,i);if(f){j.push(r(d)+(l?': ':':')+f)}}}}f=j.length===0?'{}':l?'{\n'+l+j.join(',\n'+l)+'\n'+h+'}':'{'+j.join(',')+'}';l=h;return f}}Faye.stringify=function(a,b,c){var d;l='';p='';if(typeof c==='number'){for(d=0;d<c;d+=1){p+=' '}}else if(typeof c==='string'){p=c}n=b;if(b&&typeof b!=='function'&&(typeof b!=='object'||typeof b.length!=='number')){throw new Error('JSON.stringify');}return q('',{'':a})};if(typeof JSON.stringify!=='function'){JSON.stringify=Faye.stringify}if(typeof JSON.parse!=='function'){JSON.parse=function(g,h){var j;function i(a,b){var c,d,f=a[b];if(f&&typeof f==='object'){for(c in f){if(Object.hasOwnProperty.call(f,c)){d=i(f,c);if(d!==undefined){f[c]=d}else{delete f[c]}}}}return h.call(a,b,f)}m.lastIndex=0;if(m.test(g)){g=g.replace(m,function(a){return'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(g.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+g+')');return typeof h==='function'?i({'':j},''):j}throw new SyntaxError('JSON.parse');}}}());Faye.Transport.WebSocket=Faye.extend(Faye.Class(Faye.Transport,{UNCONNECTED:1,CONNECTING:2,CONNECTED:3,batching:false,request:function(b,c){this._7=this._7||c;this._h=this._h||{};Faye.each(b,function(a){this._h[a.id]=a},this);this.withSocket(function(a){a.send(Faye.toJSON(b))})},withSocket:function(a,b){this.callback(a,b);this.connect()},connect:function(){this._1=this._1||this.UNCONNECTED;if(this._1!==this.UNCONNECTED)return;this._1=this.CONNECTING;this._b=new WebSocket(Faye.Transport.WebSocket.getSocketUrl(this._a));var d=this;this._b.onopen=function(){delete d._7;d._1=d.CONNECTED;d.setDeferredStatus('succeeded',d._b)};this._b.onmessage=function(b){var c=[].concat(JSON.parse(b.data));Faye.each(c,function(a){delete d._h[a.id]});d.receive(c)};this._b.onclose=function(){var a=(d._1===d.CONNECTED);d.setDeferredStatus('deferred');d._1=d.UNCONNECTED;delete d._b;if(a)return d.resend();Faye.ENV.setTimeout(function(){d.connect()},1000*d._7);d._7=d._7*2}},resend:function(){var c=Faye.map(this._h,function(a,b){return b});this.request(c)}}),{WEBSOCKET_TIMEOUT:1000,getSocketUrl:function(a){return Faye.URI.parse(a).toURL().replace(/^http(s?):/ig,'ws$1:')},isUsable:function(a,b,c){if(!Faye.ENV.WebSocket)return b.call(c,false);var d=false,f=this.getSocketUrl(a),g=new WebSocket(f);g.onopen=function(){d=true;g.close();b.call(c,true);g=null};var h=function(){if(!d)b.call(c,false)};g.onclose=g.onerror=h;Faye.ENV.setTimeout(h,this.WEBSOCKET_TIMEOUT)}});Faye.extend(Faye.Transport.WebSocket.prototype,Faye.Deferrable);Faye.Transport.register('websocket',Faye.Transport.WebSocket);Faye.Transport.XHR=Faye.extend(Faye.Class(Faye.Transport,{request:function(b,c){var d=this.retry(b,c),f=Faye.URI.parse(this._a).pathname,g=this,h=Faye.ENV.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();h.open('POST',f,true);h.setRequestHeader('Content-Type','application/json');h.setRequestHeader('X-Requested-With','XMLHttpRequest');h.onreadystatechange=function(){if(h.readyState!==4)return;var a=h.status;try{if((a>=200&&a<300)||a===304||a===1223)g.receive(JSON.parse(h.responseText));else d()}catch(e){d()}finally{Faye.Event.detach(Faye.ENV,'beforeunload',j);h.onreadystatechange=function(){};h=null}};var j=function(){h.abort()};Faye.Event.on(Faye.ENV,'beforeunload',j);h.send(Faye.toJSON(b))}}),{isUsable:function(a,b,c){b.call(c,Faye.URI.parse(a).isLocal())}});Faye.Transport.register('long-polling',Faye.Transport.XHR);Faye.Transport.CORS=Faye.extend(Faye.Class(Faye.Transport,{request:function(a,b){var c=Faye.ENV.XDomainRequest?XDomainRequest:XMLHttpRequest,d=new c(),f=this.retry(a,b),g=this;d.open('POST',this._a,true);d.onload=function(){try{g.receive(JSON.parse(d.responseText))}catch(e){f()}finally{d.onload=d.onerror=null;d=null}};d.onerror=f;d.onprogress=function(){};d.send('message='+encodeURIComponent(Faye.toJSON(a)))}}),{isUsable:function(a,b,c){if(Faye.URI.parse(a).isLocal())return b.call(c,false);if(Faye.ENV.XDomainRequest)return b.call(c,true);if(Faye.ENV.XMLHttpRequest){var d=new Faye.ENV.XMLHttpRequest();return b.call(c,d.withCredentials!==undefined)}return b.call(c,false)}});Faye.Transport.register('cross-origin-long-polling',Faye.Transport.CORS);Faye.Transport.JSONP=Faye.extend(Faye.Class(Faye.Transport,{request:function(b,c){var d={message:Faye.toJSON(b)},f=document.getElementsByTagName('head')[0],g=document.createElement('script'),h=Faye.Transport.JSONP.getCallbackName(),j=Faye.URI.parse(this._a,d),i=this;var k=function(){if(!g.parentNode)return false;g.parentNode.removeChild(g);return true};Faye.ENV[h]=function(a){Faye.ENV[h]=undefined;try{delete Faye.ENV[h]}catch(e){}if(!k())return;i.receive(a)};Faye.ENV.setTimeout(function(){if(!Faye.ENV[h])return;k();i.request(b,2*c)},1000*c);j.params.jsonp=h;g.type='text/javascript';g.src=j.toURL();f.appendChild(g)}}),{_x:0,getCallbackName:function(){this._x+=1;return'__jsonp'+this._x+'__'},isUsable:function(a,b,c){b.call(c,true)}});Faye.Transport.register('callback-polling',Faye.Transport.JSONP);
1
+ if(!this.Faye)Faye={};Faye.extend=function(a,b,c){if(!b)return a;for(var d in b){if(!b.hasOwnProperty(d))continue;if(a.hasOwnProperty(d)&&c===false)continue;if(a[d]!==b[d])a[d]=b[d]}return a};Faye.extend(Faye,{VERSION:'0.6.2',BAYEUX_VERSION:'1.0',ID_LENGTH:128,JSONP_CALLBACK:'jsonpcallback',CONNECTION_TYPES:['long-polling','cross-origin-long-polling','callback-polling','websocket','in-process'],MANDATORY_CONNECTION_TYPES:['long-polling','callback-polling','in-process'],ENV:(function(){return this})(),random:function(a){a=a||this.ID_LENGTH;if(a>32){var b=Math.ceil(a/32),c='';while(b--)c+=this.random(32);return c}var d=Math.pow(2,a)-1,f=d.toString(36).length,c=Math.floor(Math.random()*d).toString(36);while(c.length<f)c='0'+c;return c},commonElement:function(a,b){for(var c=0,d=a.length;c<d;c++){if(this.indexOf(b,a[c])!==-1)return a[c]}return null},indexOf:function(a,b){for(var c=0,d=a.length;c<d;c++){if(a[c]===b)return c}return-1},each:function(a,b,c){if(a instanceof Array){for(var d=0,f=a.length;d<f;d++){if(a[d]!==undefined)b.call(c||null,a[d],d)}}else{for(var g in a){if(a.hasOwnProperty(g))b.call(c||null,g,a[g])}}},map:function(a,b,c){var d=[];this.each(a,function(){d.push(b.apply(c||null,arguments))});return d},filter:function(a,b,c){var d=[];this.each(a,function(){if(b.apply(c,arguments))d.push(arguments[0])});return d},size:function(a){var b=0;this.each(a,function(){b+=1});return b},enumEqual:function(c,d){if(d instanceof Array){if(!(c instanceof Array))return false;var f=c.length;if(f!==d.length)return false;while(f--){if(c[f]!==d[f])return false}return true}else{if(!(c instanceof Object))return false;if(this.size(d)!==this.size(c))return false;var g=true;this.each(c,function(a,b){g=g&&(d[a]===b)});return g}},asyncEach:function(a,b,c,d){var f=a.length,g=-1,h=0,i=false;var j=function(){h-=1;g+=1;if(g===f)return c&&c.call(d);b(a[g],m)};var k=function(){if(i)return;i=true;while(h>0)j();i=false};var m=function(){h+=1;k()};m()},toJSON:function(a){if(this.stringify)return this.stringify(a,function(key,value){return(this[key]instanceof Array)?this[key]:value});return JSON.stringify(a)},timestamp:function(){var b=new Date(),c=b.getFullYear(),d=b.getMonth()+1,f=b.getDate(),g=b.getHours(),h=b.getMinutes(),i=b.getSeconds();var j=function(a){return a<10?'0'+a:String(a)};return j(c)+'-'+j(d)+'-'+j(f)+' '+j(g)+':'+j(h)+':'+j(i)}});Faye.Class=function(a,b){if(typeof a!=='function'){b=a;a=Object}var c=function(){if(!this.initialize)return this;return this.initialize.apply(this,arguments)||this};var d=function(){};d.prototype=a.prototype;c.prototype=new d();Faye.extend(c.prototype,b);return c};Faye.Namespace=Faye.Class({initialize:function(){this._c={}},exists:function(a){return this._c.hasOwnProperty(a)},generate:function(){var a=Faye.random();while(this._c.hasOwnProperty(a))a=Faye.random();return this._c[a]=a},release:function(a){delete this._c[a]}});Faye.Error=Faye.Class({initialize:function(a,b,c){this.code=a;this.params=Array.prototype.slice.call(b);this.message=c},toString:function(){return this.code+':'+this.params.join(',')+':'+this.message}});Faye.Error.parse=function(a){a=a||'';if(!Faye.Grammar.ERROR.test(a))return new this(null,[],a);var b=a.split(':'),c=parseInt(b[0]),d=b[1].split(','),a=b[2];return new this(c,d,a)};Faye.Error.versionMismatch=function(){return new this(300,arguments,"Version mismatch").toString()};Faye.Error.conntypeMismatch=function(){return new this(301,arguments,"Connection types not supported").toString()};Faye.Error.extMismatch=function(){return new this(302,arguments,"Extension mismatch").toString()};Faye.Error.badRequest=function(){return new this(400,arguments,"Bad request").toString()};Faye.Error.clientUnknown=function(){return new this(401,arguments,"Unknown client").toString()};Faye.Error.parameterMissing=function(){return new this(402,arguments,"Missing required parameter").toString()};Faye.Error.channelForbidden=function(){return new this(403,arguments,"Forbidden channel").toString()};Faye.Error.channelUnknown=function(){return new this(404,arguments,"Unknown channel").toString()};Faye.Error.channelInvalid=function(){return new this(405,arguments,"Invalid channel").toString()};Faye.Error.extUnknown=function(){return new this(406,arguments,"Unknown extension").toString()};Faye.Error.publishFailed=function(){return new this(407,arguments,"Failed to publish").toString()};Faye.Error.serverError=function(){return new this(500,arguments,"Internal server error").toString()};Faye.Deferrable={callback:function(a,b){if(!a)return;if(this._s==='succeeded')return a.apply(b,this._i);this._j=this._j||[];this._j.push([a,b])},errback:function(a,b){if(!a)return;if(this._s==='failed')return a.apply(b,this._i);this._k=this._k||[];this._k.push([a,b])},setDeferredStatus:function(){var a=Array.prototype.slice.call(arguments),b=a.shift(),c;this._s=b;this._i=a;if(b==='succeeded')c=this._j;else if(b==='failed')c=this._k;if(!c)return;var d;while(d=c.shift())d[0].apply(d[1],this._i)}};Faye.Publisher={countSubscribers:function(a){if(!this._3||!this._3[a])return 0;return this._3[a].length},addSubscriber:function(a,b,c){this._3=this._3||{};var d=this._3[a]=this._3[a]||[];d.push([b,c])},removeSubscriber:function(a,b,c){if(!this._3||!this._3[a])return;if(!b){delete this._3[a];return}var d=this._3[a],f=d.length;while(f--){if(b!==d[f][0])continue;if(c&&d[f][1]!==c)continue;d.splice(f,1)}},removeSubscribers:function(){this._3={}},publishEvent:function(){var b=Array.prototype.slice.call(arguments),c=b.shift();if(!this._3||!this._3[c])return;Faye.each(this._3[c],function(a){a[0].apply(a[1],b)})}};Faye.Timeouts={addTimeout:function(a,b,c,d){this._4=this._4||{};if(this._4.hasOwnProperty(a))return;var f=this;this._4[a]=Faye.ENV.setTimeout(function(){delete f._4[a];c.call(d)},1000*b)},removeTimeout:function(a){this._4=this._4||{};var b=this._4[a];if(!b)return;clearTimeout(b);delete this._4[a]}};Faye.Logging={LOG_LEVELS:{error:3,warn:2,info:1,debug:0},logLevel:'error',log:function(a,b){if(!Faye.logger)return;var c=Faye.Logging.LOG_LEVELS;if(c[Faye.Logging.logLevel]>c[b])return;var a=Array.prototype.slice.apply(a),d=' ['+b.toUpperCase()+'] [Faye',f=this.className,g=a.shift().replace(/\?/g,function(){try{return Faye.toJSON(a.shift())}catch(e){return'[Object]'}});for(var h in Faye){if(f)continue;if(typeof Faye[h]!=='function')continue;if(this instanceof Faye[h])f=h}if(f)d+='.'+f;d+='] ';Faye.logger(Faye.timestamp()+d+g)}};Faye.each(Faye.Logging.LOG_LEVELS,function(a,b){Faye.Logging[a]=function(){this.log(arguments,a)}});Faye.Grammar={LOWALPHA:/^[a-z]$/,UPALPHA:/^[A-Z]$/,ALPHA:/^([a-z]|[A-Z])$/,DIGIT:/^[0-9]$/,ALPHANUM:/^(([a-z]|[A-Z])|[0-9])$/,MARK:/^(\-|\_|\!|\~|\(|\)|\$|\@)$/,STRING:/^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*$/,TOKEN:/^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+$/,INTEGER:/^([0-9])+$/,CHANNEL_SEGMENT:/^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+$/,CHANNEL_SEGMENTS:/^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*$/,CHANNEL_NAME:/^\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*$/,WILD_CARD:/^\*{1,2}$/,CHANNEL_PATTERN:/^(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*\/\*{1,2}$/,VERSION_ELEMENT:/^(([a-z]|[A-Z])|[0-9])(((([a-z]|[A-Z])|[0-9])|\-|\_))*$/,VERSION:/^([0-9])+(\.(([a-z]|[A-Z])|[0-9])(((([a-z]|[A-Z])|[0-9])|\-|\_))*)*$/,CLIENT_ID:/^((([a-z]|[A-Z])|[0-9]))+$/,ID:/^((([a-z]|[A-Z])|[0-9]))+$/,ERROR_MESSAGE:/^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*$/,ERROR_ARGS:/^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*(,(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*)*$/,ERROR_CODE:/^[0-9][0-9][0-9]$/,ERROR:/^([0-9][0-9][0-9]:(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*(,(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*)*:(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*|[0-9][0-9][0-9]::(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*)$/};Faye.Extensible={addExtension:function(a){this._5=this._5||[];this._5.push(a);if(a.added)a.added()},removeExtension:function(a){if(!this._5)return;var b=this._5.length;while(b--){if(this._5[b]!==a)continue;this._5.splice(b,1);if(a.removed)a.removed()}},pipeThroughExtensions:function(c,d,f,g){this.debug('Passing through ? extensions: ?',c,d);if(!this._5)return f.call(g,d);var h=this._5.slice();var i=function(a){if(!a)return f.call(g,a);var b=h.shift();if(!b)return f.call(g,a);if(b[c])b[c](a,i);else i(a)};i(d)}};Faye.extend(Faye.Extensible,Faye.Logging);Faye.Channel=Faye.Class({initialize:function(a){this.id=this.name=a},push:function(a){this.publishEvent('message',a)},isUnused:function(){return this.countSubscribers('message')===0}});Faye.extend(Faye.Channel.prototype,Faye.Publisher);Faye.extend(Faye.Channel,{HANDSHAKE:'/meta/handshake',CONNECT:'/meta/connect',SUBSCRIBE:'/meta/subscribe',UNSUBSCRIBE:'/meta/unsubscribe',DISCONNECT:'/meta/disconnect',META:'meta',SERVICE:'service',expand:function(a){var b=this.parse(a),c=['/**',a];var d=b.slice();d[d.length-1]='*';c.push(this.unparse(d));for(var f=1,g=b.length;f<g;f++){d=b.slice(0,f);d.push('**');c.push(this.unparse(d))}return c},isValid:function(a){return Faye.Grammar.CHANNEL_NAME.test(a)||Faye.Grammar.CHANNEL_PATTERN.test(a)},parse:function(a){if(!this.isValid(a))return null;return a.split('/').slice(1)},unparse:function(a){return'/'+a.join('/')},isMeta:function(a){var b=this.parse(a);return b?(b[0]===this.META):null},isService:function(a){var b=this.parse(a);return b?(b[0]===this.SERVICE):null},isSubscribable:function(a){if(!this.isValid(a))return null;return!this.isMeta(a)&&!this.isService(a)},Set:Faye.Class({initialize:function(){this._2={}},getKeys:function(){var c=[];Faye.each(this._2,function(a,b){c.push(a)});return c},remove:function(a){delete this._2[a]},hasSubscription:function(a){return this._2.hasOwnProperty(a)},subscribe:function(c,d,f){if(!d)return;Faye.each(c,function(a){var b=this._2[a]=this._2[a]||new Faye.Channel(a);b.addSubscriber('message',d,f)},this)},unsubscribe:function(a,b,c){var d=this._2[a];if(!d)return false;d.removeSubscriber('message',b,c);if(d.isUnused()){this.remove(a);return true}else{return false}},distributeMessage:function(c){var d=Faye.Channel.expand(c.channel);Faye.each(d,function(a){var b=this._2[a];if(b)b.publishEvent('message',c.data)},this)}})});Faye.Subscription=Faye.Class({initialize:function(a,b,c,d){this._8=a;this._2=b;this._l=c;this._m=d;this._t=false},cancel:function(){if(this._t)return;this._8.unsubscribe(this._2,this._l,this._m);this._t=true},unsubscribe:function(){this.cancel()}});Faye.extend(Faye.Subscription.prototype,Faye.Deferrable);Faye.Client=Faye.Class({UNCONNECTED:1,CONNECTING:2,CONNECTED:3,DISCONNECTED:4,HANDSHAKE:'handshake',RETRY:'retry',NONE:'none',CONNECTION_TIMEOUT:60.0,DEFAULT_ENDPOINT:'/bayeux',INTERVAL:0.0,initialize:function(b,c){this.info('New client created for ?',b);this.endpoint=b||this.DEFAULT_ENDPOINT;this._u=c||{};Faye.Transport.get(this,Faye.MANDATORY_CONNECTION_TYPES,function(a){this._d=a},this);this._1=this.UNCONNECTED;this._2=new Faye.Channel.Set();this._y=new Faye.Namespace();this._n={};this._6={reconnect:this.RETRY,interval:1000*(this._u.interval||this.INTERVAL),timeout:1000*(this._u.timeout||this.CONNECTION_TIMEOUT)};if(Faye.Event)Faye.Event.on(Faye.ENV,'beforeunload',this.disconnect,this)},getClientId:function(){return this._0},getState:function(){switch(this._1){case this.UNCONNECTED:return'UNCONNECTED';case this.CONNECTING:return'CONNECTING';case this.CONNECTED:return'CONNECTED';case this.DISCONNECTED:return'DISCONNECTED'}},handshake:function(c,d){if(this._6.reconnect===this.NONE)return;if(this._1!==this.UNCONNECTED)return;this._1=this.CONNECTING;var f=this;this.info('Initiating handshake with ?',this.endpoint);this._9({channel:Faye.Channel.HANDSHAKE,version:Faye.BAYEUX_VERSION,supportedConnectionTypes:[this._d.connectionType]},function(b){if(b.successful){this._1=this.CONNECTED;this._0=b.clientId;Faye.Transport.get(this,b.supportedConnectionTypes,function(a){this._d=a},this);this.info('Handshake successful: ?',this._0);this.subscribe(this._2.getKeys(),true);if(c)c.call(d)}else{this.info('Handshake unsuccessful');Faye.ENV.setTimeout(function(){f.handshake(c,d)},this._6.interval);this._1=this.UNCONNECTED}},this)},connect:function(a,b){if(this._6.reconnect===this.NONE)return;if(this._1===this.DISCONNECTED)return;if(this._1===this.UNCONNECTED)return this.handshake(function(){this.connect(a,b)},this);this.callback(a,b);if(this._1!==this.CONNECTED)return;this.info('Calling deferred actions for ?',this._0);this.setDeferredStatus('succeeded');this.setDeferredStatus('deferred');if(this._o)return;this._o=true;this.info('Initiating connection for ?',this._0);this._9({channel:Faye.Channel.CONNECT,clientId:this._0,connectionType:this._d.connectionType},this._v,this)},disconnect:function(){if(this._1!==this.CONNECTED)return;this._1=this.DISCONNECTED;this.info('Disconnecting ?',this._0);this._9({channel:Faye.Channel.DISCONNECT,clientId:this._0});this.info('Clearing channel listeners for ?',this._0);this._2=new Faye.Channel.Set()},subscribe:function(c,d,f){if(c instanceof Array)return Faye.each(c,function(channel){this.subscribe(channel,d,f)},this);var g=new Faye.Subscription(this,c,d,f);var h=(d===true);if(!h&&this._2.hasSubscription(c)){this._2.subscribe([c],d,f);g.setDeferredStatus('succeeded');return g}this.connect(function(){this.info('Client ? attempting to subscribe to ?',this._0,c);this._9({channel:Faye.Channel.SUBSCRIBE,clientId:this._0,subscription:c},function(a){if(!a.successful)return g.setDeferredStatus('failed',Faye.Error.parse(a.error));var b=[].concat(a.subscription);this.info('Subscription acknowledged for ? to ?',this._0,b);this._2.subscribe(b,d,f);g.setDeferredStatus('succeeded')},this)},this);return g},unsubscribe:function(c,d,f){if(c instanceof Array)return Faye.each(c,function(channel){this.unsubscribe(channel,d,f)},this);var g=this._2.unsubscribe(c,d,f);if(!g)return;this.connect(function(){this.info('Client ? attempting to unsubscribe from ?',this._0,c);this._9({channel:Faye.Channel.UNSUBSCRIBE,clientId:this._0,subscription:c},function(a){if(!a.successful)return;var b=[].concat(a.subscription);this.info('Unsubscription acknowledged for ? from ?',this._0,b)},this)},this)},publish:function(a,b){if(!Faye.Grammar.CHANNEL_NAME.test(a))throw new Error("Cannot publish: '"+a+"' is not a valid channel name");this.connect(function(){this.info('Client ? queueing published message to ?: ?',this._0,a,b);this._9({channel:a,data:b,clientId:this._0})},this)},receiveMessage:function(c){this.pipeThroughExtensions('incoming',c,function(a){if(!a)return;if(a.advice)this._z(a.advice);var b=this._n[a.id];if(b){delete this._n[a.id];b[0].call(b[1],a)}this._A(a)},this)},_9:function(b,c,d){b.id=this._y.generate();if(c)this._n[b.id]=[c,d];this.pipeThroughExtensions('outgoing',b,function(a){if(!a)return;this._d.send(a,this._6.timeout/1000)},this)},_z:function(a){Faye.extend(this._6,a);if(this._6.reconnect===this.HANDSHAKE&&this._1!==this.DISCONNECTED){this._1=this.UNCONNECTED;this._0=null;this._v()}},_A:function(a){if(!a.channel||!a.data)return;this.info('Client ? calling listeners for ? with ?',this._0,a.channel,a.data);this._2.distributeMessage(a)},_B:function(){if(!this._o)return;this._o=null;this.info('Closed connection for ?',this._0)},_v:function(){this._B();var a=this;Faye.ENV.setTimeout(function(){a.connect()},this._6.interval)}});Faye.extend(Faye.Client.prototype,Faye.Deferrable);Faye.extend(Faye.Client.prototype,Faye.Logging);Faye.extend(Faye.Client.prototype,Faye.Extensible);Faye.Transport=Faye.extend(Faye.Class({MAX_DELAY:0.0,batching:true,initialize:function(a,b){this.debug('Created new ? transport for ?',this.connectionType,b);this._8=a;this._a=b;this._e=[]},send:function(a,b){this.debug('Client ? sending message to ?: ?',this._8._0,this._a,a);if(!this.batching)return this.request([a],b);this._e.push(a);this._7=b;if(a.channel===Faye.Channel.HANDSHAKE)return this.flush();if(a.channel===Faye.Channel.CONNECT)this._p=a;this.addTimeout('publish',this.MAX_DELAY,this.flush,this)},flush:function(){this.removeTimeout('publish');if(this._e.length>1&&this._p)this._p.advice={timeout:0};this.request(this._e,this._7);this._p=null;this._e=[]},receive:function(a){this.debug('Client ? received from ?: ?',this._8._0,this._a,a);Faye.each(a,this._8.receiveMessage,this._8)},retry:function(a,b){var c=this;return function(){Faye.ENV.setTimeout(function(){c.request(a,2*b)},1000*b)}}}),{get:function(g,h,i,j){var k=g.endpoint;if(h===undefined)h=this.supportedConnectionTypes();Faye.asyncEach(this._q,function(b,c){var d=b[0],f=b[1];if(Faye.indexOf(h,d)<0)return c();f.isUsable(k,function(a){if(a)i.call(j,new f(g,k));else c()})},function(){throw new Error('Could not find a usable connection type for '+k);})},register:function(a,b){this._q.push([a,b]);b.prototype.connectionType=a},_q:[],supportedConnectionTypes:function(){return Faye.map(this._q,function(a){return a[0]})}});Faye.extend(Faye.Transport.prototype,Faye.Logging);Faye.extend(Faye.Transport.prototype,Faye.Timeouts);Faye.Event={_f:[],on:function(a,b,c,d){var f=function(){c.call(d)};if(a.addEventListener)a.addEventListener(b,f,false);else a.attachEvent('on'+b,f);this._f.push({_g:a,_r:b,_l:c,_m:d,_w:f})},detach:function(a,b,c,d){var f=this._f.length,g;while(f--){g=this._f[f];if((a&&a!==g._g)||(b&&b!==g._r)||(c&&c!==g._l)||(d&&d!==g._m))continue;if(g._g.removeEventListener)g._g.removeEventListener(g._r,g._w,false);else g._g.detachEvent('on'+g._r,g._w);this._f.splice(f,1);g=null}}};Faye.Event.on(Faye.ENV,'unload',Faye.Event.detach,Faye.Event);Faye.URI=Faye.extend(Faye.Class({queryString:function(){var c=[],d;Faye.each(this.params,function(a,b){c.push(encodeURIComponent(a)+'='+encodeURIComponent(b))});return c.join('&')},isLocal:function(){var a=Faye.URI.parse(Faye.ENV.location.href);var b=(a.hostname!==this.hostname)||(a.port!==this.port)||(a.protocol!==this.protocol);return!b},toURL:function(){var a=this.queryString();return this.protocol+this.hostname+':'+this.port+this.pathname+(a?'?'+a:'')}}),{parse:function(d,f){if(typeof d!=='string')return d;var g=new this();var h=function(b,c){d=d.replace(c,function(a){if(a)g[b]=a;return''})};h('protocol',/^https?\:\/+/);h('hostname',/^[^\/\:]+/);h('port',/^:[0-9]+/);Faye.extend(g,{protocol:'http://',hostname:Faye.ENV.location.hostname,port:Faye.ENV.location.port},false);if(!g.port)g.port=(g.protocol==='https://')?'443':'80';g.port=g.port.replace(/\D/g,'');var i=d.split('?'),j=i.shift(),k=i.join('?'),m=k?k.split('&'):[],o=m.length,l={};while(o--){i=m[o].split('=');l[decodeURIComponent(i[0]||'')]=decodeURIComponent(i[1]||'')}if(typeof f==='object')Faye.extend(l,f);g.pathname=j;g.params=l;return g}});if(!this.JSON){JSON={}}(function(){function k(a){return a<10?'0'+a:a}if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(a){return this.getUTCFullYear()+'-'+k(this.getUTCMonth()+1)+'-'+k(this.getUTCDate())+'T'+k(this.getUTCHours())+':'+k(this.getUTCMinutes())+':'+k(this.getUTCSeconds())+'Z'};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(a){return this.valueOf()}}var m=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,o=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,l,p,s={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},n;function r(c){o.lastIndex=0;return o.test(c)?'"'+c.replace(o,function(a){var b=s[a];return typeof b==='string'?b:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+c+'"'}function q(a,b){var c,d,f,g,h=l,i,j=b[a];if(j&&typeof j==='object'&&typeof j.toJSON==='function'){j=j.toJSON(a)}if(typeof n==='function'){j=n.call(b,a,j)}switch(typeof j){case'string':return r(j);case'number':return isFinite(j)?String(j):'null';case'boolean':case'null':return String(j);case'object':if(!j){return'null'}l+=p;i=[];if(Object.prototype.toString.apply(j)==='[object Array]'){g=j.length;for(c=0;c<g;c+=1){i[c]=q(c,j)||'null'}f=i.length===0?'[]':l?'[\n'+l+i.join(',\n'+l)+'\n'+h+']':'['+i.join(',')+']';l=h;return f}if(n&&typeof n==='object'){g=n.length;for(c=0;c<g;c+=1){d=n[c];if(typeof d==='string'){f=q(d,j);if(f){i.push(r(d)+(l?': ':':')+f)}}}}else{for(d in j){if(Object.hasOwnProperty.call(j,d)){f=q(d,j);if(f){i.push(r(d)+(l?': ':':')+f)}}}}f=i.length===0?'{}':l?'{\n'+l+i.join(',\n'+l)+'\n'+h+'}':'{'+i.join(',')+'}';l=h;return f}}Faye.stringify=function(a,b,c){var d;l='';p='';if(typeof c==='number'){for(d=0;d<c;d+=1){p+=' '}}else if(typeof c==='string'){p=c}n=b;if(b&&typeof b!=='function'&&(typeof b!=='object'||typeof b.length!=='number')){throw new Error('JSON.stringify');}return q('',{'':a})};if(typeof JSON.stringify!=='function'){JSON.stringify=Faye.stringify}if(typeof JSON.parse!=='function'){JSON.parse=function(g,h){var i;function j(a,b){var c,d,f=a[b];if(f&&typeof f==='object'){for(c in f){if(Object.hasOwnProperty.call(f,c)){d=j(f,c);if(d!==undefined){f[c]=d}else{delete f[c]}}}}return h.call(a,b,f)}m.lastIndex=0;if(m.test(g)){g=g.replace(m,function(a){return'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(g.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){i=eval('('+g+')');return typeof h==='function'?j({'':i},''):i}throw new SyntaxError('JSON.parse');}}}());Faye.Transport.WebSocket=Faye.extend(Faye.Class(Faye.Transport,{UNCONNECTED:1,CONNECTING:2,CONNECTED:3,batching:false,request:function(b,c){this._7=this._7||c;this._h=this._h||{};Faye.each(b,function(a){this._h[a.id]=a},this);this.withSocket(function(a){a.send(Faye.toJSON(b))})},withSocket:function(a,b){this.callback(a,b);this.connect()},connect:function(){this._1=this._1||this.UNCONNECTED;if(this._1!==this.UNCONNECTED)return;this._1=this.CONNECTING;this._b=new WebSocket(Faye.Transport.WebSocket.getSocketUrl(this._a));var d=this;this._b.onopen=function(){delete d._7;d._1=d.CONNECTED;d.setDeferredStatus('succeeded',d._b)};this._b.onmessage=function(b){var c=[].concat(JSON.parse(b.data));Faye.each(c,function(a){delete d._h[a.id]});d.receive(c)};this._b.onclose=function(){var a=(d._1===d.CONNECTED);d.setDeferredStatus('deferred');d._1=d.UNCONNECTED;delete d._b;if(a)return d.resend();Faye.ENV.setTimeout(function(){d.connect()},1000*d._7);d._7=d._7*2}},resend:function(){var c=Faye.map(this._h,function(a,b){return b});this.request(c)}}),{WEBSOCKET_TIMEOUT:1000,getSocketUrl:function(a){return Faye.URI.parse(a).toURL().replace(/^http(s?):/ig,'ws$1:')},isUsable:function(a,b,c){if(!Faye.ENV.WebSocket)return b.call(c,false);var d=false,f=false,g=this.getSocketUrl(a),h=new WebSocket(g);h.onopen=function(){d=true;h.close();b.call(c,true);f=true;h=null};var i=function(){if(!f&&!d)b.call(c,false);f=true};h.onclose=h.onerror=i;Faye.ENV.setTimeout(i,this.WEBSOCKET_TIMEOUT)}});Faye.extend(Faye.Transport.WebSocket.prototype,Faye.Deferrable);Faye.Transport.register('websocket',Faye.Transport.WebSocket);Faye.Transport.XHR=Faye.extend(Faye.Class(Faye.Transport,{request:function(b,c){var d=this.retry(b,c),f=Faye.URI.parse(this._a).pathname,g=this,h=Faye.ENV.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();h.open('POST',f,true);h.setRequestHeader('Content-Type','application/json');h.setRequestHeader('X-Requested-With','XMLHttpRequest');h.onreadystatechange=function(){if(h.readyState!==4)return;var a=h.status;try{if((a>=200&&a<300)||a===304||a===1223)g.receive(JSON.parse(h.responseText));else d()}catch(e){d()}finally{Faye.Event.detach(Faye.ENV,'beforeunload',i);h.onreadystatechange=function(){};h=null}};var i=function(){h.abort()};Faye.Event.on(Faye.ENV,'beforeunload',i);h.send(Faye.toJSON(b))}}),{isUsable:function(a,b,c){b.call(c,Faye.URI.parse(a).isLocal())}});Faye.Transport.register('long-polling',Faye.Transport.XHR);Faye.Transport.CORS=Faye.extend(Faye.Class(Faye.Transport,{request:function(a,b){var c=Faye.ENV.XDomainRequest?XDomainRequest:XMLHttpRequest,d=new c(),f=this.retry(a,b),g=this;d.open('POST',this._a,true);d.onload=function(){try{g.receive(JSON.parse(d.responseText))}catch(e){f()}finally{d.onload=d.onerror=null;d=null}};d.onerror=f;d.onprogress=function(){};d.send('message='+encodeURIComponent(Faye.toJSON(a)))}}),{isUsable:function(a,b,c){if(Faye.URI.parse(a).isLocal())return b.call(c,false);if(Faye.ENV.XDomainRequest)return b.call(c,true);if(Faye.ENV.XMLHttpRequest){var d=new Faye.ENV.XMLHttpRequest();return b.call(c,d.withCredentials!==undefined)}return b.call(c,false)}});Faye.Transport.register('cross-origin-long-polling',Faye.Transport.CORS);Faye.Transport.JSONP=Faye.extend(Faye.Class(Faye.Transport,{request:function(b,c){var d={message:Faye.toJSON(b)},f=document.getElementsByTagName('head')[0],g=document.createElement('script'),h=Faye.Transport.JSONP.getCallbackName(),i=Faye.URI.parse(this._a,d),j=this;var k=function(){if(!g.parentNode)return false;g.parentNode.removeChild(g);return true};Faye.ENV[h]=function(a){Faye.ENV[h]=undefined;try{delete Faye.ENV[h]}catch(e){}if(!k())return;j.receive(a)};Faye.ENV.setTimeout(function(){if(!Faye.ENV[h])return;k();j.request(b,2*c)},1000*c);i.params.jsonp=h;g.type='text/javascript';g.src=i.toURL();f.appendChild(g)}}),{_x:0,getCallbackName:function(){this._x+=1;return'__jsonp'+this._x+'__'},isUsable:function(a,b,c){b.call(c,true)}});Faye.Transport.register('callback-polling',Faye.Transport.JSONP);
@@ -5,7 +5,7 @@ require 'eventmachine'
5
5
  require 'json'
6
6
 
7
7
  module Faye
8
- VERSION = '0.6.1'
8
+ VERSION = '0.6.2'
9
9
 
10
10
  ROOT = File.expand_path(File.dirname(__FILE__))
11
11
 
@@ -54,63 +54,74 @@ module Faye
54
54
  request = Rack::Request.new(env)
55
55
 
56
56
  unless request.path_info =~ @endpoint_re
57
+ env['faye.client'] = get_client
57
58
  return @app ? @app.call(env) :
58
59
  [404, TYPE_TEXT, ["Sure you're not looking for #{@endpoint} ?"]]
59
60
  end
60
61
 
61
- if env['HTTP_UPGRADE'] == 'WebSocket'
62
- return handle_upgrade(request)
63
- end
62
+ return handle_options(request) if env['REQUEST_METHOD'] == 'OPTIONS'
63
+ return handle_upgrade(request) if env['HTTP_UPGRADE'] == 'WebSocket'
64
+ return [200, TYPE_SCRIPT, File.new(SCRIPT_PATH)] if request.path_info =~ /\.js$/
65
+ handle_request(request)
66
+ end
67
+
68
+ private
69
+
70
+ def handle_request(request)
71
+ json_msg = message_from_request(request)
72
+ message = JSON.parse(json_msg)
73
+ jsonp = request.params['jsonp'] || JSONP_CALLBACK
74
+ head = request.get? ? TYPE_SCRIPT.dup : TYPE_JSON.dup
75
+ origin = request.env['HTTP_ORIGIN']
76
+ callback = request.env['async.callback']
77
+ body = DeferredBody.new
64
78
 
65
- if request.path_info =~ /\.js$/
66
- return [200, TYPE_SCRIPT, File.new(SCRIPT_PATH)]
67
- end
79
+ debug 'Received ?: ?', request.env['REQUEST_METHOD'], json_msg
80
+ @server.flush_connection(message) if request.get?
68
81
 
69
- begin
70
- json_msg = message_from_request(request)
71
- message = JSON.parse(json_msg)
72
- jsonp = request.params['jsonp'] || JSONP_CALLBACK
73
- head = request.get? ? TYPE_SCRIPT.dup : TYPE_JSON.dup
74
- origin = request.env['HTTP_ORIGIN']
75
- callback = env['async.callback']
76
- body = DeferredBody.new
77
-
78
- debug 'Received ?: ?', env['REQUEST_METHOD'], json_msg
79
- @server.flush_connection(message) if request.get?
80
-
81
- head['Access-Control-Allow-Origin'] = origin if origin
82
- callback.call [200, head, body]
83
-
84
- @server.process(message, false) do |replies|
85
- response = JSON.unparse(replies)
86
- response = "#{ jsonp }(#{ response });" if request.get?
87
- debug 'Returning ?', response
88
- body.succeed(response)
89
- end
90
-
91
- ASYNC_RESPONSE
92
-
93
- rescue
94
- [400, TYPE_TEXT, ['Bad request']]
82
+ head['Access-Control-Allow-Origin'] = origin if origin
83
+ callback.call [200, head, body]
84
+
85
+ @server.process(message, false) do |replies|
86
+ response = JSON.unparse(replies)
87
+ response = "#{ jsonp }(#{ response });" if request.get?
88
+ debug 'Returning ?', response
89
+ body.succeed(response)
95
90
  end
91
+
92
+ ASYNC_RESPONSE
93
+
94
+ rescue
95
+ [400, TYPE_TEXT, ['Bad request']]
96
96
  end
97
97
 
98
- private
99
-
100
98
  def message_from_request(request)
101
- return request.params['message'] unless request.post?
99
+ message = request.params['message']
100
+ return message if message
102
101
 
103
102
  # Some clients do not send a content-type, e.g.
104
103
  # Internet Explorer when using cross-origin-long-polling
104
+ # Some use application/xml when using CORS
105
105
  content_type = request.env['CONTENT_TYPE'] || ''
106
106
 
107
- case content_type.split(';').first
108
- when 'application/json' then request.body.read
109
- when 'text/plain' then CGI.parse(request.body.read)['message'][0]
110
- else request.params['message']
107
+ if content_type.split(';').first == 'application/json'
108
+ request.body.read
109
+ else
110
+ CGI.parse(request.body.read)['message'][0]
111
111
  end
112
112
  end
113
113
 
114
+ def handle_options(request)
115
+ headers = {
116
+ 'Access-Control-Allow-Origin' => '*',
117
+ 'Access-Control-Allow-Credentials' => 'false',
118
+ 'Access-Control-Max-Age' => '86400',
119
+ 'Access-Control-Allow-Methods' => 'POST, GET, PUT, DELETE, OPTIONS',
120
+ 'Access-Control-Allow-Headers' => 'Accept, Content-Type, X-Requested-With'
121
+ }
122
+ [200, headers, ['']]
123
+ end
124
+
114
125
  def handle_upgrade(request)
115
126
  socket = Faye::WebSocket.new(request)
116
127
 
@@ -11,24 +11,34 @@ module Faye
11
11
 
12
12
  host = @options[:host] || DEFAULT_HOST
13
13
  port = @options[:port] || DEFAULT_PORT
14
+ db = @options[:database] || 0
15
+ auth = @options[:password]
16
+ @ns = @options[:namespace] || ''
14
17
 
15
18
  @redis = EventMachine::Hiredis::Client.connect(host, port)
16
19
  @subscriber = EventMachine::Hiredis::Client.connect(host, port)
17
20
 
18
- @subscriber.subscribe('/notifications')
21
+ if auth
22
+ @redis.auth(auth)
23
+ @subscriber.auth(auth)
24
+ end
25
+ @redis.select(db)
26
+ @subscriber.select(db)
27
+
28
+ @subscriber.subscribe(@ns + '/notifications')
19
29
  @subscriber.on(:message) do |topic, message|
20
- empty_queue(message) if topic == '/notifications'
30
+ empty_queue(message) if topic == @ns + '/notifications'
21
31
  end
22
32
  end
23
33
 
24
34
  def disconnect
25
- @subscriber.unsubscribe('/notifications')
35
+ @subscriber.unsubscribe(@ns + '/notifications')
26
36
  end
27
37
 
28
38
  def create_client(&callback)
29
39
  init
30
40
  client_id = Faye.random
31
- @redis.sadd('/clients', client_id) do |added|
41
+ @redis.sadd(@ns + '/clients', client_id) do |added|
32
42
  if added == 0
33
43
  create_client(&callback)
34
44
  else
@@ -41,9 +51,13 @@ module Faye
41
51
 
42
52
  def destroy_client(client_id, &callback)
43
53
  init
44
- @redis.srem('/clients', client_id)
45
- @redis.del("/clients/#{client_id}/messages")
46
- @redis.smembers("/clients/#{client_id}/channels") do |channels|
54
+ @redis.srem(@ns + '/clients', client_id)
55
+ @redis.del(@ns + "/clients/#{client_id}/messages")
56
+
57
+ remove_timeout(client_id)
58
+ @redis.del(@ns + "/clients/#{client_id}/ping")
59
+
60
+ @redis.smembers(@ns + "/clients/#{client_id}/channels") do |channels|
47
61
  n, i = channels.size, 0
48
62
  if n == 0
49
63
  debug 'Destroyed client ?', client_id
@@ -64,7 +78,7 @@ module Faye
64
78
 
65
79
  def client_exists(client_id, &callback)
66
80
  init
67
- @redis.sismember('/clients', client_id) do |exists|
81
+ @redis.sismember(@ns + '/clients', client_id) do |exists|
68
82
  callback.call(exists != 0)
69
83
  end
70
84
  end
@@ -77,9 +91,9 @@ module Faye
77
91
 
78
92
  debug 'Ping ?, ?', client_id, timeout
79
93
  remove_timeout(client_id)
80
- @redis.set("/clients/#{client_id}/ping", time)
94
+ @redis.set(@ns + "/clients/#{client_id}/ping", time)
81
95
  add_timeout(client_id, 2 * timeout) do
82
- @redis.get("/clients/#{client_id}/ping") do |ping|
96
+ @redis.get(@ns + "/clients/#{client_id}/ping") do |ping|
83
97
  destroy_client(client_id) if ping == time
84
98
  end
85
99
  end
@@ -87,8 +101,8 @@ module Faye
87
101
 
88
102
  def subscribe(client_id, channel, &callback)
89
103
  init
90
- @redis.sadd("/clients/#{client_id}/channels", channel)
91
- @redis.sadd("/channels#{channel}", client_id) do
104
+ @redis.sadd(@ns + "/clients/#{client_id}/channels", channel)
105
+ @redis.sadd(@ns + "/channels#{channel}", client_id) do
92
106
  debug 'Subscribed client ? to channel ?', client_id, channel
93
107
  callback.call if callback
94
108
  end
@@ -96,8 +110,8 @@ module Faye
96
110
 
97
111
  def unsubscribe(client_id, channel, &callback)
98
112
  init
99
- @redis.srem("/clients/#{client_id}/channels", channel)
100
- @redis.srem("/channels#{channel}", client_id) do
113
+ @redis.srem(@ns + "/clients/#{client_id}/channels", channel)
114
+ @redis.srem(@ns + "/channels#{channel}", client_id) do
101
115
  debug 'Unsubscribed client ? from channel ?', client_id, channel
102
116
  callback.call if callback
103
117
  end
@@ -109,11 +123,11 @@ module Faye
109
123
  json_message = JSON.dump(message)
110
124
  channels = Channel.expand(message['channel'])
111
125
  channels.each do |channel|
112
- @redis.smembers("/channels#{channel}") do |clients|
126
+ @redis.smembers(@ns + "/channels#{channel}") do |clients|
113
127
  clients.each do |client_id|
114
128
  debug 'Queueing for client ?: ?', client_id, message
115
- @redis.sadd("/clients/#{client_id}/messages", json_message)
116
- @redis.publish('/notifications', client_id)
129
+ @redis.sadd(@ns + "/clients/#{client_id}/messages", json_message)
130
+ @redis.publish(@ns + '/notifications', client_id)
117
131
  end
118
132
  end
119
133
  end
@@ -125,7 +139,7 @@ module Faye
125
139
  return unless conn = connection(client_id, false)
126
140
  init
127
141
 
128
- key = "/clients/#{client_id}/messages"
142
+ key = @ns + "/clients/#{client_id}/messages"
129
143
  @redis.smembers(key) do |json_messages|
130
144
  json_messages.each do |json_message|
131
145
  @redis.srem(key, json_message)
@@ -83,7 +83,8 @@ JS.ENV.EngineSteps = JS.Test.asyncSteps({
83
83
 
84
84
  clean_redis_db: function(resume) {
85
85
  this.engine.disconnect()
86
- var redis = require('redis').createClient()
86
+ var redis = require('redis').createClient(6379, 'localhost', {no_ready_check: true})
87
+ redis.auth(this.engineOpts.password)
87
88
  redis.flushall(function() {
88
89
  redis.end()
89
90
  resume()
@@ -94,13 +95,18 @@ JS.ENV.EngineSteps = JS.Test.asyncSteps({
94
95
  JS.ENV.EngineSpec = JS.Test.describe("Pub/sub engines", function() { with(this) {
95
96
  include(JS.Test.Helpers)
96
97
 
98
+ define("create_engine", function() { with(this) {
99
+ var opts = Faye.extend(options(), engineOpts)
100
+ return new engineKlass(opts)
101
+ }})
102
+
97
103
  sharedExamplesFor("faye engine", function() { with(this) {
98
104
  include(EngineSteps)
99
105
 
100
106
  define("options", function() { return {timeout: 1} })
101
107
 
102
108
  before(function() { with(this) {
103
- this.engine = new engineKlass(options())
109
+ this.engine = create_engine()
104
110
  create_client("alice")
105
111
  create_client("bob")
106
112
  create_client("carol")
@@ -278,8 +284,8 @@ JS.ENV.EngineSpec = JS.Test.describe("Pub/sub engines", function() { with(this)
278
284
  define("options", function() { return {timeout: 1} })
279
285
 
280
286
  before(function() { with(this) {
281
- this.left = new engineKlass(options())
282
- this.right = new engineKlass(options())
287
+ this.left = create_engine()
288
+ this.right = create_engine()
283
289
  this.engine = left
284
290
 
285
291
  create_client("alice")
@@ -304,13 +310,21 @@ JS.ENV.EngineSpec = JS.Test.describe("Pub/sub engines", function() { with(this)
304
310
  }})
305
311
 
306
312
  describe("Faye.Engine.Memory", function() { with(this) {
307
- before(function() { this.engineKlass = Faye.Engine.Memory })
313
+ before(function() {
314
+ this.engineKlass = Faye.Engine.Memory
315
+ this.engineOpts = {}
316
+ })
317
+
308
318
  itShouldBehaveLike("faye engine")
309
319
  }})
310
320
 
311
321
  describe("Faye.Engine.Redis", function() { with(this) {
312
- before(function() { this.engineKlass = Faye.Engine.Redis })
322
+ before(function() {
323
+ this.engineKlass = Faye.Engine.Redis
324
+ this.engineOpts = {password: "foobared", namespace: new Date().getTime().toString()}
325
+ })
313
326
  after(function() { this.clean_redis_db() })
327
+
314
328
  itShouldBehaveLike("faye engine")
315
329
  describe("distribution", function() { with(this) {
316
330
  itShouldBehaveLike("distributed engine")
@@ -112,35 +112,46 @@ JS.ENV.NodeAdapterSpec = JS.Test.describe("NodeAdapter", function() { with(this)
112
112
 
113
113
  describe("POST requests", function() { with(this) {
114
114
  describe("with cross-origin access control", function() { with(this) {
115
- before(function() { with(this) {
116
- header("Origin", "http://example.com")
117
- header("Content-Type", "text/plain")
118
- }})
119
-
120
- it("returns a matching cross-origin access control header", function() { with(this) {
121
- stub(server, "process").yields([[]])
122
- post("/bayeux", {message: "[]"})
123
- check_access_control_origin("http://example.com")
124
- }})
125
-
126
- it("forwards the message param onto the server", function() { with(this) {
127
- expect(server, "process").given({channel: "/plain"}, false).yielding([[]])
128
- post("/bayeux", "message=%7B%22channel%22%3A%22%2Fplain%22%7D")
115
+ sharedBehavior("cross-origin request", function() { with(this) {
116
+ before(function() { with(this) {
117
+ header("Origin", "http://example.com")
118
+ }})
119
+
120
+ it("returns a matching cross-origin access control header", function() { with(this) {
121
+ stub(server, "process").yields([[]])
122
+ post("/bayeux", {message: "[]"})
123
+ check_access_control_origin("http://example.com")
124
+ }})
125
+
126
+ it("forwards the message param onto the server", function() { with(this) {
127
+ expect(server, "process").given({channel: "/plain"}, false).yielding([[]])
128
+ post("/bayeux", "message=%7B%22channel%22%3A%22%2Fplain%22%7D")
129
+ }})
130
+
131
+ it("returns the server's response as JSON", function() { with(this) {
132
+ stub(server, "process").yields([[{channel: "/meta/handshake"}]])
133
+ post("/bayeux", "message=%5B%5D")
134
+ check_status(200)
135
+ check_content_type("application/json")
136
+ check_json([{channel: "/meta/handshake"}])
137
+ }})
138
+
139
+ it("returns a 400 response if malformed JSON is given", function() { with(this) {
140
+ expect(server, "process").exactly(0)
141
+ post("/bayeux", "message=%7B%5B")
142
+ check_status(400)
143
+ check_content_type("text/plain")
144
+ }})
129
145
  }})
130
146
 
131
- it("returns the server's response as JSON", function() { with(this) {
132
- stub(server, "process").yields([[{channel: "/meta/handshake"}]])
133
- post("/bayeux", "message=%5B%5D")
134
- check_status(200)
135
- check_content_type("application/json")
136
- check_json([{channel: "/meta/handshake"}])
147
+ describe("with text/plain", function() { with(this) {
148
+ before(function() { this.header("Content-Type", "text/plain") })
149
+ behavesLike("cross-origin request")
137
150
  }})
138
151
 
139
- it("returns a 400 response if malformed JSON is given", function() { with(this) {
140
- expect(server, "process").exactly(0)
141
- post("/bayeux", "message=%7B%5B")
142
- check_status(400)
143
- check_content_type("text/plain")
152
+ describe("with application/xml", function() { with(this) {
153
+ before(function() { this.header("Content-Type", "application/xml") })
154
+ behavesLike("cross-origin request")
144
155
  }})
145
156
  }})
146
157
 
@@ -0,0 +1,312 @@
1
+ # Redis configuration file example
2
+
3
+ # Note on units: when memory size is needed, it is possible to specifiy
4
+ # it in the usual form of 1k 5GB 4M and so forth:
5
+ #
6
+ # 1k => 1000 bytes
7
+ # 1kb => 1024 bytes
8
+ # 1m => 1000000 bytes
9
+ # 1mb => 1024*1024 bytes
10
+ # 1g => 1000000000 bytes
11
+ # 1gb => 1024*1024*1024 bytes
12
+ #
13
+ # units are case insensitive so 1GB 1Gb 1gB are all the same.
14
+
15
+ # By default Redis does not run as a daemon. Use 'yes' if you need it.
16
+ # Note that Redis will write a pid file in /usr/local/var/run/redis.pid when daemonized.
17
+ daemonize no
18
+
19
+ # When running daemonized, Redis writes a pid file in /usr/local/var/run/redis.pid by
20
+ # default. You can specify a custom pid file location here.
21
+ pidfile /usr/local/var/run/redis.pid
22
+
23
+ # Accept connections on the specified port, default is 6379
24
+ port 6379
25
+
26
+ # If you want you can bind a single interface, if the bind option is not
27
+ # specified all the interfaces will listen for incoming connections.
28
+ #
29
+ # bind 127.0.0.1
30
+
31
+ # Close the connection after a client is idle for N seconds (0 to disable)
32
+ timeout 300
33
+
34
+ # Set server verbosity to 'debug'
35
+ # it can be one of:
36
+ # debug (a lot of information, useful for development/testing)
37
+ # verbose (many rarely useful info, but not a mess like the debug level)
38
+ # notice (moderately verbose, what you want in production probably)
39
+ # warning (only very important / critical messages are logged)
40
+ loglevel verbose
41
+
42
+ # Specify the log file name. Also 'stdout' can be used to force
43
+ # Redis to log on the standard output. Note that if you use standard
44
+ # output for logging but daemonize, logs will be sent to /dev/null
45
+ logfile stdout
46
+
47
+ # Set the number of databases. The default database is DB 0, you can select
48
+ # a different one on a per-connection basis using SELECT <dbid> where
49
+ # dbid is a number between 0 and 'databases'-1
50
+ databases 16
51
+
52
+ ################################ SNAPSHOTTING #################################
53
+ #
54
+ # Save the DB on disk:
55
+ #
56
+ # save <seconds> <changes>
57
+ #
58
+ # Will save the DB if both the given number of seconds and the given
59
+ # number of write operations against the DB occurred.
60
+ #
61
+ # In the example below the behaviour will be to save:
62
+ # after 900 sec (15 min) if at least 1 key changed
63
+ # after 300 sec (5 min) if at least 10 keys changed
64
+ # after 60 sec if at least 10000 keys changed
65
+ #
66
+ # Note: you can disable saving at all commenting all the "save" lines.
67
+
68
+ save 900 1
69
+ save 300 10
70
+ save 60 10000
71
+
72
+ # Compress string objects using LZF when dump .rdb databases?
73
+ # For default that's set to 'yes' as it's almost always a win.
74
+ # If you want to save some CPU in the saving child set it to 'no' but
75
+ # the dataset will likely be bigger if you have compressible values or keys.
76
+ rdbcompression yes
77
+
78
+ # The filename where to dump the DB
79
+ dbfilename dump.rdb
80
+
81
+ # The working directory.
82
+ #
83
+ # The DB will be written inside this directory, with the filename specified
84
+ # above using the 'dbfilename' configuration directive.
85
+ #
86
+ # Also the Append Only File will be created inside this directory.
87
+ #
88
+ # Note that you must specify a directory here, not a file name.
89
+ dir /usr/local/var/db/redis/
90
+
91
+ ################################# REPLICATION #################################
92
+
93
+ # Master-Slave replication. Use slaveof to make a Redis instance a copy of
94
+ # another Redis server. Note that the configuration is local to the slave
95
+ # so for example it is possible to configure the slave to save the DB with a
96
+ # different interval, or to listen to another port, and so on.
97
+ #
98
+ # slaveof <masterip> <masterport>
99
+
100
+ # If the master is password protected (using the "requirepass" configuration
101
+ # directive below) it is possible to tell the slave to authenticate before
102
+ # starting the replication synchronization process, otherwise the master will
103
+ # refuse the slave request.
104
+ #
105
+ # masterauth <master-password>
106
+
107
+ ################################## SECURITY ###################################
108
+
109
+ # Require clients to issue AUTH <PASSWORD> before processing any other
110
+ # commands. This might be useful in environments in which you do not trust
111
+ # others with access to the host running redis-server.
112
+ #
113
+ # This should stay commented out for backward compatibility and because most
114
+ # people do not need auth (e.g. they run their own servers).
115
+ #
116
+ # Warning: since Redis is pretty fast an outside user can try up to
117
+ # 150k passwords per second against a good box. This means that you should
118
+ # use a very strong password otherwise it will be very easy to break.
119
+ #
120
+ requirepass foobared
121
+
122
+ ################################### LIMITS ####################################
123
+
124
+ # Set the max number of connected clients at the same time. By default there
125
+ # is no limit, and it's up to the number of file descriptors the Redis process
126
+ # is able to open. The special value '0' means no limits.
127
+ # Once the limit is reached Redis will close all the new connections sending
128
+ # an error 'max number of clients reached'.
129
+ #
130
+ # maxclients 128
131
+
132
+ # Don't use more memory than the specified amount of bytes.
133
+ # When the memory limit is reached Redis will try to remove keys with an
134
+ # EXPIRE set. It will try to start freeing keys that are going to expire
135
+ # in little time and preserve keys with a longer time to live.
136
+ # Redis will also try to remove objects from free lists if possible.
137
+ #
138
+ # If all this fails, Redis will start to reply with errors to commands
139
+ # that will use more memory, like SET, LPUSH, and so on, and will continue
140
+ # to reply to most read-only commands like GET.
141
+ #
142
+ # WARNING: maxmemory can be a good idea mainly if you want to use Redis as a
143
+ # 'state' server or cache, not as a real DB. When Redis is used as a real
144
+ # database the memory usage will grow over the weeks, it will be obvious if
145
+ # it is going to use too much memory in the long run, and you'll have the time
146
+ # to upgrade. With maxmemory after the limit is reached you'll start to get
147
+ # errors for write operations, and this may even lead to DB inconsistency.
148
+ #
149
+ # maxmemory <bytes>
150
+
151
+ ############################## APPEND ONLY MODE ###############################
152
+
153
+ # By default Redis asynchronously dumps the dataset on disk. If you can live
154
+ # with the idea that the latest records will be lost if something like a crash
155
+ # happens this is the preferred way to run Redis. If instead you care a lot
156
+ # about your data and don't want to that a single record can get lost you should
157
+ # enable the append only mode: when this mode is enabled Redis will append
158
+ # every write operation received in the file appendonly.aof. This file will
159
+ # be read on startup in order to rebuild the full dataset in memory.
160
+ #
161
+ # Note that you can have both the async dumps and the append only file if you
162
+ # like (you have to comment the "save" statements above to disable the dumps).
163
+ # Still if append only mode is enabled Redis will load the data from the
164
+ # log file at startup ignoring the dump.rdb file.
165
+ #
166
+ # IMPORTANT: Check the BGREWRITEAOF to check how to rewrite the append
167
+ # log file in background when it gets too big.
168
+
169
+ appendonly no
170
+
171
+ # The name of the append only file (default: "appendonly.aof")
172
+ # appendfilename appendonly.aof
173
+
174
+ # The fsync() call tells the Operating System to actually write data on disk
175
+ # instead to wait for more data in the output buffer. Some OS will really flush
176
+ # data on disk, some other OS will just try to do it ASAP.
177
+ #
178
+ # Redis supports three different modes:
179
+ #
180
+ # no: don't fsync, just let the OS flush the data when it wants. Faster.
181
+ # always: fsync after every write to the append only log . Slow, Safest.
182
+ # everysec: fsync only if one second passed since the last fsync. Compromise.
183
+ #
184
+ # The default is "everysec" that's usually the right compromise between
185
+ # speed and data safety. It's up to you to understand if you can relax this to
186
+ # "no" that will will let the operating system flush the output buffer when
187
+ # it wants, for better performances (but if you can live with the idea of
188
+ # some data loss consider the default persistence mode that's snapshotting),
189
+ # or on the contrary, use "always" that's very slow but a bit safer than
190
+ # everysec.
191
+ #
192
+ # If unsure, use "everysec".
193
+
194
+ # appendfsync always
195
+ appendfsync everysec
196
+ # appendfsync no
197
+
198
+ ################################ VIRTUAL MEMORY ###############################
199
+
200
+ # Virtual Memory allows Redis to work with datasets bigger than the actual
201
+ # amount of RAM needed to hold the whole dataset in memory.
202
+ # In order to do so very used keys are taken in memory while the other keys
203
+ # are swapped into a swap file, similarly to what operating systems do
204
+ # with memory pages.
205
+ #
206
+ # To enable VM just set 'vm-enabled' to yes, and set the following three
207
+ # VM parameters accordingly to your needs.
208
+
209
+ vm-enabled no
210
+ # vm-enabled yes
211
+
212
+ # This is the path of the Redis swap file. As you can guess, swap files
213
+ # can't be shared by different Redis instances, so make sure to use a swap
214
+ # file for every redis process you are running. Redis will complain if the
215
+ # swap file is already in use.
216
+ #
217
+ # The best kind of storage for the Redis swap file (that's accessed at random)
218
+ # is a Solid State Disk (SSD).
219
+ #
220
+ # *** WARNING *** if you are using a shared hosting the default of putting
221
+ # the swap file under /tmp is not secure. Create a dir with access granted
222
+ # only to Redis user and configure Redis to create the swap file there.
223
+ vm-swap-file /tmp/redis.swap
224
+
225
+ # vm-max-memory configures the VM to use at max the specified amount of
226
+ # RAM. Everything that deos not fit will be swapped on disk *if* possible, that
227
+ # is, if there is still enough contiguous space in the swap file.
228
+ #
229
+ # With vm-max-memory 0 the system will swap everything it can. Not a good
230
+ # default, just specify the max amount of RAM you can in bytes, but it's
231
+ # better to leave some margin. For instance specify an amount of RAM
232
+ # that's more or less between 60 and 80% of your free RAM.
233
+ vm-max-memory 0
234
+
235
+ # Redis swap files is split into pages. An object can be saved using multiple
236
+ # contiguous pages, but pages can't be shared between different objects.
237
+ # So if your page is too big, small objects swapped out on disk will waste
238
+ # a lot of space. If you page is too small, there is less space in the swap
239
+ # file (assuming you configured the same number of total swap file pages).
240
+ #
241
+ # If you use a lot of small objects, use a page size of 64 or 32 bytes.
242
+ # If you use a lot of big objects, use a bigger page size.
243
+ # If unsure, use the default :)
244
+ vm-page-size 32
245
+
246
+ # Number of total memory pages in the swap file.
247
+ # Given that the page table (a bitmap of free/used pages) is taken in memory,
248
+ # every 8 pages on disk will consume 1 byte of RAM.
249
+ #
250
+ # The total swap size is vm-page-size * vm-pages
251
+ #
252
+ # With the default of 32-bytes memory pages and 134217728 pages Redis will
253
+ # use a 4 GB swap file, that will use 16 MB of RAM for the page table.
254
+ #
255
+ # It's better to use the smallest acceptable value for your application,
256
+ # but the default is large in order to work in most conditions.
257
+ vm-pages 134217728
258
+
259
+ # Max number of VM I/O threads running at the same time.
260
+ # This threads are used to read/write data from/to swap file, since they
261
+ # also encode and decode objects from disk to memory or the reverse, a bigger
262
+ # number of threads can help with big objects even if they can't help with
263
+ # I/O itself as the physical device may not be able to couple with many
264
+ # reads/writes operations at the same time.
265
+ #
266
+ # The special value of 0 turn off threaded I/O and enables the blocking
267
+ # Virtual Memory implementation.
268
+ vm-max-threads 4
269
+
270
+ ############################### ADVANCED CONFIG ###############################
271
+
272
+ # Glue small output buffers together in order to send small replies in a
273
+ # single TCP packet. Uses a bit more CPU but most of the times it is a win
274
+ # in terms of number of queries per second. Use 'yes' if unsure.
275
+ glueoutputbuf yes
276
+
277
+ # Hashes are encoded in a special way (much more memory efficient) when they
278
+ # have at max a given numer of elements, and the biggest element does not
279
+ # exceed a given threshold. You can configure this limits with the following
280
+ # configuration directives.
281
+ hash-max-zipmap-entries 64
282
+ hash-max-zipmap-value 512
283
+
284
+ # Active rehashing uses 1 millisecond every 100 milliseconds of CPU time in
285
+ # order to help rehashing the main Redis hash table (the one mapping top-level
286
+ # keys to values). The hash table implementation redis uses (see dict.c)
287
+ # performs a lazy rehashing: the more operation you run into an hash table
288
+ # that is rhashing, the more rehashing "steps" are performed, so if the
289
+ # server is idle the rehashing is never complete and some more memory is used
290
+ # by the hash table.
291
+ #
292
+ # The default is to use this millisecond 10 times every second in order to
293
+ # active rehashing the main dictionaries, freeing memory when possible.
294
+ #
295
+ # If unsure:
296
+ # use "activerehashing no" if you have hard latency requirements and it is
297
+ # not a good thing in your environment that Redis can reply form time to time
298
+ # to queries with 2 milliseconds delay.
299
+ #
300
+ # use "activerehashing yes" if you don't have such hard requirements but
301
+ # want to free memory asap when possible.
302
+ activerehashing yes
303
+
304
+ ################################## INCLUDES ###################################
305
+
306
+ # Include one or more other config files here. This is useful if you
307
+ # have a standard template that goes to all redis server but also need
308
+ # to customize a few per-server settings. Include files can include
309
+ # other files, so use this wisely.
310
+ #
311
+ # include /path/to/local.conf
312
+ # include /path/to/other.conf
@@ -89,11 +89,15 @@ EngineSteps = EM::RSpec.async_steps do
89
89
  end
90
90
 
91
91
  describe "Pub/sub engines" do
92
+ def create_engine
93
+ engine_klass.new(options.merge(engine_opts))
94
+ end
95
+
92
96
  shared_examples_for "faye engine" do
93
97
  include EngineSteps
94
98
 
95
99
  let(:options) { {:timeout => 1} }
96
- let(:engine) { engine_klass.new options }
100
+ let(:engine) { create_engine }
97
101
 
98
102
  before do
99
103
  Faye.ensure_reactor_running!
@@ -269,8 +273,8 @@ describe "Pub/sub engines" do
269
273
  include EngineSteps
270
274
 
271
275
  let(:options) { {} }
272
- let(:left) { engine_klass.new options }
273
- let(:right) { engine_klass.new options }
276
+ let(:left) { create_engine }
277
+ let(:right) { create_engine }
274
278
 
275
279
  alias :engine :left
276
280
 
@@ -299,11 +303,13 @@ describe "Pub/sub engines" do
299
303
 
300
304
  describe Faye::Engine::Memory do
301
305
  let(:engine_klass) { Faye::Engine::Memory }
306
+ let(:engine_opts) { {} }
302
307
  it_should_behave_like "faye engine"
303
308
  end
304
309
 
305
310
  describe Faye::Engine::Redis do
306
311
  let(:engine_klass) { Faye::Engine::Redis }
312
+ let(:engine_opts) { {:password => "foobared", :namespace => Time.now.to_i.to_s} }
307
313
  after { clean_redis_db }
308
314
  it_should_behave_like "faye engine"
309
315
  it_should_behave_like "distributed engine"
@@ -3,7 +3,8 @@ require "thin_proxy"
3
3
 
4
4
  describe Faye::RackAdapter do
5
5
  include Rack::Test::Methods
6
- let(:app) { ThinProxy.new(Faye::RackAdapter.new options) }
6
+ let(:adapter) { Faye::RackAdapter.new(options) }
7
+ let(:app) { ThinProxy.new(adapter) }
7
8
  let(:options) { {:mount => "/bayeux", :timeout => 30} }
8
9
  let(:server) { mock "server" }
9
10
 
@@ -17,46 +18,58 @@ describe Faye::RackAdapter do
17
18
 
18
19
  before do
19
20
  Faye::Server.should_receive(:new).with(options).and_return server
21
+ adapter.stub(:get_client).and_return mock("client")
20
22
  end
21
23
 
22
24
  describe "POST requests" do
23
25
  describe "with cross-origin access control" do
24
- before do
25
- header "Content-Type", "text/plain"
26
- header "Origin", "http://example.com"
27
- end
28
-
29
- it "returns a matching cross-origin access control header" do
30
- server.stub(:process).and_yield []
31
- post "/bayeux", :message => '[]'
32
- access_control_origin.should == "http://example.com"
33
- end
34
-
35
- it "forwards the message param onto the server" do
36
- server.should_receive(:process).with({"channel" => "/plain"}, false).and_yield []
37
- post "/bayeux", "message=%7B%22channel%22%3A%22%2Fplain%22%7D"
38
- end
39
-
40
- it "returns the server's response as JSON" do
41
- server.stub(:process).and_yield ["channel" => "/meta/handshake"]
42
- post "/bayeux", "message=%5B%5D"
43
- status.should == 200
44
- content_type.should == "application/json"
45
- json.should == ["channel" => "/meta/handshake"]
46
- end
47
-
48
- it "returns a 400 response if malformed JSON is given" do
49
- server.should_not_receive(:process)
50
- post "/bayeux", "message=%7B%5B"
51
- status.should == 400
52
- content_type.should == "text/plain"
53
- end
54
-
55
- it "returns a 404 if the path is not matched" do
56
- server.should_not_receive(:process)
57
- post "/blaf", 'message=%5B%5D'
58
- status.should == 404
59
- content_type.should == "text/plain"
26
+ shared_examples_for "cross-origin request" do
27
+ before do
28
+ header "Origin", "http://example.com"
29
+ end
30
+
31
+ it "returns a matching cross-origin access control header" do
32
+ server.stub(:process).and_yield []
33
+ post "/bayeux", :message => '[]'
34
+ access_control_origin.should == "http://example.com"
35
+ end
36
+
37
+ it "forwards the message param onto the server" do
38
+ server.should_receive(:process).with({"channel" => "/plain"}, false).and_yield []
39
+ post "/bayeux", "message=%7B%22channel%22%3A%22%2Fplain%22%7D"
40
+ end
41
+
42
+ it "returns the server's response as JSON" do
43
+ server.stub(:process).and_yield ["channel" => "/meta/handshake"]
44
+ post "/bayeux", "message=%5B%5D"
45
+ status.should == 200
46
+ content_type.should == "application/json"
47
+ json.should == ["channel" => "/meta/handshake"]
48
+ end
49
+
50
+ it "returns a 400 response if malformed JSON is given" do
51
+ server.should_not_receive(:process)
52
+ post "/bayeux", "message=%7B%5B"
53
+ status.should == 400
54
+ content_type.should == "text/plain"
55
+ end
56
+
57
+ it "returns a 404 if the path is not matched" do
58
+ server.should_not_receive(:process)
59
+ post "/blaf", 'message=%5B%5D'
60
+ status.should == 404
61
+ content_type.should == "text/plain"
62
+ end
63
+ end
64
+
65
+ describe "with text/plain" do
66
+ before { header "Content-Type", "text/plain" }
67
+ it_should_behave_like "cross-origin request"
68
+ end
69
+
70
+ describe "with application/xml" do
71
+ before { header "Content-Type", "application/xml" }
72
+ it_should_behave_like "cross-origin request"
60
73
  end
61
74
  end
62
75
 
metadata CHANGED
@@ -1,13 +1,8 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: faye
3
3
  version: !ruby/object:Gem::Version
4
- hash: 5
5
4
  prerelease:
6
- segments:
7
- - 0
8
- - 6
9
- - 1
10
- version: 0.6.1
5
+ version: 0.6.2
11
6
  platform: ruby
12
7
  authors:
13
8
  - James Coglan
@@ -15,7 +10,7 @@ autorequire:
15
10
  bindir: bin
16
11
  cert_chain: []
17
12
 
18
- date: 2011-06-06 00:00:00 +01:00
13
+ date: 2011-06-19 00:00:00 +01:00
19
14
  default_executable:
20
15
  dependencies:
21
16
  - !ruby/object:Gem::Dependency
@@ -26,11 +21,6 @@ dependencies:
26
21
  requirements:
27
22
  - - ~>
28
23
  - !ruby/object:Gem::Version
29
- hash: 47
30
- segments:
31
- - 0
32
- - 12
33
- - 0
34
24
  version: 0.12.0
35
25
  type: :runtime
36
26
  version_requirements: *id001
@@ -42,10 +32,6 @@ dependencies:
42
32
  requirements:
43
33
  - - ">="
44
34
  - !ruby/object:Gem::Version
45
- hash: 15
46
- segments:
47
- - 0
48
- - 2
49
35
  version: "0.2"
50
36
  type: :runtime
51
37
  version_requirements: *id002
@@ -57,11 +43,6 @@ dependencies:
57
43
  requirements:
58
44
  - - ">="
59
45
  - !ruby/object:Gem::Version
60
- hash: 29
61
- segments:
62
- - 0
63
- - 0
64
- - 1
65
46
  version: 0.0.1
66
47
  type: :runtime
67
48
  version_requirements: *id003
@@ -73,10 +54,6 @@ dependencies:
73
54
  requirements:
74
55
  - - ">="
75
56
  - !ruby/object:Gem::Version
76
- hash: 15
77
- segments:
78
- - 1
79
- - 0
80
57
  version: "1.0"
81
58
  type: :runtime
82
59
  version_requirements: *id004
@@ -88,10 +65,6 @@ dependencies:
88
65
  requirements:
89
66
  - - ~>
90
67
  - !ruby/object:Gem::Version
91
- hash: 11
92
- segments:
93
- - 1
94
- - 2
95
68
  version: "1.2"
96
69
  type: :runtime
97
70
  version_requirements: *id005
@@ -103,10 +76,6 @@ dependencies:
103
76
  requirements:
104
77
  - - ">="
105
78
  - !ruby/object:Gem::Version
106
- hash: 15
107
- segments:
108
- - 1
109
- - 0
110
79
  version: "1.0"
111
80
  type: :runtime
112
81
  version_requirements: *id006
@@ -118,9 +87,6 @@ dependencies:
118
87
  requirements:
119
88
  - - ">="
120
89
  - !ruby/object:Gem::Version
121
- hash: 3
122
- segments:
123
- - 0
124
90
  version: "0"
125
91
  type: :development
126
92
  version_requirements: *id007
@@ -132,9 +98,6 @@ dependencies:
132
98
  requirements:
133
99
  - - ">="
134
100
  - !ruby/object:Gem::Version
135
- hash: 3
136
- segments:
137
- - 0
138
101
  version: "0"
139
102
  type: :development
140
103
  version_requirements: *id008
@@ -146,11 +109,6 @@ dependencies:
146
109
  requirements:
147
110
  - - ~>
148
111
  - !ruby/object:Gem::Version
149
- hash: 27
150
- segments:
151
- - 2
152
- - 5
153
- - 0
154
112
  version: 2.5.0
155
113
  type: :development
156
114
  version_requirements: *id009
@@ -162,9 +120,6 @@ dependencies:
162
120
  requirements:
163
121
  - - ">="
164
122
  - !ruby/object:Gem::Version
165
- hash: 3
166
- segments:
167
- - 0
168
123
  version: "0"
169
124
  type: :development
170
125
  version_requirements: *id010
@@ -176,9 +131,6 @@ dependencies:
176
131
  requirements:
177
132
  - - ">="
178
133
  - !ruby/object:Gem::Version
179
- hash: 3
180
- segments:
181
- - 0
182
134
  version: "0"
183
135
  type: :development
184
136
  version_requirements: *id011
@@ -195,6 +147,7 @@ files:
195
147
  - README.rdoc
196
148
  - lib/faye-browser-min.js
197
149
  - spec/browser.html
150
+ - spec/redis.conf
198
151
  - spec/testswarm.pl
199
152
  - spec/install.sh
200
153
  - spec/thin_proxy.rb
@@ -265,18 +218,12 @@ required_ruby_version: !ruby/object:Gem::Requirement
265
218
  requirements:
266
219
  - - ">="
267
220
  - !ruby/object:Gem::Version
268
- hash: 3
269
- segments:
270
- - 0
271
221
  version: "0"
272
222
  required_rubygems_version: !ruby/object:Gem::Requirement
273
223
  none: false
274
224
  requirements:
275
225
  - - ">="
276
226
  - !ruby/object:Gem::Version
277
- hash: 3
278
- segments:
279
- - 0
280
227
  version: "0"
281
228
  requirements: []
282
229