All files / mod/config redisDelegate.ts

91.67% Statements 22/24
100% Branches 2/2
85.71% Functions 6/7
91.3% Lines 21/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65        1x 1x         1x 9x   9x 9x                 9x 4x       6x 5x 5x   6x     7x                     7x 7x           13x 9x   4x     3x 3x 3x      
import { Redis } from "ioredis";
import { ConfigValue, DefinedDynamicMap, DynamicGetterDelegate } from "./config";
import { EventEmitter } from "events";
 
const CONFIG_CHANGE_EVENT = "CONFIG_CHANGE";
const CONFIG_PREFIX = "config::";
 
/**
 * A DynamicConfig Delegate that uses redis to store config data
 */
export default class RedisConfigDelegate implements DynamicGetterDelegate {
  cache: { [key: string]: ConfigValue } = {};
 
  constructor(private redis: Redis, private event: EventEmitter) {
    this.redis.defineCommand("versionUpdate", {
      numberOfKeys: 2,
      lua: `
      local version = redis.call('get', KEYS[1]) or "0"
      if (tonumber(ARGV[1]) > tonumber(version)) then
        redis.call('mset', KEYS[1], ARGV[1], KEYS[2], ARGV[2])
      end
      `,
    });
    event.on(CONFIG_CHANGE_EVENT, ev => {
      this.cache[ev.name] = ev.value;
    });
  }
  async init(definedDynamics: DefinedDynamicMap): Promise<void> {
    for (const key of Object.keys(definedDynamics)) {
      const definedDynamic = definedDynamics[key];
      await this.onDefine(definedDynamic.version, key, definedDynamic.defaultValue);
    }
    return;
  }
  async onDefine(version: number, name: string, defaultValue: ConfigValue) {
    await this.redis
      // @ts-ignore
      .versionUpdate(
        `${CONFIG_PREFIX}${name}_version`,
        `${CONFIG_PREFIX}${name}`,
        version,
        JSON.stringify(defaultValue),
      )
      .catch(e => {
        console.warn("update dynamic config failed for key " + name + ", reason: ", e);
      });
    try {
      this.cache[name] = JSON.parse(await this.redis.get(`${CONFIG_PREFIX}${name}`));
    } catch (e) {
      console.warn("get dynamic config failed for key " + name + ", reason: ", e);
    }
  }
  get(name: string, defaultValue: ConfigValue): ConfigValue {
    if (typeof this.cache[name] !== "undefined") {
      return this.cache[name];
    }
    return defaultValue;
  }
  async set(name: string, value: ConfigValue) {
    this.cache[name] = value;
    this.event.emit(CONFIG_CHANGE_EVENT, { name, value });
    await this.redis.set(`${CONFIG_PREFIX}${name}`, JSON.stringify(value));
  }
}