Friday, May 24, 2013

Angular service or factory?

tl;dr is at the end

In various AngularJS tutorials and documentation, the authors choose to use service or factory but don't explain why you would use one or the other. Few mention that value and constant are also options.

Let's see why you would use one over the other. We should also understand how providers work:

provider

Here's the source for the provider method:

function provider(name, provider_) {
if (isFunction(provider_) || isArray(provider_)) {
provider_ = providerInjector.instantiate(provider_);
}
if (!provider_.$get) {
throw Error('Provider ' + name + ' must define $get factory method.');
}
return providerCache[name + providerSuffix] = provider_;
}

name is a string. provider_ can be one of three things:

  1. function

    If a function is passed in, the function is called with dependency injection and should return an object with a $get method.

  2. array

    An array will be treated like a function using Inline Annotation. It must also return an object with a $get method.

  3. object

    If an object is passed in, it is simply expected to have a $get method.

Whatever the second arg to provider is, you eventually end up with an object that has a $get method. Here's an example showing what happens:

// You can run this

// Create a module
var hippo = angular.module('hippo', []);

// Register an object provider
hippo.provider('awesome', {
$get: function() {
return 'awesome data';
}
});

// Get the injector (this happens behind the scenes in angular apps)
var injector = angular.injector(['hippo', 'ng']);

// Call a function with dependency injection
injector.invoke(function(awesome) {
console.log('awesome == ' + awesome);
});

Once you understand providers you will see that factory, service, value and constant are just convenience methods for making providers.

factory

Here's the source:

function factory(name, factoryFn) {
return provider(name, { $get: factoryFn });
}

So it lets you shorten the awesome provider creation code to this:

hippo.factory('awesome', function() {
return 'awesome data';
})

service

Here's the source:

function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
}

So it lets you make a factory that will instantiate a "class". For example:

var gandalf = angular.module('gandalf', []);

function Gandalf() {
this.color = 'grey';
}
Gandalf.prototype.comeBack = function() {
this.color = 'white';
}

gandalf.service('gandalfService', Gandalf);

var injector = angular.injector(['gandalf', 'ng']);

injector.invoke(function(gandalfService) {
console.log(gandalfService.color);
gandalfService.comeBack()
console.log(gandalfService.color);
});

The above code will instantiate Gandalf, but remember that everything that uses the service will get the same instance! (which is a good thing).

value

Here's the source:

function value(name, value) {
return factory(name, valueFn(value));
}

Using value would let you shorten the awesome provider to:

hippo.value('awesome', 'awesome data');

constant

Here's the source

function constant(name, value) {
providerCache[name] = value;
instanceCache[name] = value;
}

constant differs from value in that it's accessible during config. Here's how you use it:

var joe = angular.module('joe', []);

joe.constant('bobTheConstant', 'a value');
joe.value('samTheValue', 'a different value');

joe.config(function(bobTheConstant) {
console.log(bobTheConstant);
});

joe.config(function(samTheValue) {
console.log(samTheValue);
});

// This will fail with "Error: Unknown provider: samTheValue from joe"
var injector = angular.injector(['joe', 'ng']);

Read Module Loading & Dependencies in the Modules doc for more information on usage.

In summary

If you want your function to be called like a normal function, use factory. If you want your function to be instantiated with the new operator, use service. If you don't know the difference, use factory.

