Skip to content

Instantly share code, notes, and snippets.

@jimblandy
Forked from campd/writing-actors.md
Last active December 16, 2015 16:19
Show Gist options
  • Save jimblandy/5462644 to your computer and use it in GitHub Desktop.
Save jimblandy/5462644 to your computer and use it in GitHub Desktop.

So you want to write an actor

Starting out with primitive types

So you have an idea for a Firefox developer tool. You (obviously) want it to work on Fennec and Firefox OS, so it needs to use the remote debugging protocol. You have a backend:

function SimpleBackend(target) { this.target() }
SimpleBackend.prototype = {
    printHello: function() { dump("hello") }
};

and a frontend that's nicely tied in with the developer toolbox somehow. I don't know how, but it has access to a Target at least:

function createBackend(target) {
    let backend = new SimpleBackend(target);
    backend.printHello();
}

I guess it's not the best idea for a developer tool.

We want to make the backend into an actor. First we need to import the protocol library, and maybe destructure it a bit:

let protocol = require("devtools/server/protocol");
let {method, Arg, Option, ReturnVal} = protocol;

Then we'll do a bit of magic to change backend into an actor. This uses the addon-sdk's heritage module behind the scenes, in case you want to understand the class stuff a bit better.

let SimpleBackend = protocol.ActorClass({
    typeName: "simpleBackend", // I'll explain types later, I promise.
    initialize: function(conn) {
        protocol.Actor.prototype.initialize.call(this, conn); // the worst part of heritage.
    },

    printHello: function() { dump("hello") }
});

SimpleBackend is an actor now, but we have two problems:

  1. We haven't hooked it up to the debugger server yet, so there's no way to create one, and
  2. It doesn't actually have any requests that can be made against it.

We really should fix #1 at some point, but it's messy and I don't want to explain it right now. Soon, maybe.

But fixing #2 should be easy. Replace printHello with:

printHello: method(function() {
    dump("hello");
})

and now it supports a printHello request type that has request and response packets that look like:

{ to: <actorID>, type: 'printHello' }
{ from: <actorID> }

So from the client side we need to create a front to interact with the actor. Here's a front for the SimpleBackend actor:

let SimpleFront = protocol.FrontClass(SimpleBackend, {
    initialize: function(client, form) {
        protocol.Front.prototype.initialize.call(this, client, form);
    }
});

This front has the same problem as the actor, which is that I'm not telling you how to get the initial reference to the front. Sorry. But let's pretend you do have it, and want to say hello:

let front = magicalGetSimpleFront();
front.sayHello().then(() => {
    dump("The backend said hello.");
});

"Curses," you say, "promises again." Yeah. If people are interested we could do a version using callbacks, I'm not religious.

But really the more interesting thing is that the front has a sayHello method now, and it issues a request to the actor and waits for a response and all that good stuff.

So now we'll imagine that you want to do something a little bit more interesting than a no-argument-no-return function. Let's you want something that looks like:

echo: function(str) {
    return str + "... " + str + "...";
}

This backend's getting fancy now. Once you start having arguments and returns, you need to describe how they should be marshalled to the protocol library:

echo: method(function(str) {
    return str + "... " + str + "..."; // so far no real changes
}, {
    request: { echo: Arg(0) },
    response: { echoed: ReturnVal() }
});

This will generate a request handler whose request and response packets looks like this:

{ to: <actorID>, type: "echo", echo: <str> }
{ from: <actorID>, echoed: <str> }

The client usage should be predictable:

front.echo("hello").then(str => { assert(str === "hello... hello...") })

The library tries hard to make using fronts feel like natural javascript (or as natural as you believe promises are, I guess). When building the response it will put the return value of the function where ReturnVal() is specified in the response template, and on the client side it will use the value in that position when resolving the promise.

Maybe your response is an object:

addOneTwice: method(function(a, b) {
    return { a: a + 1, b: b + 1 };
}, {
    request: { a: Arg(0), b: Arg(1) }
    response: { ret: ReturnVal() }
});

This will generate a response packet that looks like:

{ from: <actorID>, ret: { a: <number>, b: <number> } }

