jerico
jerico

Reputation: 1869

Does Meteor.methods() preserve causality?

Can I assume that calls to Meteor methods will be executed on the server exactly in the order that they have been posted on the client? In other words: do Meteor methods preserve causality?

EDIT: Whatever the answer - this should probably go into the documentation unless I overlooked it there.

Upvotes: 1

Views: 149

Answers (2)

TimDog
TimDog

Reputation: 8928

NOTE: I thought the below was correct, but I haven't been able to confirm it yet in my code. I'd like to get some more input from the meteor core group.

That said, these were my original thoughts:

If you invoke the method on the server without using this.unblock, the function will run synchronously and therefore block all other server-side calls. This is the only scenario where you could guarantee the order of the Meteor.method calls. The docs give a good overview.

Otherwise, with this.unblock the methods will run asynchronously on the server and therefore you will have no ordering guarantee.

BUT, I have yet to confirm this in my code. Regardless of the this.unblock in the server side code, the console logs the messages in first-second-third order. On the server, I would expect the order to be first-third-second.

if (Meteor.isServer) {
    Meteor.methods({
        first: function() {
            console.log("server first");
            return "right away";
        },
        second: function () {
            this.unblock();
            for(var i = 0; i < 10000000; i++) {}
            console.log("server second");
            return "second one";
        },
        third: function () {
            console.log("server third");
            return "last";
        },
    });
}

if (Meteor.isClient) {
    Meteor.startup(function() {
        Meteor.call("first", function(error, result) {
            console.log("first completed: " + result);
        });
        Meteor.call("second", function(error, result) {
            console.log("second completed: " + result);
        });
        Meteor.call("third", function (error, result) {
            console.log("third completed: " + result);
        });
    });
}

Upvotes: 2

David Glasser
David Glasser

Reputation: 1468

On a given client/server connection, the server processes messages (method calls, sub/unsub requests, etc) from the client in order. The server does not start processing message N+1 until one of two things happens:

  • It completes processing message N. For methods this means that the method body finishes running. For subscriptions this means that the publish handler finishes running.
  • Message N is a method invocation, and the method body calls this.unblock.

(One could imagine relaxing these restrictions in the future, so that multiple subscribe methods could be processed in parallel, eg.)

Upvotes: 2

Related Questions