0f3d379e402529d57e8000328f0de86a886ce647
[squeep-indie-auther] / src / chores.js
1 'use strict';
2
3 const common = require('./common');
4 const Enum = require('./enum');
5 const { Chores: BaseChores } = require('@squeep/chores');
6 const _fileScope = common.fileScope(__filename);
7
8 /**
9 * Wrangle periodic tasks what need doing.
10 */
11
12 class Chores extends BaseChores {
13 constructor(logger, db, options) {
14 super(logger);
15 this.options = options;
16 this.db = db;
17
18 this.establishChore(Enum.Chore.CleanTokens, this.cleanTokens.bind(this), options?.chores?.tokenCleanupMs);
19 this.establishChore(Enum.Chore.CleanScopes, this.cleanScopes.bind(this), options?.chores?.scopeCleanupMs);
20 }
21
22 /**
23 * Attempt to remove tokens which are expired or otherwise no longer valid.
24 * @param {Number} atLeastMsSinceLast
25 */
26 async cleanTokens(atLeastMsSinceLast = this.options?.chores?.tokenCleanupMs || 0) {
27 const _scope = _fileScope('cleanTokens');
28 this.logger.debug(_scope, 'called', atLeastMsSinceLast);
29
30 let tokensCleaned;
31 try {
32 await this.db.context(async (dbCtx) => {
33 const codeValidityTimeoutSeconds = Math.ceil(this.options.manager.codeValidityTimeoutMs / 1000);
34 tokensCleaned = await this.db.tokenCleanup(dbCtx, codeValidityTimeoutSeconds, atLeastMsSinceLast);
35 }); // dbCtx
36 if (tokensCleaned) {
37 this.logger.info(_scope, 'finished', { tokensCleaned });
38 }
39 } catch (e) {
40 this.logger.error(_scope, 'failed', { error: e });
41 throw e;
42 }
43 }
44
45
46 /**
47 * Attempt to remove ephemeral scopes which are no longer referenced by tokens.
48 * @param {Number} atLeastMsSinceLast
49 */
50 async cleanScopes(atLeastMsSinceLast = this.options?.chores?.scopeCleanupMs || 0) {
51 const _scope = _fileScope('cleanScopes');
52 this.logger.debug(_scope, 'called', atLeastMsSinceLast);
53
54 let scopesCleaned;
55 try {
56 await this.db.context(async (dbCtx) => {
57 scopesCleaned = await this.db.scopeCleanup(dbCtx, atLeastMsSinceLast);
58 }); // dbCtx
59 if (scopesCleaned) {
60 this.logger.info(_scope, 'finished', { scopesCleaned });
61 }
62 } catch (e) {
63 this.logger.error(_scope, 'failed', { error: e });
64 throw e;
65 }
66 }
67
68 } // IAChores
69
70 module.exports = Chores;