 Fiber = Npm.require 'fibers'
 
-SyncToken = new Mongo.Collection 'meteor.SyncToken'
+SYNC_TOKEN_ID = 'syncToken'
+LAST_UPDATED_ID = 'lastUpdated'
+
+SyncState = new Mongo.Collection 'meteor.SyncState'
+
 Packages = new Mongo.Collection 'meteor.Packages'
 Versions = new Mongo.Collection 'meteor.Versions'
 Builds = new Mongo.Collection 'meteor.Builds'

        Versions.find(packageName: oldPackage.packageName).forEach (document, index, cursor) ->
          insertLatestPackage document

    initializing = false

    console.log "Latest packages observe initialized"

    connection = DDP.connect 'packages.meteor.com'

    Defaults = new Mongo.Collection 'defaults', connection
    Changes = new Mongo.Collection 'changes', connection

    connection.subscribe 'defaults', ->
      try
        SyncToken.insert
          _id: 'syncToken'
          syncToken: Defaults.findOne().syncToken
      catch error
        throw error unless /E11000 duplicate key error index:.*SyncToken\.\$_id/.test error.err

      connection.subscribe 'changes', ->
        Changes.find().observe
          added: (document) ->
            sync connection
          changed: (document, oldDocument) ->
            sync connection

  .run()

    console.log "ReleaseTracks - all: #{ReleaseTracks.find().count()}, new: #{newReleaseTracks}, updated: #{updatedReleaseTracks}" if newReleaseTracks or updatedReleaseTracks
    console.log "ReleaseVersions - all: #{ReleaseVersions.find().count()}, new: #{newReleaseVersions}, updated: #{updatedReleaseVersions}" if newReleaseVersions or updatedReleaseVersions

    # We store the new token only after all data in the result has been processed. This assures
    # that if this run has been prematurely terminated, we restart again correctly next time.
    SyncState.update
      _id: SYNC_TOKEN_ID
    ,
      $set:
        syncToken: result.syncToken
