All files / lib LightSwitch.ts

35.89% Statements 56/156
16.21% Branches 6/37
30.43% Functions 7/23
36.6% Lines 56/153

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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 3291x                               1x 1x           1x   1x   1x   1x 1x 1x 1x 1x     1x 1x       5x 1x   5x     1x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x     3x       3x   3x   3x       3x       3x 3x 3x 3x     3x   3x   1x   1x   1x   1x                                                                                                                                     2x     2x                                                                                 1x                       3x     3x 2x     1x 1x       1x         1x 1x 1x           1x                                                                                                                                                                         1x  
import {
  SdkConfig,
  LogLevel,
  ApiResponse,
  Flag,
  ErrorCallback,
  userKey,
  LSMessage,
  ILSUser,
  Title,
  flagChangedCallback,
  Switch,
  Flags,
  Property,
  ILightSwitch,
} from './types';
import { LSLogger } from './LSLogger';
import {
  getRequest,
  postRequest,
  getHashedPercentageForObjectIds,
  compareObjectsAndMaps,
} from './utils';
import ReconnectingEventSource from 'reconnecting-eventsource';
import LSUser from './LSUser';
import { LSFlagNotFoundError, LSServerError, LSTypeCastError } from './error';
 
const logger = LSLogger(LogLevel.DEBUG);
 
const FLAG_NOT_FOUND = 1000;
const VARIATION_NOT_FOUND = 1001;
const MEMBER_NOT_FOUND = 2000;
const SDK_KEY_ALREADY_EXISTS = 3000;
const SDK_KEY_NOT_FOUND = 3001;
 
class LightSwitch implements ILightSwitch {
  private static instance: LightSwitch | null = null;
  public static isInitialized = false;
  private constructor() {}
 
  public static getInstance(): LightSwitch {
    if (!LightSwitch.instance) {
      LightSwitch.instance = new LightSwitch();
    }
    return LightSwitch.instance;
  }
 
  private sdkKey = '';
  private logLevel = LogLevel.DEBUG; // 로그 레벨
  // private lastUpdated = ''; // feature flag 데이터 갱신 날짜
  private flags: Flags = new Map<string, Flag>();
  private onError: null | ErrorCallback = null;
  private eventSource: null | ReconnectingEventSource = null;
  private onFlagChanged: null | flagChangedCallback = null;
  private userKey = '';
  private reconnectTime = 3000;
 
  SERVER_URL = 'http://localhost:8000';
  INIT_REQUEST_PATH = this.SERVER_URL + '/api/v1/sdk/init';
  SSE_CONNECT_PATH = this.SERVER_URL + '/api/v1/sse/subscribe';
 