That's probably unnecessary nesting (if you're sure you won't be returning an object with 'from' as a key!), so you can just replace response with:

response: ReturnVal()

and now your packet will look like:

{ from: <actorID>, a: <number>, b: <number> }

Types and Marshalling

Things have been pretty simple up to this point - all the arguments we've passed in have been javascript primitives, so we haven't needed to specify their type. But for some types (most importantly Actor types, which I'll get to eventually), we can't just copy them into a JSON packet and expect it to work, we need to marshal things ourselves.

Again, the protocol lib tries hard to provide a natural API to actors and clients, and sometime that natural API might involve object APIs. I'm going to use a wickedly contrived example, bear with me. Let's say I have a small object that contains a number and has a few methods associated with it:

let NumberWrapper = function(i) {
    this.i = i;
};

NumberWrapper.prototype = {
    increment: function() { this.i++ },
    decrement: function() { this.i-- }
};

and I want to return it from a backend function:

wrapNumber: method(function(i) {
    return new NumberWrapper(i)
}, {
    request: { number: Arg(0) },
    response: { wrappedNumber: ReturnVal() }
});

I want that response to look like { from: <actorID>, wrappedNumber: <number> }, but the client side needs to know to return a NumberWrapper, not a primitive number. So let's tell the protocol lib about wrapped numbers:

protocol.types.addType("numberWrapper", {
    write: (v) => v.i,
    read: (v) => new NumberWrapper(v)
});

and then change the response line to let the library know to use this wrapper:

response: { wrappedNumber: ReturnVal("numberWrapper") }

And now our client can use the API as expected:

front.wrapNumber(5).then(wrapper => {
    wrapper.increment() assert(wrapper.i === 6) }

You can do the same thing with arguments:

passWrapper: method(function(w) {
    w.increment();
}, {
    request: { Arg(0, "numberWrapper") },
});

front.passWrapper(new NumberWrapper(5));

As an aside, if you want to be a bit more verbose in the interest of self-documenting code, there are boolean, number, and string types defined as aliases to the primitive type, so you could use Arg(0, "boolean"), which is no different really than Arg(0) except that it's more clear what you want.

Moving right along, let's say you want to pass/return an array of NumberWrappers. You can just prepend array: to the type name:

incrementWrapperArray: method(function(wrappers) {
    return wrappers.map(wrapper => {
        let newWrap = new NumberWrapper(wrapper.i);
        newWrap.increment();
        return newWrap;
    })
}, {
    request: { wrappers: Arg(0, "array:numberWrapper") },
    response: { wrappers: ReturnVal("array:numberWrapper") }
})

Or maybe you want to return a dictionary with one item being a wrapper. To do this you need to tell the type system which members of the dictionary need custom marshallers:

protocol.types.addDictType("contrivedObject", {
    wrapper: "numberWrapper",
    wrapperArray: "array:numberwrapper"
});

reallyContrivedExample: method(function() {
    return {
        /* a and b are primitives and so don't need to be called out specifically in addDictType */
        a: "hello", b: "world",
        wrapper: new NumberWrapper(1), wrapperArray: [new NumberWrapper(2), new NumberWrapper(3)]
    }
}, {
    response: ReturnVal("contrivedObject")
});

front.reallyContrivedExample().then(obj => {
    assert(obj.a == "hello");
    assert(obj.b == "world");
    assert(wrapper.i == 1);
    assert(wrapperArray[0].i == 2);
    assert(wrapperArray[1].i == 3);
});

Actors

Probably the most common objects that need custom martialing are actors themselves. These are more interesting than the NumberWrapper object, but by default they're somewhat easy to work with. Let's add a ChildActor implementation that will be returned by the SimpleActor (which is rapidly becoming the OverwhelminglyComplexActor):

let ChildActor = protocol.ActorClass({
    actorType: "childActor",
    initialize: function(conn, id) {
        protocol.Actor.prototype.initialize.call(this, conn);
    },
    getID: method(function() {
        return this.id;
    }, {
        response: { id: ReturnVal() },
    }
});

let ChildFront = protocol.FrontClass(ChildActor, {
    initialize: function(client, form) {
        protocol.Front.prototype.initialize.call(this, client, form);
    },
});

The library will register a marshaller for the actor type itself, using typeName as its tag (I told you I'd explain that eventually).

So we can now add the following code to SimpleActor:

getChild: method(function(id) {
    return new ChildActor(this.conn, id);
}, {
    request: { id: Arg(0) },
    response: { child: ReturnVal("childActor") }
});

front.getChild("child1").then(childFront => {
    childFront.getID().then(id => { assert(id == "child1"); });
});

The conversation will look like this:

{ to: <actorID>, type: "getChild", id: "child1" }
{ from: <actorID>, child: { actor: <childActorID> }}
{ to: <childActorID>, type: "getID" }
{ from: <childActorID>, id: "child1" }

But the ID is pretty core to this made-up example. You're never going to want a reference to a ChildActor without checking its ID. Making an extra request just to get the id is wasteful. You really want the first response to look like { from: <actorID>, child: { actor: <childActorID>, id: "child1" } }

You can customize the marshalling of an actor by providing a form method in the ChildActor class:

form: function() {
    return {
        actor: this.actorID,
        id: this.id
    }
},

And you can demarshal in the ChildFront class by implementing a matching form method:

form: function(form) {
    this.actorID = form.actor;
    this.id = form.id;
}

Now you can use the id immediately:

front.getChild("child1").then(child => { assert(child.id === "child1) });

You may come across a situation where you want to customize the output of a form method depending on the operation being performed. For example, imagine that ChildActor is a bit more complex, with a, b, c, and d members:

ChildActor:
    form: function() {
        return {
            actor: this.actorID,
            id: this.id,
            a: this.a,
            b: this.b,
            c: this.c,
            d: this.d
        }
    }
ChildFront:
    form: function(form) {
        this.actorID = form.actorID;
        this.id = form.id;
        this.a = form.a;
        this.b = form.b;
        this.c = form.c;
        this.d = form.d;
    }

And imagine you want to change 'c' and return the object:

// Oops!  If a type is going to return references to itself or any other
// type that isn't fully registered yet, you need to predeclare the type.
types.addActorType("childActor");

...

changeC: method(function(newC) {
    c = newC;
    return this;
}, {
    request: { newC: Arg(0) },
    response: { self: ReturnVal("childActor") }
});

...

childFront.changeC('hello').then(ret => { assert(ret === childFront); assert(childFront.c === "hello") });

Now our response will look like:

{ from: <childActorID>, self: { actor: <childActorID>, id: <id>, a: <a>, b: <b>, c: "hello", d: <d> }

But that's wasteful. Only c changed. So we can provide a detail to the type using #:

response: { self: ReturnVal("childActor#changec") }

and update our form methods to make use of that data:

ChildActor:
form: function(detail) {
    if (detail === "changec") {
        return { actor: this.actorID, c: this.c }
    }
    ... // the rest of the form method stays the same.
}

ChildFront:
form: function(form, detail) {
    if (detail === "changec") {
        this.actorID = form.actor;
        this.c = form.c;
        return;
    }
    ... // the rest of the form method stays the same.
}

Now the packet looks like a much more reasonable { from: <childActorID>, self: { actor: <childActorID>, c: "hello" } }

Lifetimes

No, I don't want to talk about lifetimes quite yet.

Events

Your actor has great news!

Actors are subclasses of jetpack EventTarget, so you can just emit:

let event = require("sdk/core/event");

giveGoodNews: method(function(news) {
    event.emit(this, "good-news", news);
}, {
    request: { news: Arg(0) }
});

... but nobody will really care, because that's not going over the protocol. But you can describe the packet in an events member, the same way you would specify a request:

events: {
    "good-news": {
        type: "goodNews", // event target naming and packet naming are at odds, and we want both to be natural!
        news: Arg(0)
    }
}

And now you can listen to events on a front:

front.on("good-news", news => {
    dump("Got good news: " + news + "\n");
});
front.giveGoodNews().then(() => { dump("request returned.") });

You might want to update your front's state when an event is fired, before emitting it against the front. You can use preEvent in the front definition for that:

countGoodNews: protocol.preEvent("good-news", function(news) {
    this.amountOfGoodNews++;
});

On a somewhat related note, not every method needs to be request/response. Just like an actor can emit a one-way event, a method can be marked as a one-way request. Maybe we don't care about giveGoodNews returning anything:

giveGoodNews: method(function(news) {
    emit(this, "good-news", news);
}, {
    request: { news: Arg(0) },
    oneway: true
});

Lifetimes

No, let's talk about custom front methods instead.

Custom Front Methods

You might have some bookkeeping to do before issuing a request. Let's say you're calling that echo from way back, but you want to count the number of times you issue that request. Just use the custom tag in your front implementation:

echo: custom(function(str) {
    this.numEchos++;
    return this._echo(str);
}, {
    impl: "_echo"
})

This puts the generated implementation in _echo instead of echo, letting you implement echo as needed. If you leave out the impl, it just won't generate the implementation at all. You're on your own.

Lifetimes

OK, I can't think of any more ways to procrastinate. The remote debugging protocol has the concept of a parent for each actor. This is to make distributed memory management a bit easier. Basically, any descendents of an actor will be destroyed if the actor is destroyed.

Other than that, the basic protocol makes no guarantees about lifetime. Each interface defined in the protocol will need to discuss and document its approach to lifetime management (although there are a few common patterns).

The protocol library will maintain the child/parent relationships for you, but it needs some help deciding what the child/parent relationships are.

The default parent of an object is the first object that returns it after it is created. So to revisit our earlier SimpleActor getChild implementation:

getChild: method(function(id) {
    return new ChildActor(this.conn, id);
}, {
    request: { id: Arg(0) },
    response: { child: ReturnVal("childActor") }
});

The ChildActor's parent is the SimpleActor, because it's the one that created it.

You can customize this behavior in two ways. The first is by defining a defaultParent property in your actor. Imagine a new ChildActor method:

getSibling: method(function(id) {
    return new ChildActor(this.conn, id);
}, {
    request: { id: Arg(0) },
    response: { child: ReturnVal("childActor") }
});

This creates a new child actor owned by the current child actor. But in this example we want all actors created by the child to be owned by the SimpleActor. So we can define a defaultParent property that makes use of the parent proeprty provided by the Actor class:

get defaultParent() { return this.parent }

The front needs to provide a matching defaultParent property that returns an owning front, to make sure the client and server lifetimes stay synced.

For more complex situations, you can define your own lifetime properties. Take this new pair of SimpleActor methods:

// When the "temp" lifetime is specified, look for the _temporaryParent attribute as the owner.
types.addLifetime("temp", "_temporaryParent");

getTemporaryChild: method(function(id) {
    if (!this._temporaryParent) {
        // Create an actor to serve as the parent for all temporary children and explicitly
        // add it as a child of this actor.
        this._temporaryParent = this.manage(new Actor(this.conn));
    }
    return new ChildActor(this.conn, id);
}, {
    request: { id: Arg(0) },
    response: {
        child: ReturnVal("temp:childActor") // use the lifetime name here to specify the expected lifetime.
    }
});

clearTemporaryChildren: method(function(id) {
    if (this._temporaryParent) {
        this._temporaryParent.destroy();
        delete this._temporaryParent;
    }
});

This will require some matching work on the front:

getTemporaryChild: protocol.custom(function(id) {
    if (!this._temporaryParent) {
        this._temporaryParent = this.manage(new Front(this.client));
    }
    return this._getTemporaryChild(id);
}, {
    impl: "_getTemporaryChild"
}),

clearTemporaryChildren: protocol.custom(function(id) {
    if (this._temporaryParent) {
        this._temporaryParent.destroy();
        delete this._temporaryParent;
    }
    return this._clearTemporaryChildren();
}, {
    impl: "_clearTemporaryChildren"
})

Telemetry

You can specify a telemetry probe id in your method spec:

echo: method(function(str) {
    return str;
}, {
    request: { str: Arg(0) },
    response: { str: ReturnVal() },
    telemetry: "ECHO"
});

... and the time to execute that request will be included as a telemetry probe.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment