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 instant.io 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 instant.io uses for finding p2p clients.

function startGather() {
    var hash = document.getElementById('hashField').value;
    var client = new WebTorrent();
    client.add("magnet:?tr=udp%3A%2F%2Fexodus.desync.com%3A6969&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Ftracker.internetwarriors.net%3A1337&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Ftracker.openbittorrent.com%3A80&tr=wss%3A%2F%2Ftracker.btorrent.xyz&tr=wss%3A%2F%2Ftracker.fastcast.nz&tr=wss%3A%2F%2Ftracker.openwebtorrent.com&xt=urn:btih:" + 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
    document.open();
    document.write(file.toString());
    document.close();
});

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: https://github.com/JakePrice86/ServerLessWebsite