# Code coverage report for thinkjs/lib/Lib/Driver/Socket/MemcacheSocket.js

## Statements: 100% (131 / 131) Branches: 100% (58 / 58) Functions: 100% (29 / 29) Lines: 100% (131 / 131) Ignored: none

All files » thinkjs/lib/Lib/Driver/Socket/ » MemcacheSocket.js

    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
    2811
    1

    1
    1
    1
    1

    1

    19
    19
    18

    1

    1

    1

    28
    28
    28
    28
    28
    28

    32
    14

    18
    18
    18
    18
    18
    18
    18
    18

    18
    16
    16

    18
    3
    2
    2
    1

    3

    18
    3
    3

    18
    3
    2
    2
    1

    3

    18
    3
    2
    2
    1

    3
    3

    18
    18

    19
    19
    19
    2

    17
    17
    17
    17
    1

    16
    16
    16
    15

    20
    3

    17
    63
    63
    2

    15
    15
    14

    1

    4
    4

    7
    7
    7
    7
    7
    1
    6
    3
    3
    3
    3
    3

    3
    3
    3
    3

    15
    15

    2

    2
    2

    16
    16
    16
    16
    16

    16
    16
    16

    16

    3

    7
    7
    7
    7
    7

    1

    1

    2
    2

    2
    2

    4
    3
    3

    1
    1
    5
    5

    1
     var net = require('net');
    var EventEmitter = require('events').EventEmitter;

    var CRLF = '\r\n'; //换行符
    var CRLF_LENGTH = CRLF.length;
    var ERRORS = ['ERROR', 'NOT_FOUND', 'CLIENT_ERROR', 'SERVER_ERROR']; //错误
    var ERRORS_LENGTH = ERRORS.length;

    //读取一行数据
    function readLine(string){
      'use strict';
      var pos = string.indexOf(CRLF);
      if (pos > -1) {
        return string.substr(0, pos);
      }
      return string;
    }
    /**
     * memcache类
     * @return {[type]} [description]
     */
    module.exports = Class(function(){
      'use strict';
      return {
        init: function(port, hostname){
          EventEmitter.call(this);
          this.port = port || 11211;
          this.hostname = hostname || 'localhost';
          this.buffer = '';
          this.callbacks = []; //回调函数
          this.handle = null; //socket连接句柄
        },
        /**
         * 建立连接
         * @return {[type]} [description]
         */
        connect: function(){
          if (this.handle) {
            return this;
          }
          var self = this;
          var deferred = getDefer();
          this.handle = net.createConnection(this.port, this.host);
          this.handle.on('connect', function(){
            this.setTimeout(0);
            this.setNoDelay();
            self.emit('connect');
            deferred.resolve();
          });
          this.handle.on('data', function(data){
            self.buffer += data.toString();
            self.handleData();
          });
          this.handle.on('end', function(){
            while(self.callbacks.length > 0){
              var callback = self.callbacks.shift();
              if (callback && callback.callback) {
                callback.callback('CONNECTION_CLOSED');
              }
            }
            self.handle = null;
          });
          this.handle.on('close', function(){
            self.handle = null;
            self.emit('close');
          });
          this.handle.on('timeout', function(){
            if (self.callbacks.length > 0) {
              var callback = self.callbacks.shift();
              if (callback && callback.callback) {
                callback.callback('TIMEOUT');
              }
            }
            self.emit('timeout');
          });
          this.handle.on('error', function(error){
            while(self.callbacks.length > 0){
              var callback = self.callbacks.shift();
              if (callback && callback.callback) {
                callback.callback('ERROR');
              }
            }
            self.handle = null;
            self.emit('clienterror', error);
          });
          this.promise = deferred.promise;
          return this;
        },
        /**
         * 处理接收的数据
         * @return {[type]} [description]
         */
        handleData: function(){
          while(this.buffer.length > 0){
            var result = this.getHandleResult(this.buffer);
            if(result === false){
              break;
            }
            var value = result[0];
            var pos = result[1];
            var error = result[2];
            if (pos > this.buffer.length) {
              break;
            }
            this.buffer = this.buffer.substring(pos);
            var callback = this.callbacks.shift();
            if (callback && callback.callback) {
              callback.callback(error, value);
            }
          }
        },
        getHandleResult: function(buffer){
          if (buffer.indexOf(CRLF) === -1) {
            return false;
          }
          for(var i = 0; i < ERRORS_LENGTH; i++){
            var item = ERRORS[i];
            if (buffer.indexOf(item) > -1) {
              return this.handleError(buffer);
            }
          }
          var callback = this.callbacks[0];
          if (callback && callback.type) {
            return this['handle' + ucfirst(callback.type)](buffer);
          }
          return false;
        },
        /**
         * 处理错误
         * @param  {[type]} buffer [description]
         * @return {[type]}        [description]
         */
        handleError: function(buffer){
          var line = readLine(buffer);
          return [null, line.length + CRLF_LENGTH, line];
        },
        /**
         * 处理获取数据
         * @param  {[type]} buffer [description]
         * @return {[type]}        [description]
         */
        handleGet: function(buffer){
          var value = null;
          var end = 3;
          var resultLen = 0;
          var firstPos;
          if (buffer.indexOf('END') === 0) {
            return [value, end + CRLF_LENGTH];
          }else if (buffer.indexOf('VALUE') === 0 && buffer.indexOf('END') > -1) {
            firstPos = buffer.indexOf(CRLF) + CRLF_LENGTH;
            var endPos = buffer.indexOf('END');
            resultLen = endPos - firstPos - CRLF_LENGTH;
            value = buffer.substr(firstPos, resultLen);
            return [value, firstPos + parseInt(resultLen, 10) + CRLF_LENGTH + end + CRLF_LENGTH];
          }else{
            firstPos = buffer.indexOf(CRLF) + CRLF_LENGTH;
            resultLen = buffer.substr(0, firstPos).split(' ')[3];
            value = buffer.substr(firstPos, resultLen);
            return [value, firstPos + parseInt(resultLen) + CRLF_LENGTH + end + CRLF_LENGTH];
          }
        },
        /**
         * 处理简单数据
         * @param  {[type]} buffer [description]
         * @return {[type]}        [description]
         */
        handleSimple: function(buffer){
          var line = readLine(buffer);
          return [line, line.length + CRLF_LENGTH, null];
        },
        /**
         * 版本号
         * @param  {[type]} buffer [description]
         * @return {[type]}        [description]
         */
        handleVersion: function(buffer){
          var pos = buffer.indexOf(CRLF);
          //8 is length of 'VERSION '
          var value = buffer.substr(8, pos - 8);
          return [value, pos + CRLF_LENGTH, null];
        },
        /**
         * 查询
         * @param  {[type]}   query    [description]
         * @param  {[type]}   type     [description]
         * @param  {Function} callback [description]
         * @return {[type]}            [description]
         */
        query: function(query, type){
          this.connect();
          var self = this;
          var deferred = getDefer();
          var callback = function(error, value){
            return error ? deferred.reject(error) : deferred.resolve(value);
          }
          this.promise.then(function(){
            self.callbacks.push({type: type, callback: callback});
            self.handle.write(query + CRLF);
          });
          return deferred.promise;
        },
        /**
         * 获取
         * @param  {[type]}   key      [description]
         * @param  {Function} callback [description]
         * @return {[type]}            [description]
         */
        get: function(key){
          return this.query('get ' + key, 'get');
        },
        /**
         * 存储
         * @return {[type]} [description]
         */
        store: function(key, value, type, lifetime, flags){
          lifetime = lifetime || 0;
          flags = flags || 0;
          var length  = Buffer.byteLength(value.toString());
          var query = [type, key, flags, lifetime, length].join(' ') + CRLF + value;
          return this.query(query, 'simple');
        },
        /**
         * 删除
         * @param  {[type]}   key      [description]
         * @param  {Function} callback [description]
         * @return {[type]}            [description]
         */
        delete: function(key){
          return this.query('delete ' + key, 'simple');
        },
        /**
         * 获取版本号
         * @param  {Function} callback [description]
         * @return {[type]}            [description]
         */
        version: function(){
          return this.query('version', 'version');
        },
        /**
         * 增长
         * @param  {[type]}   key      [description]
         * @param  {[type]}   step     [description]
         * @param  {Function} callback [description]
         * @return {[type]}            [description]
         */
        increment: function(key, step){
          step = step || 1;
          return this.query('incr ' + key + ' ' + step, 'simple');
        },
        /**
         * 减少
         * @param  {[type]}   key      [description]
         * @param  {[type]}   step     [description]
         * @param  {Function} callback [description]
         * @return {[type]}            [description]
         */
        decrement: function(key, step){
          step = step || 1;
          return this.query('decr ' + key + ' ' + step, 'simple');
        },
        /**
         * 关闭
         * @return {[type]} [description]
         */
        close: function(){
          if (this.handle && this.handle.readyState === 'open') {
            this.handle.end();
            this.handle = null;
          }
        }
      }
    }, EventEmitter).extend(function(){
      'use strict';
      var result = {};
      ['set', 'add', 'replace', 'append', 'prepend'].forEach(function(item){
        result[item] = function(key, value, lifetime, flags){
          return this.store(key, value, 'set', lifetime, flags);
        }
      });
      return result;
    });