index.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. const config = require('../config');
  2. const Metadata = require('../metadata');
  3. const mozlog = require('../log');
  4. const createRedisClient = require('./redis');
  5. function getPrefix(seconds) {
  6. return Math.max(Math.floor(seconds / 86400), 1);
  7. }
  8. class DB {
  9. constructor(config) {
  10. let Storage = null;
  11. if (config.s3_bucket) {
  12. Storage = require('./s3');
  13. } else if (config.gcs_bucket) {
  14. Storage = require('./gcs');
  15. } else {
  16. Storage = require('./fs');
  17. }
  18. this.log = mozlog('send.storage');
  19. this.storage = new Storage(config, this.log);
  20. this.redis = createRedisClient(config);
  21. this.redis.on('error', err => {
  22. this.log.error('Redis:', err);
  23. });
  24. }
  25. async ttl(id) {
  26. const result = await this.redis.ttlAsync(id);
  27. return Math.ceil(result) * 1000;
  28. }
  29. async getPrefixedId(id) {
  30. const prefix = await this.redis.hgetAsync(id, 'prefix');
  31. return `${prefix}-${id}`;
  32. }
  33. async length(id) {
  34. const filePath = await this.getPrefixedId(id);
  35. return this.storage.length(filePath);
  36. }
  37. async get(id) {
  38. const filePath = await this.getPrefixedId(id);
  39. return this.storage.getStream(filePath);
  40. }
  41. async set(id, file, meta, expireSeconds = config.default_expire_seconds) {
  42. const prefix = getPrefix(expireSeconds);
  43. const filePath = `${prefix}-${id}`;
  44. await this.storage.set(filePath, file);
  45. this.redis.hset(id, 'prefix', prefix);
  46. if (meta) {
  47. this.redis.hmset(id, meta);
  48. }
  49. this.redis.expire(id, expireSeconds);
  50. }
  51. setField(id, key, value) {
  52. this.redis.hset(id, key, value);
  53. }
  54. incrementField(id, key, increment = 1) {
  55. this.redis.hincrby(id, key, increment);
  56. }
  57. async del(id) {
  58. const filePath = await this.getPrefixedId(id);
  59. this.storage.del(filePath);
  60. this.redis.del(id);
  61. }
  62. async ping() {
  63. await this.redis.pingAsync();
  64. await this.storage.ping();
  65. }
  66. async metadata(id) {
  67. const result = await this.redis.hgetallAsync(id);
  68. return result && new Metadata(result);
  69. }
  70. }
  71. module.exports = new DB(config);