Ruleset that provides a general purpose URL shortener

Principles of operation

This ruleset is intended to be used as a module by one of your rulesets, rather than directly by an end user.

The idea is simple. The ruleset has an entity variable, ent:shortcuts, which is a map keyed by ECIs for the pico in which it is installed, with the values being long URLs. You register a long URL, identified by a tag to get the short form, which will look like http://DOMAIN/sky/event/ECI/none/s/u and a browser given the long form will redirect an end user to the long URL associated with that ECI.

To register a long URL with this ruleset, simply

raise s event "u" attributes {"url": the_long_URL, "tag": an_identifier}

To find the ECI and request the short URL, use code like this:

chan = wrangler:channels([an_identifer,"s"]).head() eci = chan{"id"} short_URL = s:u(eci)


This module is useful when you have a ruleset that generates very long URLs that are ultimately intended for human consumption, perhaps in the form of a QR Code. The short form is easier to communicate, and generates a smaller QR Code.


You have the responsibility of ensuring that the tag your ruleset supplies is unique across all uses of this module.

Each ECI identifies both your pico and the specific long URL. The channel policy doesn’t allow the ECI to be used to send any extraneous events or queries to your pico.


ruleset s { meta { description <<URL shortener>> use module io.picolabs.wrangler alias wrangler provides u } global { u = function(eci){ <<#{meta:host}/sky/event/#{eci}/none/s/u>> } } rule recordShortcut { select when s u url re#(.+)# setting(url) pre { tag = event:attr("tag").lc().replace(re#[^a-z0-9_.-]#g,"-") eid = tag => tag | "none" shortcut = function(eci){ <<#{meta:host}/sky/event/#{eci}/#{eid}/s/u>> } } every { wrangler:createChannel( [eid,"s"], {"allow":[{"domain":"s","name":"u"}],"deny":[]}, {"allow":[],"deny":[{"rid":"*","name":"*"}]} ) setting(channel) send_directive("shortcut registered",{ "tag":tag, "eci":channel{"id"}, "shortcut":shortcut(channel{"id"}), "url":url }) } fired { ent:shortcuts{channel{"id"}} := url raise shortcut event "registered" attributes { "tag":tag, "eci":channel{"id"}, "shortcut":shortcut(channel{"id"}), "url":url } } } rule redirectShortcut { select when s u where event:attr("url").isnull() send_directive("_redirect",{"url":ent:shortcuts{meta:eci}}) } }

Copyright Picolabs | Licensed under Creative Commons.