Mailspring/internal_packages/worker-sync/lib/nylas-sync-worker.coffee

173 lines
4.5 KiB
CoffeeScript
Raw Normal View History

_ = require 'underscore'
{Actions, DatabaseStore} = require 'nylas-exports'
2015-05-16 01:53:00 +08:00
NylasLongConnection = require './nylas-long-connection'
refactor(*): Thread list fixes, flexible workspace store, multiple root sheets Summary: Remember to remove all the event listeners added to email frame New files tab, queryable filename, not attribute Rename ThreadSelectionBar to RootSelectionBar to go with RootCenterComponent, make it appear for draft selection and file selection as well Initial file list and file list store, File Location Remove unnecessary shouldComponentUpdate Always track whether new requests have happened since ours to prevent out of order triggers Always scroll to the current [focused/keyboard-cursor] in lists So goodbye to the trash tag Only scroll to current item if focus or keyboard has moved Show message snippet in notification if no subject line Make the RootSelectionBar pull items from Component Registry New Archive button (prettier than the other one) Refactor event additions to iframe so iframe can be used for file display also Thread List is no longer the uber root package - drafts and files moved to separate packages WorkspaceStore now allows packages to register sheets, "view" concept replaced with "root sheet" concept, "mode" may not be observed by all sheets, and is now called "preferred mode" Don't animate transitions between two root sheets Mode switch is only visible on root sheets that support multiple modes Account sidebar now shows "Views" that have registered themselves: drafts and files for now Model Selection Bar is now a component, just like ModelList. Meant to be in the toolbar above a Model List Misc supporting changes New files package which registers it's views and components Rename files package to `file-list` Move checkmark column down into model list Don't throw exception if shift-down arrow and nothing selected Takes a long time on login to fetch first page of threads, make pages smaller Displaynames, spec fixes Test Plan: Run tests Reviewers: evan Reviewed By: evan Differential Revision: https://review.inboxapp.com/D1412
2015-04-11 05:33:05 +08:00
PAGE_SIZE = 250
# BackoffTimer is a small helper class that wraps setTimeout. It fires the function
# you provide at a regular interval, but backs off each time you call `backoff`.
#
class BackoffTimer
constructor: (@fn) ->
@reset()
cancel: =>
clearTimeout(@_timeout) if @_timeout
@_timeout = null
reset: =>
@cancel()
@_delay = 20 * 1000
backoff: =>
@_delay = Math.min(@_delay * 1.4, 5 * 1000 * 60) # Cap at 5 minutes
if not atom.inSpecMode()
console.log("Backing off after sync failure. Will retry in #{Math.floor(@_delay / 1000)} seconds.")
start: =>
clearTimeout(@_timeout) if @_timeout
@_timeout = setTimeout =>
@_timeout = null
@fn()
, @_delay
module.exports =
2015-05-16 01:53:00 +08:00
class NylasSyncWorker
constructor: (api, account) ->
2015-05-16 01:53:00 +08:00
@_api = api
@_account = account
@_terminated = false
@_connection = new NylasLongConnection(api, account.id)
@_resumeTimer = new BackoffTimer =>
# indirection needed so resumeFetches can be spied on
@resumeFetches()
@_unlisten = Actions.retryInitialSync.listen(@_onRetryInitialSync, @)
@_state = null
DatabaseStore.findJSONObject("NylasSyncWorker:#{@_account.id}").then (json) =>
@_state = json ? {}
for model, modelState of @_state
modelState.busy = false
@resumeFetches()
@
2015-05-16 01:53:00 +08:00
account: ->
@_account
connection: ->
@_connection
state: ->
@_state
busy: ->
return false unless @_state
for key, state of @_state
if state.busy
return true
false
start: ->
@_resumeTimer.start()
@_connection.start()
@resumeFetches()
cleanup: ->
@_unlisten?()
@_resumeTimer.cancel()
@_connection.end()
@_terminated = true
@
resumeFetches: =>
return unless @_state
# Stop the timer. If one or more network requests fails during the fetch process
# we'll backoff and restart the timer.
@_resumeTimer.cancel()
@fetchCollection('threads')
@fetchCollection('calendars')
@fetchCollection('events')
@fetchCollection('contacts')
@fetchCollection('drafts')
if @_account.usesLabels()
@fetchCollection('labels')
if @_account.usesFolders()
@fetchCollection('folders')
fetchCollection: (model, options = {}) ->
return unless @_state
return if @_state[model]?.complete and not options.force?
return if @_state[model]?.busy
@_state[model] =
complete: false
error: null
busy: true
count: 0
fetched: 0
@writeState()
@fetchCollectionCount(model)
@fetchCollectionPage(model, {offset: 0, limit: PAGE_SIZE})
fetchCollectionCount: (model) ->
@_api.makeRequest
accountId: @_account.id
path: "/#{model}"
returnsModel: false
qs:
view: 'count'
success: (response) =>
return if @_terminated
@updateTransferState(model, count: response.count)
error: (err) =>
return if @_terminated
@_resumeTimer.backoff()
@_resumeTimer.start()
fetchCollectionPage: (model, params = {}) ->
requestStartTime = Date.now()
requestOptions =
error: (err) =>
return if @_terminated
@_resumeTimer.backoff()
@_resumeTimer.start()
@updateTransferState(model, {busy: false, complete: false, error: err.toString()})
success: (json) =>
return if @_terminated
lastReceivedIndex = params.offset + json.length
if json.length is params.limit
nextParams = _.extend({}, params, {offset: lastReceivedIndex})
nextDelay = Math.max(0, 1500 - (Date.now() - requestStartTime))
setTimeout(( => @fetchCollectionPage(model, nextParams)), nextDelay)
@updateTransferState(model, {fetched: lastReceivedIndex})
else
@updateTransferState(model, {fetched: lastReceivedIndex, busy: false, complete: true})
if model is 'threads'
@_api.getThreads(@_account.id, params, requestOptions)
else
@_api.getCollection(@_account.id, model, params, requestOptions)
2015-05-16 01:53:00 +08:00
updateTransferState: (model, {busy, error, complete, fetched, count}) ->
@_state[model] = _.defaults({busy, error, complete, fetched, count}, @_state[model])
@writeState()
writeState: ->
@_writeState ?= _.debounce =>
DatabaseStore.persistJSONObject("NylasSyncWorker:#{@_account.id}", @_state)
,100
@_writeState()
_onRetryInitialSync: =>
@resumeFetches()
NylasSyncWorker.BackoffTimer = BackoffTimer