This is the (great) documentation for each function in the AngularJS source:

  1. factory

    A short hand for configuring services if only `$get` method is required.

  2. service

    A short hand for registering service of given class.

  3. value

    A short hand for configuring services if the `$get` method is a constant.

  4. constant

    A constant value, but unlike {@link AUTO.$provide#value value} it can be injected into configuration function (other modules) and it is not interceptable by {@link AUTO.$provide#decorator decorator}.

Wednesday, May 22, 2013

Angular and components

I've been playing around with AngularJS lately.  It's okay.  It's very weird.  They've named some things poorly (and magically), the documentation is not great and there are some unexpected quirks.  I feel like AngularJS is the first step toward a new class of JavaScript libraries, but it's not the end.

Something is going to come along and choose good names (without magic '@', '=', '&') with great documentation.  Just today, I happened on this talk:



Which does a lot of AngularJS things.

I haven't explained thoroughly... sorry.  Maybe when I have more time, I'll post more.

Friday, May 10, 2013

@#$%!


To all you producers of words: please stop swearing.  For the sake of your audience, elevate your language above crude speech.  You lose respect when you swear.


You're not dying!

I once watched a video about API design.  Rather, I once watched part of a video about API design.  I had to stop after the 5th or 6th expletive.

API design.

API design?!  A discussion about API design is probably the last thing in the world that deserves to be littered with swearing!

You're not dying.  Your family isn't dying.  Your arm isn't being severed.  And even these terrible situations don't merit debasing yourself by swearing -- much less API design.


I really want(ed) to share your stuff...

Too frequently, I'm reading an interesting article when @#$&!  Out of nowhere (and completely out of context) I'm jarred by a four-letter word.  Why did they ruin it?  I wanted to share this and now I don't.

I don't want to share with my coworkers, family members or friends something profane -- for sharing implies endorsement, and I don't want to be associated with such things.

If you want it to be shareable, leave out the swear words.

Make me laugh, not cringe

Instead of attacking me by swearing, invite me to laugh with you.  Replace poor words with ridiculous or benign ones.  Or channel an unloveable critter/substance/thing to express your shock/displeasure/pain: Rats! Mucus! Taxes!

(Let me be clear: that was "Taxes" not "Texas.")

Yes, swearing sometimes makes some people laugh.  Bathroom humor makes some people laugh, too.  There are much better ways of making people laugh: choose a better way.

And, yes, swearing will garner attention.  A baseball bat to the head will also garner a certain amount of attention.  You don't want that kind of attention.  And in the end, it's better to lead people through charisma and intelligence than through head shots.

Use honey, not vinegar.

You're smarter than that

We don't live in a high school locker room.  Swearing is a cheap alternative to thoughtfulness.  Demonstrate your intelligence by expressing yourself accurately and powerfully through well-chosen words.  People think you're dumb when you swear.  Go ahead, A/B test it.

When your mouth is foul, your brain is discredited by association.

It's who I am

Some will say, "It's who I am.  Deal with it."  Well, they'd probably say, "$#%!, it's who I am *$!@.  @$#& deal with it.  *@&# $%@!"

Swearing isn't an identity.  You control your mouth.  You have a brain.  Use it wisely.

Thank you

To those who speak well, thank you.  I frequent an IRC channel that has an enforced family-friendly policy.  The admins gently remind people to keep it clean, which they generally do.  And it's great!  I feel comfortable there.  I respect the admins and others there.



Keep it clean and make the world better, muskrat!

Tuesday, February 5, 2013

What I wish Puppet and Salt would do differently


I like the idea of configuration management tools like Puppet and Salt; they have promise.  They attempt to solve a huge, complex problem.  I haven't come up with a working solution that is any better.  But if I ever had time to work on a solution it would improve on the current solutions in the following ways:

I wish they would use a standard for state definition


If each tool worked from a standard state description syntax, then people could try different tools without so much more effort.  Perhaps this could be achieved by developing a standard for describing machine state, and then developing tools that convert from the standard state definition to the tool-specific state definition.

A standard would also allow for more general tools to create state definitions.

And a standard would allow interoperability with things that are not configuration management tools: state visualization tools, for instance.


I wish they would stop claiming that you describe state only


Both tools inspire awe when they claim that you only have to describe "the desired state" of resources, rather than a script of things to do.  But they lie!

Puppet manifest files and Salt sls files both include syntax for restarting services, running scripts based on changes or doing other one-time events.  In other words, you are describing both state AND events.

I think the tools could be simplified if they would stop pretending that you can manage a system by describing state alone.


I wish they would focus on getting out of the way instead of cute, colored output

Colored output can be useful.  But when you're coloring output instead of providing useful data, the color is infuriating.

I spent an hour with Salt trying to create a user on a machine.  Every time it failed to create the user, this is the error I would see:

'Failed to create new user lighttpd'

It didn't show the command it was trying to execute.  It didn't show the stdout/stderr from the shell.  The logs didn't help either.  The output was very cute, colorful and useless.  When something runs, I should be able to see the arguments used to spawn the process, the environment variables for the process and the stdin, stdout, stderr and exit code of the process.  Why replace that great debugging information with cute, custom messages and colors?

Thursday, July 5, 2012

Bite-sized Twisted:Telnet

Finally, in this post, we'll monitor keypresses instead of lines of text. This means that you won't have to press enter after each command.

Strictly speaking, the changes we'll make to the code are for Telnet, and not really Twisted-specific -- though Twisted's support for Telnet makes it easier.

Telnet's modes

On my computer (running Ubuntu), running telnet will default to line by line mode. I can see this by starting the obstinate server:

from twisted.internet.protocol import Protocol, Factory
from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.internet import reactor

class ObstinateProtocol(Protocol):

def dataReceived(self, data):
self.transport.write('no\r\n')

factory = Factory()
factory.protocol = ObstinateProtocol
endpoint = TCP4ServerEndpoint(reactor, 8900)
endpoint.listen(factory)
reactor.run()
obstinate1.py

Then if I start telnet and send some stuff, I see that it reacts to the lines I send:

$ telnet 127.0.0.1 8900
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
Wanna play?
no
Are you obstinate?
no
Are you a duck?
no

We can switch the telnet client to character mode by typing the escape character Control ], then typing mode char. From then on, the server will receive each byte as we type it:

