move sessionprotocol to a full static class

pull/1166/head
Audric Ackermann 5 years ago
parent a92f4ab8da
commit 15f71cb9c8
No known key found for this signature in database
GPG Key ID: 999F434D76324AD4

@ -5,34 +5,38 @@ import { createOrUpdateItem, getItemById } from '../../../js/modules/data';
interface StringToNumberMap { interface StringToNumberMap {
[key: string]: number; [key: string]: number;
} }
// tslint:disable: function-name
// tslint:disable: no-unnecessary-class
export class SessionProtocol {
private static dbLoaded: Boolean = false;
/** /**
* This map olds the sent session timestamps, i.e. session requests message effectively sent to the recipient. * This map olds the sent session timestamps, i.e. session requests message effectively sent to the recipient.
* It is backed by a database entry so it's loaded from db on startup. * It is backed by a database entry so it's loaded from db on startup.
* This map should not be used directly, but instead through * This map should not be used directly, but instead through
* `_updateSendSessionTimestamp()`, `_getSendSessionRequest()` or `_hasSendSessionRequest()` * `updateSendSessionTimestamp()`, `getSendSessionRequest()` or `hasSendSessionRequest()`
*/ */
let sentSessionsTimestamp: StringToNumberMap; private static sentSessionsTimestamp: StringToNumberMap;
/** /**
* This map olds the processed session timestamps, i.e. when we received a session request and handled it. * This map olds the processed session timestamps, i.e. when we received a session request and handled it.
* It is backed by a database entry so it's loaded from db on startup. * It is backed by a database entry so it's loaded from db on startup.
* This map should not be used directly, but instead through * This map should not be used directly, but instead through
* `_updateProcessedSessionTimestamp()`, `_getProcessedSessionRequest()` or `_hasProcessedSessionRequest()` * `updateProcessedSessionTimestamp()`, `getProcessedSessionRequest()` or `hasProcessedSessionRequest()`
*/ */
let processedSessionsTimestamp: StringToNumberMap; private static processedSessionsTimestamp: StringToNumberMap;
/** /**
* This map olds the timestamp on which a sent session reset is triggered for a specific device. * This map olds the timestamp on which a sent session reset is triggered for a specific device.
* Once the message is sent or failed to sent, this device is removed from here. * Once the message is sent or failed to sent, this device is removed from here.
* This is a memory only map. Which means that on app restart it's starts empty. * This is a memory only map. Which means that on app restart it's starts empty.
*/ */
const pendingSendSessionsTimestamp: Set<string> = new Set(); private static readonly pendingSendSessionsTimestamp: Set<string> = new Set();
/** ======= exported functions ======= */
/** Returns true if we already have a session with that device */ /** Returns true if we already have a session with that device */
export async function hasSession(device: string): Promise<boolean> { public static async hasSession(device: string): Promise<boolean> {
// Session does not use the concept of a deviceId, thus it's always 1 // Session does not use the concept of a deviceId, thus it's always 1
const address = new window.libsignal.SignalProtocolAddress(device, 1); const address = new window.libsignal.SignalProtocolAddress(device, 1);
const sessionCipher = new window.libsignal.SessionCipher( const sessionCipher = new window.libsignal.SessionCipher(
@ -47,9 +51,9 @@ export async function hasSession(device: string): Promise<boolean> {
* Returns true if we sent a session request to that device already OR * Returns true if we sent a session request to that device already OR
* if a session request to that device is right now being sent. * if a session request to that device is right now being sent.
*/ */
export async function hasSentSessionRequest(device: string): Promise<boolean> { public static async hasSentSessionRequest(device: string): Promise<boolean> {
const pendingSend = pendingSendSessionsTimestamp.has(device); const pendingSend = SessionProtocol.pendingSendSessionsTimestamp.has(device);
const hasSent = await _hasSentSessionRequest(device); const hasSent = await SessionProtocol._hasSentSessionRequest(device);
return pendingSend || hasSent; return pendingSend || hasSent;
} }
@ -60,10 +64,10 @@ export async function hasSentSessionRequest(device: string): Promise<boolean> {
* - we did not sent a session request already to that device and * - we did not sent a session request already to that device and
* - we do not have a session request currently being send to that device * - we do not have a session request currently being send to that device
*/ */
export async function sendSessionRequestIfNeeded( public static async sendSessionRequestIfNeeded(
device: string device: string
): Promise<void> { ): Promise<void> {
if (hasSession(device) || hasSentSessionRequest(device)) { if (SessionProtocol.hasSession(device) || SessionProtocol.hasSentSessionRequest(device)) {
return Promise.resolve(); return Promise.resolve();
} }
@ -75,11 +79,11 @@ export async function sendSessionRequestIfNeeded(
timestamp: Date.now(), timestamp: Date.now(),
}); });
return sendSessionRequest(sessionReset, device); return SessionProtocol.sendSessionRequest(sessionReset, device);
} }
/** */ /** */
export async function sendSessionRequest( public static async sendSessionRequest(
message: SessionResetMessage, message: SessionResetMessage,
device: string device: string
): Promise<void> { ): Promise<void> {
@ -87,35 +91,35 @@ export async function sendSessionRequest(
// mark the session as being pending send with current timestamp // mark the session as being pending send with current timestamp
// so we know we already triggered a new session with that device // so we know we already triggered a new session with that device
pendingSendSessionsTimestamp.add(device); SessionProtocol.pendingSendSessionsTimestamp.add(device);
// const rawMessage = toRawMessage(message); // const rawMessage = toRawMessage(message);
// // TODO: Send out the request via MessageSender // // TODO: Send out the request via MessageSender
// try { // try {
// await MessageSender.send(rawMessage); // await MessageSender.send(rawMessage);
// await _updateSentSessionTimestamp(device, timestamp); // await SessionProtocolupdateSentSessionTimestamp(device, timestamp);
// } catch (e) { // } catch (e) {
// window.console.log('Failed to send session request to', device); // window.console.log('Failed to send session request to', device);
// } finally { // } finally {
// pendingSendSessionsTimestamp.delete(device); // SessionProtocolpendingSendSessionsTimestamp.delete(device);
// } // }
} }
/** /**
* Called when a session is establish so we store on database this info. * Called when a session is establish so we store on database this info.
*/ */
export async function onSessionEstablished(device: string) { public static async onSessionEstablished(device: string) {
// remove our existing sent timestamp for that device // remove our existing sent timestamp for that device
return _updateSentSessionTimestamp(device, undefined); return SessionProtocol.updateSentSessionTimestamp(device, undefined);
} }
export async function shouldProcessSessionRequest( public static async shouldProcessSessionRequest(
device: string, device: string,
messageTimestamp: number messageTimestamp: number
): Promise<boolean> { ): Promise<boolean> {
const existingSentTimestamp = (await _getSentSessionRequest(device)) || 0; const existingSentTimestamp = (await SessionProtocol.getSentSessionRequest(device)) || 0;
const existingProcessedTimestamp = const existingProcessedTimestamp =
(await _getProcessedSessionRequest(device)) || 0; (await SessionProtocol.getProcessedSessionRequest(device)) || 0;
return ( return (
messageTimestamp > existingSentTimestamp && messageTimestamp > existingSentTimestamp &&
@ -123,68 +127,74 @@ export async function shouldProcessSessionRequest(
); );
} }
export async function onSessionRequestProcessed(device: string) { public static async onSessionRequestProcessed(device: string) {
return _updateProcessedSessionTimestamp(device, Date.now()); return SessionProtocol.updateProcessedSessionTimestamp(device, Date.now());
}
public static reset() {
SessionProtocol.dbLoaded = false;
SessionProtocol.sentSessionsTimestamp = {};
SessionProtocol.processedSessionsTimestamp = {};
} }
/** ======= local / utility functions ======= */
/** /**
* We only need to fetch once from the database, because we are the only one writing to it * We only need to fetch once from the database, because we are the only one writing to it
*/ */
async function _fetchFromDBIfNeeded(): Promise<void> { private static async fetchFromDBIfNeeded(): Promise<void> {
if (!sentSessionsTimestamp) { if (!SessionProtocol.dbLoaded) {
const sentItem = await getItemById( const sentItem = await getItemById(
'sentSessionsTimestamp' 'sentSessionsTimestamp'
); );
if (sentItem) { if (sentItem) {
sentSessionsTimestamp = sentItem.value; SessionProtocol.sentSessionsTimestamp = sentItem.value;
} else { } else {
sentSessionsTimestamp = {}; SessionProtocol.sentSessionsTimestamp = {};
} }
const processedItem = await getItemById( const processedItem = await getItemById(
'processedSessionsTimestamp' 'processedSessionsTimestamp'
); );
if (processedItem) { if (processedItem) {
processedSessionsTimestamp = processedItem.value; SessionProtocol.processedSessionsTimestamp = processedItem.value;
} else { } else {
processedSessionsTimestamp = {}; SessionProtocol.processedSessionsTimestamp = {};
} }
SessionProtocol.dbLoaded = true;
} }
} }
async function _writeToDBSentSessions(): Promise<void> { private static async writeToDBSentSessions(): Promise<void> {
const data = { const data = {
id: 'sentSessionsTimestamp', id: 'sentSessionsTimestamp',
value: JSON.stringify(sentSessionsTimestamp), value: JSON.stringify(SessionProtocol.sentSessionsTimestamp),
}; };
await createOrUpdateItem(data); await createOrUpdateItem(data);
} }
async function _writeToDBProcessedSessions(): Promise<void> { private static async writeToDBProcessedSessions(): Promise<void> {
const data = { const data = {
id: 'processedSessionsTimestamp', id: 'processedSessionsTimestamp',
value: JSON.stringify(processedSessionsTimestamp), value: JSON.stringify(SessionProtocol.processedSessionsTimestamp),
}; };
await createOrUpdateItem(data); await createOrUpdateItem(data);
} }
/** /**
* This is a utility function to avoid duplicated code of _updateSentSessionTimestamp and _updateProcessedSessionTimestamp * This is a utility function to avoid duplicated code of updateSentSessionTimestamp and updateProcessedSessionTimestamp
*/ */
async function _updateSessionTimestamp( private static async updateSessionTimestamp(
device: string, device: string,
timestamp: number | undefined, timestamp: number | undefined,
map: StringToNumberMap map: StringToNumberMap
): Promise<boolean> { ): Promise<boolean> {
await _fetchFromDBIfNeeded(); await SessionProtocol.fetchFromDBIfNeeded();
if (!timestamp) { if (!timestamp) {
if (!!map[device]) { if (!!map[device]) {
delete map.device; delete map.device;
// FIXME double check how are args handle in ts (by ref/value)
return true; return true;
} }
@ -200,53 +210,54 @@ async function _updateSessionTimestamp(
* @param device the device id * @param device the device id
* @param timestamp undefined to remove the key/value pair, otherwise updates the sent timestamp and write to DB * @param timestamp undefined to remove the key/value pair, otherwise updates the sent timestamp and write to DB
*/ */
async function _updateSentSessionTimestamp( private static async updateSentSessionTimestamp(
device: string, device: string,
timestamp: number | undefined timestamp: number | undefined
): Promise<void> { ): Promise<void> {
if (_updateSessionTimestamp(device, timestamp, sentSessionsTimestamp)) { if (SessionProtocol.updateSessionTimestamp(device, timestamp, SessionProtocol.sentSessionsTimestamp)) {
await _writeToDBSentSessions(); await SessionProtocol.writeToDBSentSessions();
} }
} }
/** /**
* timestamp undefined to remove the key/value pair, otherwise updates the processed timestamp and writes to DB * timestamp undefined to remove the key/value pair, otherwise updates the processed timestamp and writes to DB
*/ */
async function _updateProcessedSessionTimestamp( private static async updateProcessedSessionTimestamp(
device: string, device: string,
timestamp: number | undefined timestamp: number | undefined
): Promise<void> { ): Promise<void> {
if (_updateSessionTimestamp(device, timestamp, processedSessionsTimestamp)) { if (SessionProtocol.updateSessionTimestamp(device, timestamp, SessionProtocol.processedSessionsTimestamp)) {
await _writeToDBProcessedSessions(); await SessionProtocol.writeToDBProcessedSessions();
} }
} }
/** /**
* This is a utility function to avoid duplicate code between `_getProcessedSessionRequest()` and `_getSentSessionRequest()` * This is a utility function to avoid duplicate code between `getProcessedSessionRequest()` and `getSentSessionRequest()`
*/ */
async function _getSessionRequest( private static async getSessionRequest(
device: string, device: string,
map: StringToNumberMap map: StringToNumberMap
): Promise<number | undefined> { ): Promise<number | undefined> {
await _fetchFromDBIfNeeded(); await SessionProtocol.fetchFromDBIfNeeded();
return map[device]; return map[device];
} }
async function _getSentSessionRequest( private static async getSentSessionRequest(
device: string device: string
): Promise<number | undefined> { ): Promise<number | undefined> {
return _getSessionRequest(device, sentSessionsTimestamp); return SessionProtocol.getSessionRequest(device, SessionProtocol.sentSessionsTimestamp);
} }
async function _getProcessedSessionRequest( private static async getProcessedSessionRequest(
device: string device: string
): Promise<number | undefined> { ): Promise<number | undefined> {
return _getSessionRequest(device, processedSessionsTimestamp); return SessionProtocol.getSessionRequest(device, SessionProtocol.processedSessionsTimestamp);
} }
async function _hasSentSessionRequest(device: string): Promise<boolean> { private static async _hasSentSessionRequest(device: string): Promise<boolean> {
await _fetchFromDBIfNeeded(); await SessionProtocol.fetchFromDBIfNeeded();
return !!sentSessionsTimestamp[device]; return !!SessionProtocol.sentSessionsTimestamp[device];
}
} }

@ -1,4 +1,4 @@
import * as SessionProtocol from './SessionProtocol'; import {SessionProtocol} from './SessionProtocol';
import * as MultiDeviceProtocol from './MultiDeviceProtocol'; import * as MultiDeviceProtocol from './MultiDeviceProtocol';
export { SessionProtocol, MultiDeviceProtocol }; export { SessionProtocol, MultiDeviceProtocol };

Loading…
Cancel
Save