All files / src/lua/call lua-redis.ts

76.71% Statements 112/146
58% Branches 29/50
90% Functions 9/10
75.88% Lines 107/141

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 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387  1x 1x   1x     1x 1x   1x   1x   34x 34x 34x 152x     34x       20x 20x 20x 20x 20x 17x 9x   8x     20x         20x           20x   2x 2x 2x 2x 2x 2x 4x 4x                                                     4x       4x 4x             4x 2x 2x   2x 2x           2x 2x       2x 2x           2x 2x 2x                   2x 2x         2x 2x 2x       2x       2x 2x 2x                   2x                       2x       2x     2x     2x           20x           20x 20x       20x             2x 2x 2x 2x 2x 4x       4x 4x 2x         2x           2x         2x         2x       2x       2x                   2x             2x     2x         20x         20x 20x           1x     40x 40x           40x 17x       17x           40x             14x           12x 12x 6x   6x         12x       12x                                         2x       2x                     2x       2x 2x         2x 12x       12x                
 
import Parser = require("redis-parser");
const fengari = require("fengari");
 
import { DefaultRequest } from "../../server/default-request";
import { IRequest } from "../../server/request";
import { IRespCommand } from "../../resp/command/resp-command";
import { Logger } from "../../logger";
import { RespSerialize } from "../../resp/protocol/resp-serialize";
 
const { lua } = fengari;
 
export default class LuaRedisLib {
    public static stringFrom(element: any[]): string {
        let elementValue: string = "";
        Eif (element) {
            element.forEach((c) => {
                elementValue += String.fromCharCode(c);
            });
        }
        return elementValue;
    }
 
    public static LoadLibrary(L: any, request: IRequest): void {
        this.logger.debug("Assembling lua redis library");
        const argv: string[] = [],
            keycount: string = request.getParam(1),
            keys: string[] = [];
        for (let index = 2; index < request.getParams().length; index++) {
            if (index > Number(keycount) + 1) {
                argv.push(request.getParam(index));
            } else {
                keys.push(request.getParam(index));
            }
        }
        this.createLuaTable(
            L,
            "ARGV",
            argv
        );
        this.createLuaTable(
            L,
            "KEYS",
            keys
        );
 
        const redis: any = {
            "call": () => {
                const n = lua.lua_gettop(L);
                const args : string[] = new Array(n - 1);
                let cmd: any = null;
                this.logger.debug(`CALL pushing ${n} args`);
                let returned: any = null;
                for (let i = 0; i < n; i++) {
                    let value: any = null;
                    switch (lua.lua_type(
                        L,
                        i + 1
                    )) {
                    case lua.LUA_TNIL:
                        this.logger.debug("RCALL: LUA_TNIL");
                        value = null;
                        break;
                    case lua.LUA_TNUMBER:
                        value = lua.lua_tonumber(
                            L,
                            i + 1
                        );
                        value = String(Number(parseInt(
                            value,
                            10
                        )));
                        this.logger.debug(`RCALL: LUA_TNUMBER: ${value}`);
                        break;
                    case lua.LUA_TBOOLEAN:
                        value = lua.lua_toboolean(
                            L,
                            i + 1
                        );
                        this.logger.debug(`RCALL: LUA_TBOOLEAN: ${value}`);
                        break;
                    case lua.LUA_TSTRING:
                        value = lua.lua_tojsstring(
                            L,
                            i + 1
                        );
                        this.logger.debug(`RCALL: LUA_TSTRING: ${value}`);
                        break;
                    case lua.LUA_TTABLE:
                    default:
                        this.logger.warn("Not prepared to readtable");
                        // Value = this.flua_readtable(L, i + 1);
                        break;
                    }
                    if (i === 0) {
                        cmd = value;
                        this.logger.debug(`pushjs setting cmd to ${cmd}`);
                    } else {
                        args[i - 1] = value;
                        this.logger.debug(
                            `pushjs setting arg[${i - 1}] to "%s"`,
                            value
                        );
                    }
                }
                this.logger.debug(`LUA starting call to ${cmd} (${args})`);
                this.logger.debug(
                    `RCALL redis with ${cmd} and %s`,
                    ...args
                );
                const execcommand: IRespCommand = request.getServerContext().getCommand(cmd),
                    rqst: IRequest = new DefaultRequest(
                        request.getServerContext(),
                        request.getSession(),
                        cmd,
                        args
                    );
                const response: any = execcommand.execSync(rqst);
                this.logger.debug(`Type of response is ${response.constructor.name}`);
                const parser: Parser = new Parser({
                    "returnBuffers": false,
                    "returnError": (err: any) => {
                        this.logger.warn(
                            "returnError: \"%j\"",
                            err
                        );
                        return err;
                    },
                    "returnReply": (result: any) => {
                        this.logger.debug(`Replying with: ${result}`);
                        returned = result;
                    },
                    // Force numbers from double precision to integer
                    "stringNumbers": true
                }),
                    serializedResponse: string = new RespSerialize(response).serialize();
                parser.execute(Buffer.from(serializedResponse));
                this.logger.debug(
                    "parsedReply is %s",
                    returned
                );
                this.logger.debug(
                    `LUA call returned ${returned}: %j`,
                    returned
                );
                Eif (returned) {
                    this.logger.debug(`return value is ${returned.constructor.name}`);
                    Iif (returned.constructor.name === "Number") {
                        this.logger.debug(`Adjusting Number (${returned}) to Integer`);
                        returned = String(parseInt(
                            String(returned),
                            10
                        ));
                    }
                } else {
                    this.logger.debug("return value is null or undefined");
                }
                Iif (Array.isArray(returned) && returned.length === 0) {
                    this.logger.debug("Pushing NIL into empty returned array");
                    returned.push(null);
                }
 
                /*
                 * If (Array.isArray(returned)) {
                 *   This.logger.debug(`Preserving returned value(s) %j`, returned);
                 *   Request.getResponses().push(returned);
                 * }
                 */
 
                this.pushany(
                    L,
                    returned
                );
                this.logger.debug(`returned.length is ${Array.isArray(returned)
                    ? returned.length
                    : 1}`);
                this.logger.debug(`Returning ${Array.isArray(returned)
                    ? returned.length
                    : 1}`);
                return String(Array.isArray(returned)
                    ? returned.length
                    : 1);
            }
        };
 
        lua.lua_createtable(
            L,
            0,
            Object.keys(redis).length
        );
        //    For (const key of Object.keys(redis)) {
        this.logger.debug("Registering redis lib function \"call\"");
        lua.lua_pushstring(
            L,
            "call"
        );
        lua.lua_pushjsfunction(
            L,
            (LIB: any) => {
                /*
                 * This is the entry point for redis.call()
                 * Which we call below with redis['call'].call(null, ...args);
                 */
                const n = lua.lua_gettop(LIB);
                const args = new Array(n),
                    stringArgs = new Array(n - 1);
                let cmd: string = "";
                for (let i = 0; i < n; i++) {
                    const value: any = lua.lua_tonumber(
                        LIB,
                        i + 1
                    );
                    args[i] = value;
                    if (i === 0) {
                        cmd = LuaRedisLib.stringFrom(lua.lua_tostring(
                            LIB,
                            i + 1
                        ));
                    } else {
                        stringArgs[i - 1] = LuaRedisLib.stringFrom(lua.lua_tostring(
                            LIB,
                            i + 1
                        ));
                    }
                }
                this.logger.debug(
                    `lua_pushjsfunction: REDIS calling '${cmd}' with %j`,
                    ...stringArgs
                );
 
                const callReturn: any = redis.call.call(
                    null,
                    ...args
                );
                // CallReturn is the number of arguments that were pushed to the stack by lua
                this.logger.debug(
                    `lua_pushjsfunction: REDIS "call" returned ${callReturn}: %j`,
                    callReturn
                );
                this.logger.debug(`lua_pushjsfunction: return value is ${callReturn
                    ? callReturn.constructor.name
                    : "not defined"}`);
 
                switch (true) {
                case callReturn && callReturn.constructor.name === "Number":
                    // CallReturn is the number of arguments that were pushed to the stack by lua
                    this.logger.debug(`lua_pushjsfunction: Pushing returned argument count ${callReturn} as number`);
                    lua.lua_pushnumber(
                        LIB,
                        callReturn
                    );
                    break;
                default:
                    this.logger.warn(
                        `Ignore:  Not pushing type "${callReturn
                            ? callReturn.constructor.name
                            : "null or undefined"} %j`,
                        callReturn
                    );
                }
                this.logger.debug(`lua_pushjsfunction: callReturn.length is ${Array.isArray(callReturn)
                    ? callReturn.length
                    : 1}`);
                return Array.isArray(callReturn)
                    ? callReturn.length
                    : 1;
            }
        );
        lua.lua_rawset(
            L,
            -3
        );
        //    }
        this.logger.debug("Setting \"redis\" global");
        lua.lua_setglobal(
            L,
            "redis"
        );
    }
 