^]mode char

telnet> mode char
no
no
no
no
no
no

Each of those no lines was printed after pressing single keys. Great! We don't have to press enter anymore to play boom!

You can force the client to character mode

by telling the Telnet client that you will echo, will supress go-ahead and won't use linemode. We'll use Twisted's Telnet protocol from the conch package (changed lines are highlighted):

from twisted.internet.protocol import Protocol, Factory
from twisted.conch.telnet import Telnet, SGA, LINEMODE, ECHO
from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.internet import reactor

class ObstinateProtocol(Telnet):

def connectionMade(self):
self.will(ECHO)
self.will(SGA)
self.wont(LINEMODE)

def enableLocal(self, option):
return option in (ECHO, SGA)

def applicationDataReceived(self, data):
self.transport.write('no\r\n')


factory = Factory()
factory.protocol = ObstinateProtocol
endpoint = TCP4ServerEndpoint(reactor, 8900)
endpoint.listen(factory)
reactor.run()
lessobstinate.py

Telnet into this and you should see the same behavior as when we set the client to character mode manually.

Finally, a playable game

I've pushed changes to the tx-telnet-2 branch on GitHub. You can see everything that's changed since the last post here.

To play the game, get the tx-telnet-2 branch and run run.py as before. Then telnet to port 8900 multiple times from multiple computers. If you die, you'll have to telnet in again :)

Thursday, June 21, 2012

Bite-sized Twisted:Networking Triforce

This post begins a series of posts about networking -- an area where Twisted shines.

Network Input/Output == Bytes

In the second Bite-sized Twisted post we accepted input (bytes) from stdin asynchronously. In this post, we'll accept input (bytes) over the network. I'm intentionally emphasizing bytes (bytes). It's all just bytes.

It might be worth reviewing that second post, so the concepts are fresh.

Parts of the Triforce

In Twisted, dealing with networking (moving bytes) usually involves three things:

  1. Protocol - determines fate of bytes
  2. Transport - carries bytes between protocol and remote
  3. Factory - creates protocols

Protocol

A Protocol's job is to do application-specific things with bytes. Code for deciding what bytes should be sent back across the wire is also in the Protocol. When it decides to send bytes across the wire, it will invoke the Transport's write method.

Here's an ObstinateProtocol which sends the bytes 'no\r\n' in response to all data received:

from twisted.internet.protocol import Protocol

class ObstinateProtocol(Protocol):

def dataReceived(self, data):
self.transport.write('no\r\n')
protocol1.py

Transport

As seen above, the Transport provides an interface for interacting with the remote side. It has a write method which sends bytes to the remote side. There is generally one Transport per Protocol. You can access the transport through a Protocol's transport attribute.

Factory

A Factory's job is to make a Protocol for a connection. In general, there is one Factory for many Protocol instances.

Standard Factories determine what Protocol to make based on their protocol attribute. This snippet shows a Factory that will make ObstinateProtocol protocols:

from twisted.internet.protocol import Factory
factory = Factory()
factory.protocol = ObstinateProtocol
factory1.py

Notice that factory.protocol is set to the class ObstinateProtocol and not an instance ObstinateProtocol().

