11
Meteor's Fibers
As I confessed in the previous chapter, I learned to program on Meteor, and for a long time asynchrony did not exist for me. A method on the server looked like this:
Meteor.methods({
transfer(from, to, amount) {
const a = Accounts.findOne(from);
if (a.balance < amount) throw new Meteor.Error('no-money');
Accounts.update(from, { $inc: { balance: -amount } });
Accounts.update(to, { $inc: { balance: amount } });
return Accounts.findOne(to).balance;
}
});
Not a single callback, not a single then, not a single await. Every line goes to the database, and the code reads like a textbook. An error thrown anywhere reaches the client, and try/catch works the way it should. Meanwhile the server ran on the same Node with its single thread, and while one method waited for the database, other clients were served. At the time I did not wonder how this worked.
It was built on the Fibers library. A fiber is a part of the program with its own stack; it can be suspended at any point and later resumed from the same place. In languages that have them, fibers are sometimes called coroutines or lightweight threads. Unlike real threads, fibers do not run at the same time: at any moment only one is running, and they switch only when the running fiber itself decides to wait.
Marcel Laverdet wrote node-fibers, a Node library that added such fibers to V8, and Meteor built its entire server on it. Each client request ran in its own fiber. When code inside a method went to the database, the driver sent the request and suspended the fiber together with its whole stack, and the event loop went off to serve others. When the response arrived, the fiber resumed, and findOne returned the result as if it had simply been waiting all along. For old libraries written in Node style, Meteor had a wrapper, Meteor.wrapAsync: it turned a callback-style function into a function that suspends the fiber and returns the result in the ordinary way.
Free, one step away
The rest of the book is free
Leave your email and I will send a link to confirm it. Once you click it, every chapter opens here, on this device, for a year. When a new book comes out I will write to this address; reply “stop” to any email and I will not write again.
Have an INITE account? Sign in and the book opens without an email.
I do not charge for the book. If you would like to support it, you can donate from any chapter.
How your email is stored