signal-desktop/ts/util/incrementMessageCounter.ts

71 lines
2 KiB
TypeScript
Raw Normal View History

2021-03-04 21:44:57 +00:00
// Copyright 2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
2021-09-15 18:45:22 +00:00
import { debounce, isNumber } from 'lodash';
import { strictAssert } from './assert';
import Data from '../sql/Client';
import * as log from '../logging/log';
2021-03-04 21:44:57 +00:00
let receivedAtCounter: number | undefined;
2021-09-15 18:45:22 +00:00
export async function initializeMessageCounter(): Promise<void> {
strictAssert(
receivedAtCounter === undefined,
'incrementMessageCounter: already initialized'
);
const storedCounter = Number(localStorage.getItem('lastReceivedAtCounter'));
const dbCounter = await Data.getMaxMessageCounter();
if (isNumber(dbCounter) && isNumber(storedCounter)) {
log.info('initializeMessageCounter: picking max of db/stored counters');
2021-09-15 18:45:22 +00:00
receivedAtCounter = Math.max(dbCounter, storedCounter);
if (receivedAtCounter !== storedCounter) {
log.warn('initializeMessageCounter: mismatch between db/stored counters');
2021-09-15 18:45:22 +00:00
}
} else if (isNumber(storedCounter)) {
log.info('initializeMessageCounter: picking stored counter');
2021-09-15 18:45:22 +00:00
receivedAtCounter = storedCounter;
} else if (isNumber(dbCounter)) {
log.info(
2021-09-15 18:45:22 +00:00
'initializeMessageCounter: picking fallback counter from the database'
);
receivedAtCounter = dbCounter;
} else {
log.info('initializeMessageCounter: defaulting to Date.now()');
2021-09-15 18:45:22 +00:00
receivedAtCounter = Date.now();
2021-03-04 21:44:57 +00:00
}
2021-09-15 18:45:22 +00:00
if (storedCounter !== receivedAtCounter) {
localStorage.setItem('lastReceivedAtCounter', String(receivedAtCounter));
}
}
export function incrementMessageCounter(): number {
strictAssert(
receivedAtCounter !== undefined,
'incrementMessageCounter: not initialized'
);
receivedAtCounter += 1;
2021-03-04 21:44:57 +00:00
debouncedUpdateLastReceivedAt();
return receivedAtCounter;
2021-03-04 21:44:57 +00:00
}
2021-09-08 23:28:18 +00:00
export function flushMessageCounter(): void {
debouncedUpdateLastReceivedAt.flush();
}
const debouncedUpdateLastReceivedAt = debounce(
() => {
localStorage.setItem('lastReceivedAtCounter', String(receivedAtCounter));
},
25,
{
maxWait: 25,
}
);