Serverless Websites

Feb 18, 2017 10:02

I've been interested in serverless web systems ever since I was asked by a client to setup a store on the popular p2p marketplace called OpenBazaar. The idea fascinated me - instead of connecting to normal servers, you connect to peers - like Torrents - and download the websites from them. The only issue for me with this system was that you had to download software to do it. This got me thinking - can you do the same sort of things with normal websites, without downloading new software?

It appears so! Using the amazing WebTorrent - I've managed to cobble together a basic system that allows users to input a hash of a torrent (only from at the moment) - download a HTML page and display it! Let me show you the basics (some lines removed for brevity - you can check out all the code at the GitHub link at the bottom):

Firstly, we'll create a new WebTorrent object, and add the torrent to it. We'll also register the callback to onTorrent which is what we'll use to manage the torrent process. Don't worry about the magnet link, and associated text with it - those are trackers that uses for finding p2p clients.

function startGather() {
    var hash = document.getElementById('hashField').value;
    var client = new WebTorrent();
    client.add("magnet:?" + hash, onTorrent);
    console.log("Attempting to gather website...");
    return false;

Now we'll monitor the torrent and report to the console if we are downloading the torrent, and if so, whats our progress and how many peers we are connected to:

var interval = setInterval(function () {
    peers = torrent.numPeers + (torrent.numPeers === 1 ? ' peer' : ' peers');
    console.log('Progress: ' + (torrent.progress * 100).toFixed(1) + '% [' + peers + ']');
}, 1000);

And once we are done, we'll stop reporting the download stats, report instead on seeding and we'll replace the WHOLE HTML page with the first file we find from the torrent:

this.files[0].getBuffer(function(err, file) {
    //-- Overwrite whole document;

Easy peasy eh?

If you want to play around with what I've made so far - please do so! The link to the GitHub for it is: