All files memcached.ts

79.11% Statements 125/158
87.32% Branches 62/71
79.69% Functions 51/64
76.12% Lines 102/134

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 329 330 331 332 333 334 335 336 337 338 3391x 1x                       1x                         1x               1x 53x   53x       53x 53x 53x   53x 53x 53x         53x     53x     53x       1x 46x 46x       1x 46x 46x     46x     1x 92x                 92x 92x 91x 91x 91x     1x           1x 92x 92x       1x       180x     90x     90x 90x 90x     1x                                                                                     1x 1x             1x 1x         1x     1x     1x   1x       1x     1x                   1x       1x       23x 46x       1x       10x 20x       1x         30x 60x 60x       1x         4x 8x 8x       1x         2x 4x 4x       1x         2x 4x 4x       1x         4x 8x 8x       1x           2x 4x 4x       1x 2x 4x       1x         4x 8x 8x       1x         4x 8x 8x       1x 2x 4x       1x 1x 2x     1x   1x       1x    
import { EventEmitter } from "events";
import {
  Connection,
  ConnectionConfig,
  ConnectionOptions,
  defaultConnectionOptions,
  Status,
  StoreOptions,
  RetrieveOptions,
} from "./connection";
import { Response, StatsResponse } from "./response";
import { Server } from "./server";
 
import { ConnectionError, ConnectionErrorCode } from "./error";
 
export interface MemcachedOptions {
  poolSize: number;
  initSize: number;
  removeDeadServer: boolean;
  timeout: number;
  wait: boolean;
  waitTimeout: number;
}
 
export type Options = Partial<MemcachedOptions & ConnectionOptions>;
 
const defaultOptions: Options = {
  ...defaultConnectionOptions,
  initSize: 1,
  poolSize: 10,
  wait: false,
  waitTimeout: 3000,
};
 
export class Memcached extends EventEmitter {
  private _connectionId = 0;
  private _connectionConfig: ConnectionConfig;
  private _connectionPool: Connection[] = [];
  private _options: Options;
 
  constructor(args: ConnectionConfig, options?: Options) {
    super();
    this._connectionConfig = args;
    this._options = { ...defaultOptions, ...options };
 
    for (let i = 0; i < this._options.initSize; i++) {
      const connectionOptions = options as ConnectionOptions;
      const connection = new Connection(
        args,
        ++this._connectionId,
        connectionOptions
      );
      connection.on("close", (connection: Connection) =>
        this.emit("close", connection)
      );
      connection.on("drop", (connection: Connection, server: Server) =>
        this.emit("drop", connection, server)
      );
      this._connectionPool.push(connection);
    }
  }
 
  public clean(): void {
    this._connectionPool.forEach((connection) => {
      connection.close(true);
    });
  }
 
  public async createPool(): Promise<void[]> {
    const connTry = this._connectionPool.map((connection: Connection) => {
      return connection.connect(Status.IDLE);
    });
 
    return await Promise.all(connTry);
  }
 
  public getConnection(): Connection {
    Iif (this._connectionPool.length === 0) {
      const connection = new Connection(
        this._connectionConfig,
        ++this._connectionId
      );
      this._connectionPool.push(connection);
      return connection;
    }
 
    const idleConnections = this._getIdleConnections();
    if (idleConnections.length > 0) {
      const connection = idleConnections[0];
      connection.status = Status.RESEARVED;
      return idleConnections[0];
    }
 
    throw new ConnectionError(
      "no connection available",
      ConnectionErrorCode.ER_CONN_NO_AVAILABLE
    );
  }
 
  private _getIdleConnections(): Array<Connection> {
    return this._connectionPool.filter((connection: Connection) => {
      return connection.isIdle();
    });
  }
 
  private async _cmd<T>(
    fn: (connection?: Connection) => Promise<T>
  ): Promise<T> {
    let connection: Connection;
    if (Ethis._options.wait) {
      connection = await this._getConnection();
    } else {
      connection = this.getConnection();
    }
 
    const resp = await fn(connection);
    connection.close();
    return resp;
  }
 
  private async _getConnection(): Promise<Connection> {
    try {
      return this.getConnection();
    } catch (err) {
      const connErr = err as ConnectionError;
      switch (connErr.code) {
        case ConnectionErrorCode.ER_CONN_NO_AVAILABLE:
          await new Promise((resolve, reject) => {
            this._connectionPool.forEach((conn: Connection) => {
              const timeout = setTimeout(() => {
                reject(
                  new ConnectionError(
                    "timout to get connection",
                    ConnectionErrorCode.ER_CONN_TIMEOUT
                  )
                );
              }, this._options.waitTimeout);
 
              conn.once("changeStatus", (id) => {
                const connection = this._connectionPool.find(
                  (conn: Connection) => {
                    return conn.id === id;
                  }
                );
 
                // this shouldn't happen
                if (!connection) {
                  throw err;
                }
 
                clearTimeout(timeout);
                connection.status = Status.RESEARVED;
                resolve(connection);
              });
            });
          });
          break;
      }
 
      throw connErr;
    }
  }
 