Magic glue

One other component is needed for the Networking Triforce to work: magic glue. Here's a complete example that serves the ObstinateProtocol using TCP on port 8900 (magic glue is highlighted):

from twisted.internet.protocol import Factory, Protocol
from twisted.internet import reactor
from twisted.internet.endpoints import TCP4ServerEndpoint

class ObstinateProtocol(Protocol):

def dataReceived(self, data):
self.transport.write('no\n')

factory = Factory()
factory.protocol = ObstinateProtocol
endpoint = TCP4ServerEndpoint(reactor, 8900)
endpoint.listen(factory)
reactor.run()
glue1.py

Start glue1.py in one shell, then open another shell and start telnet with this command:

telnet 127.0.0.1 8900

You've just connected to the obstinate server. Type something then press enter; you should see 'no' written back. For example:

$ telnet 127.0.0.1 8900
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
Are you there?
no
Are you lying?
no
Are you sure?
no

If you have another computer nearby, start glue1.py here, then start telnet on the other computer, changing 127.0.0.1 to this computer's IP (you can even do this while the other telnet session is still going).

A thousand words to explain the magic glue

I don't like magical code. So, here's the pertinent code for hooking up the Triforce (from twisted/internet/tcp.py). First, the factory is asked to build a protocol:

protocol = self.factory.buildProtocol(self._buildAddr(addr))
portion of twisted/internet/tcp.py

Factory.buildProtocol looks like this:

class Factory:

def buildProtocol(self, addr):
p = self.protocol()
p.factory = self
return p
portion of twisted/internet/protocol.py

Then a transport is created:

transport = self.transport(skt, protocol, addr, self, s, self.reactor)
portion of twisted/internet/tcp.py

The transport is connected to the protocol:

protocol.makeConnection(transport)
portion of twisted/internet/tcp.py

which looks like this:

class BaseProtocol:

def makeConnection(self, transport):
self.connected = 1
self.transport = transport
portion of twisted/internet/protocol.py

Here's a thousand words describing it:

Toward a better boom

Here's a Protocol and Factory that will let you telnet in to play.

from twisted.internet.protocol import Protocol, Factory
import string


from boom.game import Pawn, YoureDead, IllegalMove


class SimpleProtocol(Protocol):

num = 0

move_mapping = {
'w': 'u',
'a': 'l',
'd': 'r',
's': 'd',
}

def connectionMade(self):
self.factory.protocols.append(self)
name = string.uppercase[self.num % len(string.uppercase)]
SimpleProtocol.num += 1
self.pawn = Pawn(name)
self.factory.board.insertPawn((0,0), self.pawn)


def connectionLost(self, reason):
self.factory.protocols.remove(self)
self.factory.board.pawns.remove(self.pawn)


def dataReceived(self, data):
for k in data:
if k in self.move_mapping:
try:
self.pawn.move(self.move_mapping[k])
except YoureDead, e:
pass
except IllegalMove, e:
pass
elif k == 'e':
try:
self.pawn.dropBomb()
except YoureDead, e:
pass
except IllegalMove, e:
pass



class SimpleFactory(Factory):
"""
A factory for making L{SimpleProtocol}s

@ivar board: the game board on which I'll be playing
@ivar protocols: A list of L{SimpleProtocol} instances currently
in use.
"""

protocol = SimpleProtocol


def __init__(self, board):
self.board = board
self.protocols = []
boom/protocol.py

The code is available from GitHub in the tx-telnet-1 branch. Do this:

git clone -b tx-telnet-1 git://github.com/iffy/boom boom.git
cd boom.git
PYTHONPATH=. python run.py

Or if you don't have Git:

wget https://github.com/iffy/boom/tarball/tx-telnet-1
tar xf tx-telnet-1
cd iffy-boom-f5c6433/
PYTHONPATH=. python run.py

Then connect with:

telnet 127.0.0.1 8900

Next time, we'll remove the need to press enter after each move. In the meantime, have a look at Twisted's guide to writing servers for more information.

Monday, June 18, 2012

Bite-sized Twisted: Asynchronous Testing and the Clock

In this, the seventh Bite-sized Twisted post, I'll go over a little asynchronous testing and the Clock.

Impatient runners