    private static logger: Logger = new Logger(module.id);
 
    private static createLuaTable(L: any, tableName: string, tableArray: string[]) {
        this.logger.debug(`Creating ${tableName} table`);
        lua.lua_createtable(
            L,
            tableArray.length,
            0
        );
        // Reverse the value array
        for (let index = tableArray.length - 1; index > -1; index--) {
            lua.lua_pushstring(
                L,
                tableArray[index]
            );
            lua.lua_seti(
                L,
                -2,
                index + 1
            );
        }
        lua.lua_setglobal(
            L,
            fengari.to_luastring(tableName)
        );
    }
 
    private static pushany(L: any, element: any) {
        switch (true) {
        case !element || element === null:
            this.logger.debug("Push nil");
            lua.lua_pushnil(L);
            break;
        case element.constructor.name === "String":
            this.logger.debug(`Push string ${element}`);
            if (!isNaN(Number(element))) {
                this.logger.debug(`Converting ${element} to integer`);
                // eslint-disable-next-line no-param-reassign
                element = String(parseInt(
                    element,
                    10
                ));
            }
            lua.lua_pushstring(
                L,
                element
            );
            break;
        case element.constructor.name === "Number":
            // eslint-disable-next-line no-param-reassign
            element = String(parseInt(
                String(element),
                10
            ));
            this.logger.debug(`Push number: ${element} as string`);
            lua.lua_pushstring(
                L,
                element
            );
            break;
        case element.constructor.name === "Boolean":
            this.logger.debug(`Push boolean: ${element}`);
            lua.lua_pushboolean(
                L,
                element
            );
            break;
        case element.constructor.name === "Array":
            this.pushtable(
                L,
                element
            );
            break;
        default:
            this.logger.warn(
                `Not prepared to push type "${element.constructor.name}": %j`,
                element
            );
            throw new Error(`Not prepared to push type "${element.constructor.name}": ${element}`);
        }
    }
 
    private static pushtable(L: any, table: any[]) {
        this.logger.debug(
            "pushtable(L, %j)",
            ...table
        );
        this.logger.debug(`Table length is ${table.length}`);
        lua.lua_createtable(
            L,
            0,
            table.length
        );
        for (let counter = 0; counter < table.length; counter++) {
            this.pushany(
                L,
                table[counter]
            );
            lua.lua_rawseti(
                L,
                -2,
                counter + 1
            );
        }
    }
}