-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathd.js
67 lines (67 loc) · 2.9 KB
/
d.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
import { syncIfPossible } from './syncIfPossible';
import { MINUTES } from '../helpers/date-constants';
export function LocalSyncWorker(db, cloudOptions, cloudSchema) {
let localSyncEventSubscription = null;
//let syncHandler: ((event: Event) => void) | null = null;
//let periodicSyncHandler: ((event: Event) => void) | null = null;
let cancelToken = { cancelled: false };
let retryHandle = null;
let retryPurpose = null; // "pull" is superset of "push"
function syncAndRetry(purpose, retryNum = 1) {
// Use setTimeout() to get onto a clean stack and
// break free from possible active transaction:
setTimeout(() => {
if (retryHandle)
clearTimeout(retryHandle);
const combPurpose = retryPurpose === 'pull' ? 'pull' : purpose;
retryHandle = null;
retryPurpose = null;
syncIfPossible(db, cloudOptions, cloudSchema, {
cancelToken,
retryImmediatelyOnFetchError: true, // workaround for "net::ERR_NETWORK_CHANGED" in chrome.
purpose: combPurpose,
}).catch((e) => {
console.error('error in syncIfPossible()', e);
if (cancelToken.cancelled) {
stop();
}
else if (retryNum < 3) {
// Mimic service worker sync event: retry 3 times
// * first retry after 5 minutes
// * second retry 15 minutes later
const combinedPurpose = retryPurpose && retryPurpose === 'pull' ? 'pull' : purpose;
const handle = setTimeout(() => syncAndRetry(combinedPurpose, retryNum + 1), [0, 5, 15][retryNum] * MINUTES);
// Cancel the previous retryHandle if it exists to avoid scheduling loads of retries.
if (retryHandle)
clearTimeout(retryHandle);
retryHandle = handle;
retryPurpose = combinedPurpose;
}
});
}, 0);
}
const start = () => {
// Sync eagerly whenever a change has happened (+ initially when there's no syncState yet)
// This initial subscribe will also trigger an sync also now.
console.debug('Starting LocalSyncWorker', db.localSyncEvent['id']);
localSyncEventSubscription = db.localSyncEvent.subscribe(({ purpose }) => {
try {
syncAndRetry(purpose || 'pull');
}
catch (err) {
console.error('What-the....', err);
}
});
//setTimeout(()=>db.localSyncEvent.next({}), 5000);
};
const stop = () => {
console.debug('Stopping LocalSyncWorker');
cancelToken.cancelled = true;
if (localSyncEventSubscription)
localSyncEventSubscription.unsubscribe();
};
return {
start,
stop,
};
}