Firebase

jyke.savia@tut.fi

Firebase is simple Database in the cloud

Marketing slogans:

  • key-value data
  • realtime syncronization
  • security
  • automatic scaling

hierarchy of data

- firebase forge -

programming

  • client libraries: javascript, iOS/OSX, Java/Android
  • server libraries: node.js
  • general REST API

events


var fbRef = new Firebase('https://sample.firebaseio.com/');
fbRef.child('users').on('event', function(dataSnapshot) {
  // event code
}
	
  • value
  • child_added
  • child_removed
  • child_changed

change data

  • set()
  • update()
  • remove()
  • setWithPriority()

Data can be: array, string, number, boolean, null or object

dy.fi/idy


function pressed( button ) 
{
  var other = button=='A' ? 'B' : 'A';

  jykev.fb.child( button ).child( jykev.UUID ).set( true );
  jykev.fb.child( other ).child( jykev.UUID ).remove();

}
	

jykev.fb.child('A').on('child_added', function(snap,old) {
	new_vote('A', snap.name() );
});
jykev.fb.child('B').on('child_added', function(snap,old) {
	new_vote('B', snap.name() );
});
jykev.fb.child('A').on('child_removed', function(snap) {
	remove_vote('A', snap.name() );
});
jykev.fb.child('B').on('child_removed', function(snap) {
	remove_vote('B', snap.name() );
});
	

function new_vote( button, name )
{
  button === 'A' ? jykev.countA += 1 : jykev.countB += 1;
  if( name === jykev.UUID ) highlightButton( button );
  updateCounts();
}

function remove_vote( button, name )
{
  button === 'A' ? jykev.countA -= 1 : jykev.countB -= 1;
  if( name === jykev.UUID ) offButton( button );
  updateCounts();
}
	

// get vote configuration
jykev.fb.child('info').once('value', function(snapshot) {
      jykev.info = snapshot.val();
      if(jykev.info === null) {
	$('#info').html('No '+name+' vote in progress');
      } else {
	$('#title').text( jykev.info.name );
	$('#txtA').text( jykev.info.buttonA );
	$('#txtB').text( jykev.info.buttonB );
	zoomText();
...
	

dy.fi/idy

push


var msgRef= 
  new Firebase('https://SampleChat.firebaseIO-demo.com/message_list');
msgRef.push({'user_id': 'fred', 'text': 'Yabba Dabba Doo!'});
	
The unique name generated by push( ) is prefixed with a client-generated timestamp so that the resulting list will be chronologically-sorted.

update limiting


var msgRef = 
  new Firebase('https://SampleChat.firebaseIO-demo.com/message_list');
lastMessagesQuery = msgRef.endAt().limit(500);
lastMessagesQuery.on('child_added', function(childSnapshot) { 
	/* handle child add */ 
});
	
The child_added event will only be triggered for the last 500 messages.

transactions


// Increment Fred's rank by 1.
var fredRankRef = 
  new Firebase('https://SampleChat.firebaseIO-demo.com/users/fred/rank');
fredRankRef.transaction(function(currentRank) {
  return currentRank+1;
});
	

// Try to create a user for wilma, but only if the user 
// id 'wilma' isn't already taken.
var wilmaRef = 
  new Firebase('https://SampleChat.firebaseIO-demo.com/users/wilma');
wilmaRef.transaction(function(currentData) {
  if (currentData === null) {
    return {name: {first: 'Wilma', last: 'Flintstone'} };
  } else {
    console.log('User wilma already exists.');
    return; // Abort the transaction.
  }
}, function(error, committed, snapshot) {
  if (error)
    console.log('Transaction failed abnormally!', error);
  else if (!committed)
    console.log('aborted (because wilma already exists).');
  else
    console.log('User wilma added!');
  console.log('Wilma\'s data: ', snapshot.val());
});
	

online status


var presenceRef = 
  new Firebase('https://SampleChat.firebaseIO-demo.com/disconnectmessage');
// Write a string when I lose my connection
presenceRef.onDisconnect().set("I disconnected!");
	

var connectedRef = 
  new Firebase("https://SampleChat.firebaseIO-demo.com/.info/connected");
connectedRef.on("value", function(snap) {
  if (snap.val() === true) {
    alert("connected");
  } else {
    alert("not connected");
  }
});
	

Authentication


var commentsRef = 
  new Firebase("https://FireTube.firebaseIO-demo.com/");

var auth = new FirebaseSimpleLogin(commentsRef, 
function(error, user) {
  if (!error) {
    // Success!
  }
});

auth.login('facebook');
	
Facebook, Twitter, Github, Persona or Email&Password

Custom token

Your own application server can generate an auth token for the client.

Server Security Rules

JSON / javascript syntax for rules enforced by the firebase servers


{
  "rules": {
    ".read": true,
    ".write": "auth != null"
  }
}
	

{
  "rules": {
    ".read": true,
    "comments": {
      "$comment": {
        ".write": "auth != null && !data.exists()",
        ".validate": "newData.hasChildren(['userid', 'body']) 
                     && newData.child('body').isString()
                     && auth.id == newData.child('userid')"
      }
    }
  }
}
	

distributed systems - Brewer's theorem

consistency, availability, partition tolerance - pick two

 

All Firebase Writes Are Local. Every client sharing a Firebase maintains its own internal version of any active data. When data is written, it is written to this local version of the Firebase. The Firebase client then synchronizes that data with the Firebase servers and with other clients on a best-effort basis.

integration

  • BackFire - Backbone.js
  • AngularFire - AngularJS

data lock-in

  • you can export your data in JSON
  • programming API not compatible with anything

scaling

Automatic Scaling- The Firebase API is built from the ground up for performance and scale. Whenever your data changes, Firebase calculates the minimum set of updates required to keep all your clients in sync. In addition, all Firebase API functions are designed to scale linearly with the size of the data being synchronized. More importantly, Firebase handles all of the scaling and operations for you. Your app will scale from its first user to its first million without any code changes.

implementation

New browsers use websockets for events.

Older browsers revert to long polling

Location

Service IP:s revert to

  • http://www.softlayer.com/ Founded in 2005, SoftLayer Technologies, Inc. is a dedicated server, managed hosting and cloud computing provider.
  • http://www.theplanet.com/ (will redirect to softlayer.com) The Planet was a privately held dedicated server company based in Texas.

summary

key-value data
realtime syncronization best effort
security simple and advanced features
automatic scaling more than one server. otherwise ??