diff --git a/CHANGELOG.md b/CHANGELOG.md index b259d72..43c28f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ - API deployment with Docker and Nginx web server. +## [1.1.1] - + +### Fix + +- Cleaning up session store before starting websocket server + ## [1.1.0] - 2022-01-31 ### Added diff --git a/app/Services/WsService.ts b/app/Services/WsService.ts index 2cc313f..7d29e51 100644 --- a/app/Services/WsService.ts +++ b/app/Services/WsService.ts @@ -59,8 +59,20 @@ class WsService { }); this.sessionStore = new RedisSessionStore(Redis.connection('session')); - this.setupMiddlewares(); - this.listen(); + /** + * Clean up sessions before start + */ + this.sessionStore.destroyAllSessions().then(() => { + /** + * Middlewares + */ + this.setupMiddlewares(); + + /** + * On connection socket + */ + this.listen(); + }); } private listen() { diff --git a/app/Store/SessionStore.ts b/app/Store/SessionStore.ts index 12e43c6..afa715c 100644 --- a/app/Store/SessionStore.ts +++ b/app/Store/SessionStore.ts @@ -25,6 +25,20 @@ class RedisSessionStore { }; } + private async scanSessionKeys(): Promise> { + const keys = new Set(); + let nextIndex = 0; + + do { + // eslint-disable-next-line no-await-in-loop + const [nextIndexAsStr, result] = await this.redisClient.scan(nextIndex, 'MATCH', '*', 'COUNT', 100); + nextIndex = parseInt(nextIndexAsStr, 10); + result.forEach(s => keys.add(s)); + } while (nextIndex !== 0); + + return keys; + } + /** * Return session data by session id * @@ -40,15 +54,7 @@ class RedisSessionStore { * Returns the all sessions from store */ public async getSessions(): Promise> { - const keys = new Set(); - let nextIndex = 0; - - do { - // eslint-disable-next-line no-await-in-loop - const [nextIndexAsStr, result] = await this.redisClient.scan(nextIndex, 'MATCH', '*', 'COUNT', 100); - nextIndex = parseInt(nextIndexAsStr, 10); - result.forEach(s => keys.add(s)); - } while (nextIndex !== 0); + const keys = await this.scanSessionKeys(); const commands = Array.from(keys).map(key => { // eslint-disable-next-line @typescript-eslint/no-unused-vars const [prefix, ...id] = key.split('-'); @@ -103,6 +109,27 @@ class RedisSessionStore { return 0; } + + /** + * Remove all sessions from redis store + * + * @returns Count of deleted sessions + */ + public async destroyAllSessions() { + const keys = await this.scanSessionKeys().then(values => + Array.from(values).map(v => { + const [, ...key] = v.split('-'); + return key.join('-'); + }) + ); + + if (keys.length > 0) { + const deleted = await this.redisClient.del(keys); + return deleted; + } + + return 0; + } } export default RedisSessionStore;