fox-send/server/storage/index.js

77 lines
1.9 KiB
JavaScript
Raw Normal View History

2018-02-06 22:31:18 +00:00
const config = require('../config');
const Metadata = require('../metadata');
const mozlog = require('../log');
const createRedisClient = require('./redis');
class DB {
constructor(config) {
2018-08-09 21:49:52 +00:00
const Storage = config.s3_bucket ? require('./s3') : require('./fs');
2018-02-06 22:31:18 +00:00
this.log = mozlog('send.storage');
2018-08-08 18:07:09 +00:00
2018-08-09 21:49:52 +00:00
this.storage = new Storage(config, this.log);
2018-08-08 18:07:09 +00:00
2018-02-06 22:31:18 +00:00
this.redis = createRedisClient(config);
this.redis.on('error', err => {
this.log.error('Redis:', err);
});
}
async ttl(id) {
const result = await this.redis.ttlAsync(id);
return Math.ceil(result) * 1000;
}
2018-08-09 21:49:52 +00:00
async getPrefixedId(id) {
const prefix = await this.redis.hgetAsync(id, 'prefix');
return `${prefix}-${id}`;
2018-02-06 22:31:18 +00:00
}
2018-08-08 18:07:09 +00:00
async length(id) {
2018-08-09 21:49:52 +00:00
const filePath = await this.getPrefixedId(id);
return this.storage.length(filePath);
2018-02-06 22:31:18 +00:00
}
2018-08-08 18:07:09 +00:00
async get(id) {
2018-08-09 21:49:52 +00:00
const filePath = await this.getPrefixedId(id);
return this.storage.getStream(filePath);
2018-08-08 18:07:09 +00:00
}
async set(id, file, meta, expireSeconds = config.default_expire_seconds) {
2018-08-09 21:49:52 +00:00
const expireTimes = config.expire_times_seconds;
let i;
for (i = 0; i < expireTimes.length - 1; i++) {
if (expireSeconds <= expireTimes[i]) {
2018-08-08 18:07:09 +00:00
break;
}
}
2018-08-09 21:49:52 +00:00
const prefix = config.expire_prefixes[i];
const filePath = `${prefix}-${id}`;
await this.storage.set(filePath, file);
this.redis.hset(id, 'prefix', prefix);
2018-02-06 22:31:18 +00:00
this.redis.hmset(id, meta);
2018-08-08 18:07:09 +00:00
this.redis.expire(id, expireSeconds);
2018-02-06 22:31:18 +00:00
}
setField(id, key, value) {
this.redis.hset(id, key, value);
}
2018-08-08 18:07:09 +00:00
async del(id) {
2018-08-09 21:49:52 +00:00
const filePath = await this.getPrefixedId(id);
this.storage.del(filePath);
2018-02-06 22:31:18 +00:00
this.redis.del(id);
}
async ping() {
await this.redis.pingAsync();
2018-08-09 21:49:52 +00:00
await this.storage.ping();
2018-02-06 22:31:18 +00:00
}
async metadata(id) {
const result = await this.redis.hgetallAsync(id);
return result && new Metadata(result);
}
}
module.exports = new DB(config);