Skip to content

Commit

Permalink
feat(files): cache usage on Redis
Browse files Browse the repository at this point in the history
  • Loading branch information
sg-gs committed Jun 11, 2024
1 parent 9133acb commit dd9d38c
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 6 deletions.
24 changes: 18 additions & 6 deletions src/app/services/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const MailService = require('./mail');
const UtilsService = require('./utils');
const passport = require('../middleware/passport');
const Logger = require('../../lib/logger').default;
const { default: Redis } = require('../../config/initializers/redis');

const { Op, col, fn } = sequelize;

Expand Down Expand Up @@ -508,13 +509,24 @@ module.exports = (Model, App) => {

const getUsage = async (user) => {
const targetUser = await Model.users.findOne({ where: { username: user.bridgeUser } });
const usage = await Model.file.findAll({
where: { user_id: targetUser.id, status: { [Op.ne]: 'DELETED' } },
attributes: [[fn('sum', col('size')), 'total']],
raw: true,
});
Redis.getInstance();
const cachedUsage = await Redis.getUsage(user.uuid);
let driveUsage = 0;

const driveUsage = parseInt(usage[0].total);
if (cachedUsage) {
logger.info('Cache hit for user ' + user.uuid);
driveUsage = cachedUsage;
} else {
const usage = await Model.file.findAll({
where: { user_id: targetUser.id, status: { [Op.ne]: 'DELETED' } },
attributes: [[fn('sum', col('size')), 'total']],
raw: true,
});

driveUsage = parseInt(usage[0].total);

await Redis.setUsage(user.uuid, driveUsage);
}

const backupsQuery = await Model.backup.findAll({
where: { userId: targetUser.id },
Expand Down
18 changes: 18 additions & 0 deletions src/config/initializers/redis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,24 @@ export default class Redis {
return Redis.instance;
}

static async getUsage(userUuid: string): Promise<number | null> {
const r = Redis.instance;

const v = await r.get(`${userUuid}-usage`);

if (!v) {
return null;
}

return (JSON.parse(v) as { usage: number }).usage;
}

static async setUsage(userUuid: string, usage: number): Promise<void> {
const r = Redis.instance;

await r.set(`${userUuid}-usage`, JSON.stringify({ usage }), 'EX', 10*60);
}

static async releaseLock(key: string) {
const r = Redis.instance;

Expand Down

0 comments on commit dd9d38c

Please sign in to comment.