/
PollingBackend.js
228 lines (196 loc) Β· 6.16 KB
/
PollingBackend.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
/**
* @copyright Copyright (c) 2019 Julius HΓ€rtl <jus@bitgrid.net>
*
* @author Julius HΓ€rtl <jus@bitgrid.net>
*
* @license AGPL-3.0-or-later
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
import { logger } from '../helpers/logger.js'
import { SyncService, ERROR_TYPE } from './SyncService.js'
import { Connection } from './SessionApi.js'
/**
* Minimum inverval to refetch the document changes
*
* @type {number} time in ms
*/
const FETCH_INTERVAL = 300
/**
* Maximum interval between refetches of document state if multiple users have joined
*
* @type {number} time in ms
*/
const FETCH_INTERVAL_MAX = 5000
/**
* Interval to check for changes when there is only one user joined
*
* @type {number} time in ms
*/
const FETCH_INTERVAL_SINGLE_EDITOR = 5000
/**
* Interval to fetch for changes when a browser window is considered invisible by the
* page visibility API https://developer.mozilla.org/de/docs/Web/API/Page_Visibility_API
*
* @type {number} time in ms
*/
const FETCH_INTERVAL_INVISIBLE = 60000
/* Maximum number of retries for fetching before emitting a connection error */
const MAX_RETRY_FETCH_COUNT = 5
/**
* Timeout for sessions to be marked as disconnected
* Make sure that this is higher than any FETCH_INTERVAL_ values
*/
const COLLABORATOR_DISCONNECT_TIME = FETCH_INTERVAL_INVISIBLE * 1.5
class PollingBackend {
/** @type {SyncService} */
#syncService
/** @type {Connection} */
#connection
#lastPoll
#fetchInterval
#fetchRetryCounter
#pollActive
#initialLoadingFinished
constructor(syncService, connection) {
this.#syncService = syncService
this.#connection = connection
this.#fetchInterval = FETCH_INTERVAL
this.#fetchRetryCounter = 0
this.#lastPoll = 0
}
connect() {
if (this.fetcher > 0) {
console.error('Trying to connect, but already connected')
return
}
this.#initialLoadingFinished = false
this.fetcher = setInterval(this._fetchSteps.bind(this), 50)
document.addEventListener('visibilitychange', this.visibilitychange.bind(this))
}
/**
* This method is only called though the timer
*/
async _fetchSteps() {
if (this.#pollActive) {
return
}
const now = Date.now()
if (this.#lastPoll > (now - this.#fetchInterval)) {
return
}
if (!this.fetcher) {
console.error('No inverval but triggered')
return
}
this.#pollActive = true
try {
logger.debug('[PollingBackend] Fetching steps', this.#syncService.version)
const response = await this.#connection.sync({
version: this.#syncService.version,
force: false,
manualSave: false,
})
this._handleResponse(response)
} catch (e) {
this._handleError(e)
} finally {
this.#lastPoll = Date.now()
this.#pollActive = false
}
}
_handleResponse({ data }) {
const { document, sessions } = data
this.#fetchRetryCounter = 0
this.#syncService.emit('change', { document, sessions })
this.#syncService._receiveSteps(data)
if (data.steps.length === 0) {
if (!this.#initialLoadingFinished) {
this.#initialLoadingFinished = true
}
if (this.#syncService.checkIdle()) {
return
}
const disconnect = Date.now() - COLLABORATOR_DISCONNECT_TIME
const alive = sessions.filter((s) => s.lastContact * 1000 > disconnect)
if (alive.length < 2) {
this.maximumRefetchTimer()
} else {
this.increaseRefetchTimer()
}
this.#syncService.emit('stateChange', { initialLoading: true })
return
}
if (this.#initialLoadingFinished) {
this.resetRefetchTimer()
}
}
_handleError(e) {
if (!e.response || e.code === 'ECONNABORTED') {
if (this.#fetchRetryCounter++ >= MAX_RETRY_FETCH_COUNT) {
logger.error('[PollingBackend:fetchSteps] Network error when fetching steps, emitting CONNECTION_FAILED')
this.#syncService.emit('error', { type: ERROR_TYPE.CONNECTION_FAILED, data: {} })
} else {
logger.error(`[PollingBackend:fetchSteps] Network error when fetching steps, retry ${this.#fetchRetryCounter}`)
}
} else if (e.response.status === 409) {
// Still apply the steps to update our version of the document
this._handleResponse(e.response)
logger.error('Conflict during file save, please resolve')
this.#syncService.emit('error', {
type: ERROR_TYPE.SAVE_COLLISSION,
data: {
outsideChange: e.response.data.outsideChange,
},
})
} else if (e.response.status === 403) {
this.#syncService.emit('error', { type: ERROR_TYPE.SOURCE_NOT_FOUND, data: {} })
this.disconnect()
} else if (e.response.status === 404) {
this.#syncService.emit('error', { type: ERROR_TYPE.SOURCE_NOT_FOUND, data: {} })
this.disconnect()
} else if (e.response.status === 503) {
this.increaseRefetchTimer()
this.#syncService.emit('error', { type: ERROR_TYPE.CONNECTION_FAILED, data: {} })
logger.error('Failed to fetch steps due to unavailable service', { error: e })
} else {
this.disconnect()
this.#syncService.emit('error', { type: ERROR_TYPE.CONNECTION_FAILED, data: {} })
logger.error('Failed to fetch steps due to other reason', { error: e })
}
}
disconnect() {
clearInterval(this.fetcher)
this.fetcher = 0
document.removeEventListener('visibilitychange', this.visibilitychange.bind(this))
}
resetRefetchTimer() {
this.#fetchInterval = FETCH_INTERVAL
}
increaseRefetchTimer() {
this.#fetchInterval = Math.min(this.#fetchInterval * 2, FETCH_INTERVAL_MAX)
}
maximumRefetchTimer() {
this.#fetchInterval = FETCH_INTERVAL_SINGLE_EDITOR
}
visibilitychange() {
if (document.visibilityState === 'hidden') {
this.#fetchInterval = FETCH_INTERVAL_INVISIBLE
} else {
this.resetRefetchTimer()
}
}
}
export default PollingBackend