the new virtual host map - unfolded
Pronghorn's virtualHostMap class provides an internal API for creating, accessing and deleting virtual hosts objects.
But how's the data organized? The most common way is probably to simply store the hostnames in a hashmap. We did so prior to pronghorn release 0.8 since it's the simplest and probably most efficient way - unless it comes to wildcard subdomains.
What's so tricky about wildcard subdomains? Having a configured wildcard subdomain "*.example.com" and a request to "dharmainitiative.foo.bar.example.com", several lookups are required to find the appropriate virtual host which makes the lookup process quite expensive. The following steps are needed to find the associated virtual host:
VirtualHost: *.example.com, Request: dharmainitiative.foo.bar.example.com
- lookup dharmainitiative.foo.bar.example.com (doesn't exist)
- lookup *.foo.bar.example.com (doesn't exist)
- lookup *.bar.example.com (doesn't exist)
- lookup *.example.com (oh, we finally got it)
As you can see, four steps are required in this example.
As mentioned before, pronghorn 0.8 comes up with another approach, which will be explained in the following lines.
keyword: tree
All Hostnames are organized in a tree (as the domain name system, DNS, does). If a new virtual host is registered to the virtual host map, all its hostnames will be inserted into the tree by splitting the hostname into its labels ("example.com" becomes an array of "example" and "com") whereas the labels are placed into reverse order ("com", "example" - the TLD is represented by the first level of the tree). If the root node of the tree doesn't contain a child node with name "com", it will be created instead. The same happens with the "example" label. If the "com" node doesn't hold a child node with name "example", a new node will be created and linked to the "com" node.
Lookups work in a similar way. The root node is accessed, the existence of the "com" label is ensured, and if the child label "example" doesn't exist, the "com" label will be checked for a child label with name "*" - a wildcard one. Of course expensive string comparisons can't be abandonded, which are needed to find the desired label. But compared to flat hashmaps lookups are performed in an incremental way - step by step, hostname label by hostname label. In so doing there's no need to compare long strings at once which saves time and makes this approach more efficient. And last but not least memory is saved since each label is only stored once (at the respective position in the tree).
Deleting hostnames from the tree is the hardest part. Before deleting a label, it needs to be ensured that it isn't shared with other hostnames. But as of now, the new hostname implementation works like a charm.