Let's test that a lit bomb explodes with a message when it should. Or in other words, that a function returns a Deferred which fires after a time. For convenience, I'm going to put the code to be tested in the same file as the test.

We'll need to import some things:

from unittest import TestCase
from twisted.internet import reactor
from twisted.internet.defer import Deferred
test_bomb1.py:1-3

Here's the test:

class BombTest(TestCase):

def test_explodes(self):
def check(result):
self.assertEqual(result, 'exploded')
d = lightBomb(2, 'exploded')
d.addCallback(check)
test_bomb1.py:5-11

And here's the function:

def lightBomb(fuse, message):
defer = Deferred()
reactor.callLater(fuse, defer.callback, message)
return defer
test_bomb1.py:12-16

When we run it, we see that it passes the test:

test_bomb1
BombTest
test_explodes ... [OK]

-------------------------------------------------------------------------------
Ran 1 tests in 0.001s

PASSED (successes=1)
trial test_bomb1.py

Yay!

No, not yay. Change the test to this:

    def test_explodes(self):
def check(result):
print "I was executed with %r" % result
d = lightBomb(2, 'exploded')
d.addCallback(check)
test_bomb2.py:7-11

And see that check is never called:

test_bomb2
BombTest
test_explodes ... [OK]

-------------------------------------------------------------------------------
Ran 1 tests in 0.001s

PASSED (successes=1)
trial test_bomb2.py

What gives?

Wait up!

Does it seem a little suspicious that the bomb is supposed to go off in 2 seconds and the test runs in less than 1 second? The problem is that the test runner is not waiting for the Deferred to be called back. To wait for the Deferred, we'll have to use twisted.trial.unittest.TestCase and return the Deferred from the test method:

from twisted.trial.unittest import TestCase
from twisted.internet import reactor
from twisted.internet.defer import Deferred
test_bomb3.py:1-3
    def test_explodes(self):
def check(result):
self.assertEqual(result, 'exploded')
d = lightBomb(2, 'exploded')
d.addCallback(check)
return d
test_bomb3.py:7-12
test_bomb3
BombTest
test_explodes ... [OK]

-------------------------------------------------------------------------------
Ran 1 tests in 2.012s

PASSED (successes=1)
trial test_bomb3.py

See how the test took more than 2 seconds to run this time?

Timeout

What if lightBomb looked like this instead?

def lightBomb(fuse, message):
defer = Deferred()
return defer
test_hang.py:14-16

Run the test and it will hang. Add a timeout to fail any test that takes too long:

class BombTest(TestCase):

timeout = 3
test_timeout.py:5-7
test_timeout
BombTest
test_explodes ... [ERROR]

===============================================================================
[ERROR]
Traceback (most recent call last):
Failure: twisted.internet.defer.TimeoutError: <test_timeout.BombTest testMethod=test_explodes> (test_explodes) still running at 3.0 secs

test_timeout.BombTest.test_explodes
-------------------------------------------------------------------------------
Ran 1 tests in 3.015s

FAILED (errors=1)
trial test_timeout.py

Hello, Clock

If you have a lot of tests dealing with scheduled events and timing, running all of them will take a long time. To avoid that, we can simulate the passage of time with the Clock.

Here's the same test as test_bomb3.py using the Clock (changed lines are highlighted):

from twisted.trial.unittest import TestCase
from twisted.internet.task import Clock
from twisted.internet import reactor
from twisted.internet.defer import Deferred

class BombTest(TestCase):

def test_explodes(self):
def check(result):
self.assertEqual(result, 'exploded')
clock = Clock()
d = lightBomb(2, 'exploded', reactor=clock)
d.addCallback(check)
clock.advance(2)
return d

def lightBomb(fuse, message, reactor=reactor):
defer = Deferred()
reactor.callLater(fuse, defer.callback, message)
return defer
test_clock.py
test_clock
BombTest
test_explodes ... [OK]

-------------------------------------------------------------------------------
Ran 1 tests in 0.005s

PASSED (successes=1)
trial test_clock.py

Yes! Much faster! Here are the Clock docs if you are interested. Note in test_clock.py how we had to make lightBomb accept an optional reactor.

Boom tests

All of the code for the current version of boom was test-driven. Perhaps reading some of the tests will be enlightening -- though I make no claim at being a testing expert. The test code is available on GitHub.