  public async init(config: SdkConfig): Promise<void> {
    Iif (LightSwitch.instance != null && LightSwitch.isInitialized) {
      logger.info('lightswitch is already initialized, skip init process');
      return;
    }
    const { sdkKey, onError, onFlagChanged, reconnectTime, endpoint } = config;
 
    this.sdkKey = sdkKey;
 
    Iif (reconnectTime) {
      this.reconnectTime = reconnectTime;
    }
 
    Iif (onError) {
      this.onError = onError;
    }
 
    if (endpoint) {
      this.SERVER_URL = endpoint;
      this.INIT_REQUEST_PATH = this.SERVER_URL + '/api/v1/sdk/init';
      this.SSE_CONNECT_PATH = this.SERVER_URL + '/api/v1/sse/subscribe';
    }
 
    this.onFlagChanged = onFlagChanged;
 
    await this.getInitData();
 
    logger.debug('success to getInitData');
 
    await this.getUserKey();
 
    logger.debug('success to getUserKey, start connecting SSE');
 
    this.eventSource = this.getEventSource(this.userKey, this.reconnectTime);
    this.addSseListener();
    LightSwitch.isInitialized = true;
    // logger.info('success to initialize client sdk');
  }
  private getVariationValue<T>(flag: Flag, LSUser: ILSUser): any {
    let percentage = getHashedPercentageForObjectIds([LSUser.getUserId(), flag.title], 1);
    logger.info(percentage);
    Iif (flag.variations) {
      for (let i = 0; i < flag.variations.length; i++) {
        const variation = flag.variations[i];
        percentage -= variation.portion;
        logger.info(`percentage : ${percentage}, portion : ${variation.portion}`);
        Iif (percentage < 0) {
          // logger.info(`value : ${variation.value}`);
          return variation.value as T;
        }
      }
    }
    return flag.defaultValue as T;
  }
  private getTypedValue<T>(flag: Flag, value: string) {
    if (flag.type == 'STRING') {
      return value as T;
    } else if (flag.type == 'BOOLEAN') {
      if (value == 'TRUE') return true as T;
      else return false as T;
    } else Iif (flag.type == 'INTEGER') {
      return parseInt(value) as T;
    }
  }
  public getFlag<T>(name: string, LSUser: ILSUser, defaultVal: T): T {
    const flag = this.flags.get(name);
    Iif (!flag) {
      logger.warning(`${name} 플래그가 존재하지 않습니다. 기본값을 이용합니다.`);
      return defaultVal;
    }
 
    if (!flag.active) {
      logger.info(
        `id : ${flag?.flagId} title : ${flag?.title} 플래그가 활성화 되어있지 않습니다. 기본값을 이용합니다.`,
      );
      return this.getTypedValue(flag, flag.defaultValue) as T;
    } else {
      Iif (flag.keywords.length > 0 && LSUser.properties?.size > 0) {
        logger.info(
          `id : ${flag?.flagId} title : ${flag.title} 플래그가 활성화 되어 있습니다. 키워드를 확인합니다.`,
        );
        for (let i = 0; i < flag.keywords.length; i++) {
          const keyword = flag.keywords[i];
          const isEqual = compareObjectsAndMaps(keyword.properties, LSUser.properties);
          if (isEqual) {
            return this.getTypedValue(flag, keyword.value) as T;
          } else {
            logger.info(`키워드 대상이 아닙니다. portion을 계산합니다.`);
          }
        }
      }
      logger.info(
        `id : ${flag?.flagId} title : ${flag.title} 플래그가 활성화 되어 있습니다. portion을 계산합니다.`,
      );
      const evaluatedValue = this.getVariationValue<T>(flag, LSUser);
      return this.getTypedValue(flag, evaluatedValue) as T;
    }
  }
 
  private handleError(error: Error) {
    Iif (this.onError) {
      this.onError(error);
    } else {
      throw error;
    }
  }
  public getBooleanFlag(name: string, LSUser: ILSUser, defaultVal: boolean): boolean {
    const booleanFlag = this.getFlag<boolean>(name, LSUser, defaultVal);
    Iif (typeof booleanFlag != 'boolean') {
      this.handleError(
        new LSTypeCastError(
          `${name} 플래그를 BOOLEAN 타입으로 캐스팅하는데 실패했습니다.`,
        ),
      );
    }
    return booleanFlag;
  }
  public getIntegerFlag(name: string, LSUser: ILSUser, defaultVal: number): number {
    const integerFlag = this.getFlag<number>(name, LSUser, defaultVal);
    Iif (typeof integerFlag != 'number') {
      this.handleError(
        new LSTypeCastError(
          `${name} 플래그를 INTEGER 타입으로 캐스팅하는데 실패했습니다.`,
        ),
      );
    }
    return integerFlag;
  }
  public getStringFlag(name: string, LSUser: ILSUser, defaultVal: string): string {
    const stringFlag = this.getFlag<string>(name, LSUser, defaultVal);
    Iif (typeof stringFlag != 'string') {
      this.handleError(
        new LSTypeCastError(
          `${name} 플래그를 STRING 타입으로 캐스팅하는데 실패했습니다.`,
        ),
      );
    }
    return stringFlag;
  }
 
