ajacksified/Mediator.js — pull request #35 by tbusser (2014-09-03 08:23:13+00:00)
Title: Add automatic cleanup of channels

Channels which no longer have any subscribers and no sub-channels are
just taking up resources without any purpose. These channels also add
unnecessary time when trying to publish to or getting a subscriber from
them.

This commit adds a new parameter `autoClean` to the `remove` method on
the Mediator class. When this parameter has the value `true` it will
check if the channel from which a subscriber is removed can automatically
be removed. By default the parameter will be false, making this new
behaviour of the Mediator opt-in rather than opt-out.

In order to qualify for automatic removal the channel needs to meet the
following three criteria:

1. The channel should not have any subscribers
2. The channel should not be the parent to any other channels
3. The channel should have a parent channel

Only when these three criteria are met will the channel request its
parent to be removed. This in turn will trigger the parent to check if
it meets the criteria for automatic removal.

Example
```
- root channel
- channel 1: 2 subscribers
- channel 2: 1 subscriber
- channel 2.1: 1 subscriber
- channel 3: no subscriber
- channel 3.1: 1 subscriber
```

Removing a subscriber from channel 1 will NOT cause it to be removed as
the channel still has one more subscriber. Only when the second
subscriber is removed will channel 1 remove itself as it no longer has
any subscribers and no sub-channel.s

Removing a subscriber from channel 2 will NOT cause it to be removed.
While channel 2 will no longer have any subscribers it is still the
parent of channel 2.1 and thus doesn't meet the three criteria for auto
removal.

Removing the subscriber from channel 2.1 after having removed the
subscriber from channel 2 will cause channel 2.1 to be automatically
removed as it doesn't have other subscriber and it isn't the parent to
any other channels. Once channel 2.1 is removed it will in turn cause
channel 2 to remove itself as it is now no longer a parent to any
channels and thus meets the three criteria for auto removal.

Removing a subscriber from channel 3.1 will cause both channel 3.1 and
channel 3 to removed. Neither has any subscribers left and once channel
3.1 tells channel 3 to remove it from its channels it causes channel 3
to no longer be the parent to any channels.

Unit tests for these scenarios have been added to ChannelSpec.