Sharing 2: Sharin' it to the Streets

June 22, 2017

So, I’ve been working with Sharing, the ephemeral shared data tool I made in the last post, and I think it’s clear to me now how bad the original API is. You could get everything you needed done, sure. But it was, at moments, quite confusing.

For instance, I like knowing what the shared state is before I make any writes. This is possible to implement on top of the API, but it’s awkward. Managing connection state was awkward. Explicitly separating creating and joining was awkward. It was bad.

So now I have a new API (the old one still works, because I’m still converting some not-mine code over to it – and who knows if you guys have been using it). Here it is:

Sharing.meet(
  name : String,
  password : String,
  onNewData : (String) => ()
) : Meeting

Sharing.meetAnyone(
  name : String,
  max_listeners : Int,
  onNewData : (String) => ()
) : Meeting

Sharing.setNamePrefix(namePrefix : String) : void

Meeting : {
  getInitialData : (callback : (data) => ()) => (),
  send : (data, onSuccess) => (),
  close: () => (), // no new subscribers
  leave : () => () // no more new data
}

The idea is, you connect with the meet functions – where meetAnyone is a shared queue – and use the Meeting object to drive your non-onNewData interactions. The new functions also use a name prefix – defaulting to the hostname it runs on – to provide basic isolation from people you don’t want to bump into. Cross domain communication is cool, though, so the setNamePrefix function lets you avoid that isolation.

I’m also thinking of adding a Meeting.destroy method that not only cleans up server resources but lets all the other listeners know to stop listening. But I feel that API should be paired with an onDestroyed hook, and I’m not entirely convinced this makes sense for things that can be auto-evicted (like all ephemeral stores like this). If it’s used for any application level purpose e.g. the game you were playing is over, then it might be confused with a server-generated resource reclaiming, and those are rarely interchangeable events. So I’m still noodling that. But in the meantime, all previous versions of the API will still work, and sending an application-specific shutdown message is considered best.