  public async createConnection(): Promise<Connection> {
    Iif (this._connectionPool.length >= this._options.poolSize) {
      throw new ConnectionError(
        "connection reached the pool size",
        ConnectionErrorCode.ER_CONN_MAX_CONNECTION
      );
    }
 
    const connectionOptions = this._options as ConnectionOptions;
    const connection = new Connection(
      this._connectionConfig,
      ++this._connectionId,
      connectionOptions
    );
    connection.on("close", (connection: Connection) =>
      this._handleClose(connection)
    );
    connection.on("drop", (connection: Connection, server: Server) =>
      this._handleDrop(connection, server)
    );
    this._connectionPool.push(connection);
 
    Iif (this._connectionPool.length === this._options.poolSize) {
      this.emit("maxConnection", this._options.poolSize);
    }
 
    return connection;
  }
 
  private _handleClose(removedConnection: Connection) {
    this._connectionPool = this._connectionPool.filter(
      (connection: Connection) => {
        return connection.id !== removedConnection.id;
      }
    );
 
    this.emit("close", removedConnection);
  }
 
  private _handleDrop(belongingConnection: Connection, server: Server) {
    this.emit("drop", belongingConnection, server);
  }
 
  public async get(
    keys: string | Array<string>,
    options?: RetrieveOptions
  ): Promise<Response> {
    return await this._cmd(
      async (connection: Connection) => await connection.get(keys, options)
    );
  }
 
  public async gets(
    keys: string | Array<string>,
    options?: RetrieveOptions
  ): Promise<Response> {
    return await this._cmd(
      async (connection: Connection) => await connection.gets(keys, options)
    );
  }
 
  public async set(
    key: string,
    value: string | Record<string, any>,
    options?: StoreOptions
  ): Promise<Response> {
    return await this._cmd(
      async (connection: Connection) =>
        await connection.set(key, value, options)
    );
  }
 
  public async add(
    key: string,
    value: string | Record<string, any>,
    options?: StoreOptions
  ): Promise<Response> {
    return await this._cmd(
      async (connection: Connection) =>
        await connection.add(key, value, options)
    );
  }
 
  public async append(
    key: string,
    value: string | Record<string, any>,
    options?: StoreOptions
  ): Promise<Response> {
    return await this._cmd(
      async (connection: Connection) =>
        await connection.append(key, value, options)
    );
  }
 
  public async prepend(
    key: string,
    value: string | Record<string, any>,
    options?: StoreOptions
  ): Promise<Response> {
    return await this._cmd(
      async (connection: Connection) =>
        await connection.prepend(key, value, options)
    );
  }
 
  public async replace(
    key: string,
    value: string | Record<string, any>,
    options?: StoreOptions
  ): Promise<Response> {
    return await this._cmd(
      async (connection: Connection) =>
        await connection.replace(key, value, options)
    );
  }
 
  public async cas(
    key: string,
    value: string | Record<string, any>,
    casId: number,
    options?: StoreOptions
  ): Promise<Response> {
    return await this._cmd(
      async (connection: Connection) =>
        await connection.cas(key, value, casId, options)
    );
  }
 
  public async delete(key: string): Promise<Response> {
    return await this._cmd(
      async (connection: Connection) => await connection.delete(key)
    );
  }
 
  public async gat(
    keys: string | Array<string>,
    expire: number,
    options?: RetrieveOptions
  ): Promise<Response> {
    return await this._cmd(
      async (connection: Connection) =>
        await connection.gat(keys, expire, options)
    );
  }
 
  public async gats(
    keys: string | Array<string>,
    expire: number,
    options?: RetrieveOptions
  ): Promise<Response> {
    return await this._cmd(
      async (connection: Connection) =>
        await connection.gats(keys, expire, options)
    );
  }
 
  public async touch(key: string, expires: number): Promise<Response> {
    return await this._cmd(
      async (connection: Connection) => await connection.touch(key, expires)
    );
  }
 
  public async stats(): Promise<StatsResponse> {
    return await this._cmd(
      async (connection: Connection) => await connection.stats()
    );
  }
}
 
export function createPool(
  args: ConnectionConfig,
  options?: MemcachedOptions
): Memcached {
  return new Memcached(args, options);
}