  private getEventSource(
    userKey: string,
    reconnectTime: number,
  ): ReconnectingEventSource {
    return new ReconnectingEventSource(this.SSE_CONNECT_PATH + '/' + userKey, {
      // indicating if CORS should be set to include credentials, default `false`
      withCredentials: true,
      // the maximum time to wait before attempting to reconnect in ms, default `3000`
      // note: wait time is randomised to prevent all clients from attempting to reconnect simultaneously
      max_retry_time: reconnectTime,
      // underlying EventSource class, default `EventSource`
      eventSourceClass: EventSource,
    });
  }
 
  private async getInitData(): Promise<void> {
    const response: ApiResponse<Flag[]> = await postRequest(this.INIT_REQUEST_PATH, {
      sdkKey: this.sdkKey,
    });
    if (response?.code == SDK_KEY_NOT_FOUND) {
      this.handleError(new LSServerError(response.message));
    }
 
    const newFlags: Flag[] = response?.data;
    newFlags.forEach((flag) => {
      this.flags.set(flag.title, flag);
    });
 
    this.onFlagChanged?.();
 
    // logger.info(`receive init data : ${JSON.stringify(response)}`);
  }
  private async getUserKey(): Promise<void> {
    try {
      logger.info(this.sdkKey);
      const response: ApiResponse<userKey> = await postRequest(
        `${this.SSE_CONNECT_PATH}`,
        {
          sdkKey: this.sdkKey,
        },
      );
      this.userKey = response.data.userKey;
      // logger.info(`receive userKey data : ${JSON.stringify(response)}`);
    } catch (error) {
      Iif (error instanceof Error) {
        this.handleError(new LSServerError(error.message));
      }
    }
  }
 
  public getAllFlags(): Flags {
    return this.flags;
  }
 
  private addSseListener(): void {
    this.eventSource?.addEventListener('sse', (event: MessageEvent) => {
      Iif (event.data === 'SSE connected') {
        return;
      }
      const data: LSMessage = JSON.parse(event.data);
      logger.info(data.type);
      switch (data.type) {
        case 'CREATE':
          const createData = data.data as Flag;
          this.addFlag(createData);
          break;
        case 'UPDATE':
          const updateData = data.data as Flag;
          this.updateFlag(updateData);
          break;
        case 'DELETE':
          const deleteData = data.data as Title;
          this.deleteFlag(deleteData);
          break;
        case 'SWITCH': // not used
          const switchData = data.data as Switch;
          this.switchFlag(switchData);
          break;
      }
 
      this.flags.forEach((f) => {
        logger.info(`updated flag : ${JSON.stringify(f)}`);
      });
 
      this.onFlagChanged?.();
    });
  }
 
  private addFlag(flag: Flag): void {
    logger.info('addFlag call');
 
    this.flags.set(flag.title, flag);
  }
 
  private updateFlag(newFlag: Flag): void {
    logger.info('updateFlag call');
 
    this.flags.delete(newFlag.title);
    this.flags.set(newFlag.title, newFlag);
  }
 
  private deleteFlag(title: Title): void {
    logger.info('deleteFlag call');
    this.flags.delete(title.title);
  }
 
  private switchFlag(sw: Switch): void {
    logger.info('switchFlag call');
 
    const flag = this.flags.get(sw.title);
    const newFlag = JSON.parse(JSON.stringify(flag));
    newFlag.active = sw.active;
    this.flags.set(sw.title, newFlag);
    logger.info(newFlag);
  }
 
  public destroy(): void {
    Iif (!LightSwitch.isInitialized) {
      throw new Error('LightSwitch is not initialized.');
    }
    this.eventSource?.close();
    LightSwitch.isInitialized = false;
    logger.debug('call destroy');
  }
}
 
export default LightSwitch;