For the past few weeks I’ve been playing with Meteor reactive framework which is heavily utilizing Node.js and MongoDB. It’s been a while since I did something in JavaScript and never ever before I tried something that can be called “reactive”. While few things a pretty weird and a lot of concepts are familiar, there were few moments that got me stuck for a bit and I want to post here just to remember in the future:
Net package for sockets from Node.js
Since my task required some plain socket communication with other service, I touched the default net package from Node.js and while from the first look it was pretty easy, there are couple of problems. Some of them are known (like binding sockets to fibers with bindEnvironment) and there are lots of post around on the forums and related sites, but one that got me go crazy was reading data from sockets line-by-line.
The on data event for the socket fires whenever there is some data coming, but it doesn’t mean you will receive it line-by-line. You can receive part of the line or lots of lines and the last one is not promised to be terminated by newline. The workaround that I found with help of Google was to use backlog, and whenever you receive some data, append it to the backlog and then shift data from backlog line-by-line, leaving whatever rest in backlog that is not a complete line in the log. The idea is clear and should work, but what happens if you receive some more data in the socket and on data event fires while you are still processing the previous call of such event? Not that easy I found out that now I have multiple callbacks manipulating same backlog and that ends up with a lot of mess in you data. Old-school ideas that I thought of was all kind of locks, tokens so on to prevent such behaviour, but did work out very well. Finally, the easiest way was to put socket on pause whenever some data is received, process that data and then resume the socket when processing of data is done. To make my life even easier, whenever I have a full line extracted from socket backlog, I was just emitting the line event on it and process it in different place. The code I end up with is as follows:
socket.on('data', Meteor.bindEnvironment( function (data) { socket.pause(); socketBackLog += data; var n = socketBackLog.indexOf('\n'); while (~n) { socket.emit('line', socketBackLog.substring(0, n)); socketBackLog = socketBackLog.substring(n + 1); n = socketBackLog.indexOf('\n'); } socket.resume(); })); socket.on('line', Meteor.bindEnvironment( function (data) { processData(data.toString()); }));
Note the Meteor.bindEnvironment all over around callbacks for socket – this is the way to keep things in fibers, otherwise Meteor will complain and fail.
Loose data types
I know it is pretty common practice now and many languages do not force you to cast variables or define them with the particular type and that is somewhat cool in most of the cases, but sometimes I really miss C-style with all that strictness. This time with JavaScript was exactly the case. Did I ask to convert 1/0 in some cases to boolean true/false or to string “1”/”0″ when I stated it is 0/1??? Since I need integer type, my code is full of binary OR operations, that force JavaScript to keep variable to be unsigned integers.
Example inserting some stuff in MongoDB and forcing integer:
Stuff = new Mongo.Collection("stuff"); Stuff.insert({ name: "Test", number_of_kids: (1 | 0) });
Basically I wound do binary OR my “integer” variables with 0 and get the result.
MongoDB object relationship and related
That is still a mystery for me and I will try to sort it out eventually. Assuming I have one child collection that has two different parent collections, or, in more traditional way, two OneToMany relations where “One” is the same. In my case here how it would look:
ParentsA = new Mongo.Collection("parents_a"); ParentsB = new Mongo.Collection("parents_b"); Childs = new Mongo.Collection("childs"); var parent_a = ParentsA.insert({ name: "parent 1 type 1", count: (0 | 0), childs: [] }); var parent_b = ParentsB.insert({ name: "parent 1 type 2", count: (0 | 0), childs: [] }); var child = Childs.insert({ name: "child 1" parent_a_id: parent_a, parent_b_id: parent_b }); ParentsA.update(parent_a,{$inc: {childs: (1 | 0)},$addToSet: {childs: child}}); ParentsB.update(parent_b,{$inc: {childs: (1 | 0)},$addToSet: {childs: child}});
In my case, if I do find/findOne on the records, both parents will have in their childs a list of child IDs (not child objects), which I can assume is a normal thing, but strange thing comes with child record itself: it would have parent_a_id as a plain ID for parentA and in parent_b_id it will have the whole parentB object. So to find the ID of parentA I can call child.parent_a_id, but for parentB I have to call child.parent_b_id._id and until now I don’t know what controls this behaviour.
Another problem I faced is that, according my knowledge, there is no way to count number of items in parents childs field and I have to keep track with the count field. But good thing is the there few query modifiers in Mongo that makes my life easier. As you can see, I use $inc modifier to adjust the count as well as $addToSet to make sure I don’t put the same child to the parent twice.
Setting session variables on client from server
I really love all this reactive things, the way how client acts on collection changes and session adjustments, but one thing is still not clear for me – how can I adjust clients session variable from the server after some events happen. Simple example:
if (Meteor.isClient) { Template.some_template.events({ 'click .send_data': function (event,template) { Meteor.call('processData',template.find('input[name="data"]').value); } }); } if (Meteor.isServer) { Meteor.methods({ 'processData': function (data) { var socket = new Imap({....}); socket.once('ready', Meteor.bindEnvironment(function () { // here I want to set clients session "imap_ready" to true })); socket.connect(); } }); }
What happens is whenever client clicks some .send_data button, we get the data from input and pass it to server’s method processData, which tries to establish the connection to IMAP server and if ok – I want to update clients session “imap_ready” variable. The problem here is that we don’t really know when (if at all) socket connection will emit the ready event and by sure, the processData will already return by that time, so using optional callback for Meteor.call is not an option as well.
For the time being I solved the problem by introducing a MongoDB collection which has session_id, key, value fields. Whenever client calls server methods of such kind, it passes session_id as additional argument (BTW had to use permanent session addon to avoid session losing session data and uuid addon to generate some nice session id), then whenever server has something it needs to pass back – it updates the relevant Mongo document and on the client side, I use observeChanges on the collection to gather all the data and put it in the session. Sounds weird, I don’t like this way, but it somehow works. If anyone can suggest a better way for the above problem – feel free to comment or contact me in any other way.
I think that’s enough for the time being. Maybe one day I will post a follow up with solutions (where applicable) to the problems above.