UNPKG

@ultipa-graph/ultipa-node-sdk

Version:

NodeJS SDK for ultipa-server 4.0

835 lines 39.9 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ConnectionBase = exports.RAFT_GLOBAL = void 0; const grpc = __importStar(require("@grpc/grpc-js")); const md5_1 = __importDefault(require("md5")); const types_1 = require("../../types"); const moment_timezone_1 = __importDefault(require("moment-timezone")); const ultipa_pb_1 = require("../../proto/ultipa_pb"); const utils_1 = require("../../utils"); const lodash_1 = __importDefault(require("lodash")); const network_manager_1 = require("../network.manager"); const timezone_1 = require("../../utils/timezone"); const chalk_1 = __importDefault(require("chalk")); let { CommandList } = utils_1.UQLMAKER; let ClientType = types_1.ULTIPA.ClientType; let ClientCache = {}; class GrpcClientInfo { constructor(host, username, password, crt) { this.host = host; this.username = username; this.password = password; this.host = host; this.crt = crt; } getMetadata(graphSetName, clusterId, timeZone, timeZoneOffset) { let metadata = new grpc.Metadata(); metadata.add("user", this.username); metadata.add("password", this.password); metadata.add("graph_name", graphSetName); let tzObj = (0, timezone_1.rpc_timezone)(timeZone, timeZoneOffset); for (const key in tzObj) { metadata.add(key, tzObj[key]); } if (!!clusterId) { metadata.add("ns_cluster_id", clusterId); } return metadata; } getClient() { return network_manager_1.grpcNetworkManager.getUltipaRpcsClient(this.host, this.crt); } } exports.RAFT_GLOBAL = "global"; class HostManagerControl { constructor(initHost, username, password, crt, consistency) { this.initHost = initHost; this.username = username; this.password = password; this.consistency = consistency; this.crt = crt; this.allHostManager = {}; } chooseClientInfo(params) { let { graphSetName } = params, others = __rest(params, ["graphSetName"]); let hostManager = this.getHostManger(graphSetName); return hostManager.chooseClientInfo(Object.assign(Object.assign({}, others), { consistency: this.consistency })); } upsetHostManger(graphSetName, initHost) { let hostManager = new HostManager(graphSetName, initHost, this.username, this.password, this.crt); this.allHostManager[graphSetName] = hostManager; return hostManager; } getHostManger(graphSetName) { let hostManager = this.allHostManager[graphSetName]; if (!hostManager) { hostManager = this.upsetHostManger(graphSetName, this.initHost); } return hostManager; } getAllHosts() { let hostManager = this.getHostManger(exports.RAFT_GLOBAL); return hostManager.getAllHosts(); } closeAll() { Object.values(this.allHostManager).forEach(hm => { hm.closeAll(); }); } } class HostManager { constructor(graphSetName, host, username, password, crt) { this.graphSetName = graphSetName; this.username = username; this.password = password; this.crt = crt; this.leaderHost = host; this.nullClientInfos = this.createClientInfo("0.0.0.0"); this.defaultClientInfo = this.createClientInfo(host); } createClientInfo(host) { if (this.leaderClientInfo && this.leaderClientInfo.host == host) { return this.leaderClientInfo; } if (this.defaultClientInfo && this.defaultClientInfo.host == host) { return this.defaultClientInfo; } return new GrpcClientInfo(host, this.username, this.password, this.crt); } getAllHosts() { let hosts = [ this.leaderHost, ...(this.followersPeerInfos || []).map((n) => n.host), ]; return hosts; } chooseClientInfo(params) { return this._chooseClientInfo(params) || this.nullClientInfos; } _chooseClientInfo(params) { if (params.useHost) { return this.getAllClientInfos({ needUnset: true }).find((c) => c.host == params.useHost); } if (params.useMaster) { return this.leaderClientInfo || this.defaultClientInfo; } // 三个原则:写发给leader、算法发给follower,读三个节点负载均衡 let { type, uql, consistency } = params; type = type || ClientType.Default; if (!type && uql) { // 如果没有type,并且有uql,自动判断 let uqlParse = new utils_1.EasyUqlParse(uql); if (uqlParse.hasExecTask()) { type = ClientType.Algo; } else if (uqlParse.hasWrite()) { type = ClientType.Update; } else if (uqlParse.forceUseMaster()) { type = ClientType.Leader; } } if (type == ClientType.Algo) { return lodash_1.default.sample(this.algoClientInfos); } if (type == ClientType.Update || type == ClientType.Leader || consistency) { return this.leaderClientInfo || this.defaultClientInfo; } // 负载聚恒,随机取除算法外的的clientInfo中的其中一个 return lodash_1.default.sample(this.getAllClientInfos({ ignoreAlgo: true })); } getAllClientInfos(p) { let all = [this.defaultClientInfo]; if (this.leaderClientInfo && this.leaderClientInfo.host !== this.defaultClientInfo.host) { all.push(this.leaderClientInfo); } if (!(p === null || p === void 0 ? void 0 : p.ignoreAlgo)) { all.push(...(this.algoClientInfos || [])); } all.push(...(this.otherFollowerClientInfos || [])); if (p === null || p === void 0 ? void 0 : p.needUnset) { all.push(...(this.otherUnsetFollowerClientInfos || [])); } return all; } closeAll() { this.getAllClientInfos().forEach(c => { c.getClient().close(); }); } setClients(leaderHost, followersPeerInfos) { // 创建leaderClientInfo this.leaderHost = leaderHost; // 如果和default一致,直接使用default的clientInfo this.leaderClientInfo = this.createClientInfo(leaderHost); this.followersPeerInfos = followersPeerInfos; this.otherFollowerClientInfos = []; this.otherUnsetFollowerClientInfos = []; this.algoClientInfos = []; if (followersPeerInfos && followersPeerInfos.length > 0) { for (const info of followersPeerInfos) { let host = info.host; if (info.isAlgoExecutable) { this.algoClientInfos.push(this.createClientInfo(host)); } if (info.isFollowerReadable) { this.otherFollowerClientInfos.push(this.createClientInfo(host)); } if (info.isUnset) { this.otherUnsetFollowerClientInfos.push(this.createClientInfo(host)); } } } else { // 如果没有follower,则是单机模式使用leader做为算法节点 this.algoClientInfos = [this.leaderClientInfo]; } } } class ConnectionBase { constructor(host, username, password, crt, defaultConfig, isMd5) { if (!isMd5) { password = (0, md5_1.default)(password).toUpperCase(); } this.username = username; this.password = password; this.crt = crt; this.setDefaultConfig(defaultConfig); this.hostManagerControl = new HostManagerControl(host, username, password, crt, defaultConfig === null || defaultConfig === void 0 ? void 0 : defaultConfig.consistency); } setDefaultConfig(config) { if (!this.defaultConfig) { // set default this.defaultConfig = { graphSetName: "default", timeout: 15, responseWithRequestInfo: false, }; } if (config === null || config === void 0 ? void 0 : config.useHost) { this.defaultConfig.useHost = config === null || config === void 0 ? void 0 : config.useHost; } if (config === null || config === void 0 ? void 0 : config.graphSetName) { this.defaultConfig.graphSetName = config === null || config === void 0 ? void 0 : config.graphSetName; } if ((config === null || config === void 0 ? void 0 : config.timeout) !== undefined) { this.defaultConfig.timeout = config === null || config === void 0 ? void 0 : config.timeout; } if ((config === null || config === void 0 ? void 0 : config.threadNum) !== undefined) { this.defaultConfig.threadNum = config === null || config === void 0 ? void 0 : config.threadNum; } if ((config === null || config === void 0 ? void 0 : config.responseWithRequestInfo) !== undefined) { this.defaultConfig.responseWithRequestInfo = config === null || config === void 0 ? void 0 : config.responseWithRequestInfo; } if ((config === null || config === void 0 ? void 0 : config.consistency) !== undefined) { this.defaultConfig.consistency = config.consistency; } if (config === null || config === void 0 ? void 0 : config.logUql) { this.defaultConfig.logUql = config === null || config === void 0 ? void 0 : config.logUql; } if (config === null || config === void 0 ? void 0 : config.timeZone) { this.defaultConfig.timeZone = config.timeZone; } if (config === null || config === void 0 ? void 0 : config.timeZoneOffset) { this.defaultConfig.timeZoneOffset = config.timeZoneOffset; } if ((config === null || config === void 0 ? void 0 : config.timestampToString) !== undefined) { this.defaultConfig.timestampToString = config.timestampToString; } } getGraphSetName(currentGraphName, uql, isGlobal) { var _a; if (isGlobal) { return exports.RAFT_GLOBAL; } if (uql) { let uqlParse = new utils_1.EasyUqlParse(uql); if (uqlParse.isGlobal()) { return exports.RAFT_GLOBAL; } // truncate,mount,unmount,update, 发给当前图集 if ([ CommandList.truncate, CommandList.mountGraph, CommandList.unmountGraph, ].includes(`${uqlParse.firstCommandName()}().${uqlParse.secondCommandName()}`)) { let graphName = (_a = uqlParse.getCommand(1)) === null || _a === void 0 ? void 0 : _a.safelyGetFirstParams(); if (!!graphName) { return graphName; } } } return currentGraphName || this.defaultConfig.graphSetName; } getTimeout(timeout) { return timeout || this.defaultConfig.timeout; } getThreadNum(threadNum) { return threadNum || this.defaultConfig.threadNum; } getLogUql(logUql) { return logUql || this.defaultConfig.logUql; } getTimeZone(timeZone) { return timeZone || this.defaultConfig.timeZone; } getTimeZoneOffset(timeZoneOffset) { return timeZoneOffset || this.defaultConfig.timeZoneOffset; } getTimestampToString(timestampToString) { if (timestampToString === true || timestampToString === false) { return timestampToString; } return this.defaultConfig.timestampToString; } // public closeAll() { // this.hostManagerControl.closeAll() // } getClientInfo(params) { return __awaiter(this, void 0, void 0, function* () { let { type, graphSetName, uql, isGlobal, ignoreRaft, useHost, clusterId, useMaster, timeZone, timeZoneOffset, } = params; let goGraphName = this.getGraphSetName(graphSetName, params.uql, isGlobal); if ((!ignoreRaft && !this.hostManagerControl.getHostManger(goGraphName).raftReady) || (params === null || params === void 0 ? void 0 : params.forceRefresh)) { let res = yield this.refreshRaftLeader(this.hostManagerControl.initHost, { graphSetName: goGraphName, }); this.hostManagerControl.getHostManger(goGraphName).raftReady = res; } let clientInfo = this.hostManagerControl.chooseClientInfo({ type, uql, graphSetName: goGraphName, useHost: useHost, useMaster: useMaster, }); let metadata = clientInfo.getMetadata(goGraphName, clusterId, this.getTimeZone(timeZone), this.getTimeZoneOffset(timeZoneOffset)); return { client: clientInfo.getClient(), host: clientInfo.host, metadata, goGraphName, }; }); } getTimeZoneType(commonReq) { return { timestampToString: this.getTimestampToString(commonReq === null || commonReq === void 0 ? void 0 : commonReq.timestampToString), timeZone: this.getTimeZone(commonReq === null || commonReq === void 0 ? void 0 : commonReq.timeZone), timeZoneOffset: this.getTimeZoneOffset(commonReq === null || commonReq === void 0 ? void 0 : commonReq.timeZoneOffset), }; } uqlStream(uql, stream, requestConfig) { return __awaiter(this, void 0, void 0, function* () { if (!requestConfig) { requestConfig = {}; } yield new Promise((resolve, reject) => { this.uql(uql, Object.assign(Object.assign({}, requestConfig), { stream: { onData: (_res) => __awaiter(this, void 0, void 0, function* () { yield stream.onData(types_1.ULTIPA.formatBaseResponse(_res)); }), onEnd: () => { stream.onEnd(); resolve(true); }, onClose: () => { var _a; resolve(true); (_a = stream.onClose) === null || _a === void 0 ? void 0 : _a.call(stream); }, onError: (err) => { var _a; resolve(true); (_a = stream.onError) === null || _a === void 0 ? void 0 : _a.call(stream, err); }, onPause: () => { var _a; (_a = stream.onPause) === null || _a === void 0 ? void 0 : _a.call(stream); }, onReadable: () => { var _a; (_a = stream.onReadable) === null || _a === void 0 ? void 0 : _a.call(stream); }, onResume: () => { var _a; (_a = stream.onResume) === null || _a === void 0 ? void 0 : _a.call(stream); }, onStart: () => { var _a; (_a = stream.onStart) === null || _a === void 0 ? void 0 : _a.call(stream); }, package_limit: stream.package_limit } })); }); }); } uql(uql, requestConfig) { return __awaiter(this, void 0, void 0, function* () { try { return yield this._uql_without_catch(uql, requestConfig); } catch (error) { return utils_1.FormatResponse.catchUltipaUqlError(error); } }); } /** * 运行UQL */ _uql_without_catch(uql, commonReq) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { try { let _TIME_MAP = { main: `${uql.substr(0, 20) + (uql.length > 20 ? "..." : "")}`, getClientInfo: "Get client info", uql: "Execute UQL", }; let logUql = this.getLogUql(commonReq === null || commonReq === void 0 ? void 0 : commonReq.logUql); let timeRecordManager = new utils_1.TimeRecordManager(_TIME_MAP.main); let response = new types_1.ULTIPA.UQLBaseResponse(); let onErrorCache_go_on_exec_onEnd = null; let request = new ultipa_pb_1.UqlRequest(); request.setUql(uql); request.setTimeout(this.getTimeout(commonReq === null || commonReq === void 0 ? void 0 : commonReq.timeout)); request.setThreadNum(this.getThreadNum(commonReq === null || commonReq === void 0 ? void 0 : commonReq.threadNum) || 0); let timeZoneType = this.getTimeZoneType(); if (timeZoneType.timeZone !== undefined) { request.setTz(timeZoneType.timeZone); } if (timeZoneType.timeZoneOffset !== undefined) { request.setTzOffset(timeZoneType.timeZoneOffset + ""); } timeRecordManager.start(_TIME_MAP.getClientInfo); let clientInfo = yield this.getClientInfo({ graphSetName: commonReq === null || commonReq === void 0 ? void 0 : commonReq.graphSetName, clusterId: commonReq === null || commonReq === void 0 ? void 0 : commonReq.clusterId, uql, useHost: (commonReq === null || commonReq === void 0 ? void 0 : commonReq.useHost) || this.defaultConfig.useHost, useMaster: commonReq === null || commonReq === void 0 ? void 0 : commonReq.useMaster, forceRefresh: commonReq === null || commonReq === void 0 ? void 0 : commonReq.forceRefresh, timeZone: commonReq === null || commonReq === void 0 ? void 0 : commonReq.timeZone, timeZoneOffset: commonReq === null || commonReq === void 0 ? void 0 : commonReq.timeZoneOffset, }); timeRecordManager.stop(_TIME_MAP.getClientInfo); timeRecordManager.start(_TIME_MAP.uql); let { currentRetry } = utils_1.retryHelper.getRetry(commonReq); let getDateString = () => { return `${(0, moment_timezone_1.default)().format("YYYY-DD-MM HH:mm:ss.SSS")} <${chalk_1.default.green(this.username)}>`; }; let { goGraphName, metadata, host } = clientInfo; if (logUql) { console.log(`${getDateString()} SDK_LOG: [${host}-${goGraphName}] ${chalk_1.default.green(uql)} START! ${(commonReq === null || commonReq === void 0 ? void 0 : commonReq.forceRefresh) ? "Force Refresh!" : ""}`); } let uqlParse = new utils_1.EasyUqlParse(uql); let isUseUqlExtra = uqlParse.isExtra(); // isUseUqlExtra = false let stream = isUseUqlExtra ? clientInfo.client.controlsClient.uqlEx(request, metadata) : clientInfo.client.rpcsClient.uql(request, metadata); let dataCustomDeal = utils_1.streamHelper.isUseStream(commonReq === null || commonReq === void 0 ? void 0 : commonReq.stream); let addReq = () => { var _a; if ((_a = this.defaultConfig) === null || _a === void 0 ? void 0 : _a.responseWithRequestInfo) { response.req = { graphName: goGraphName, uql, retry: currentRetry, host, isUseUqlExtra, forceRefresh: commonReq === null || commonReq === void 0 ? void 0 : commonReq.forceRefresh }; } }; let dealReq = dataCustomDeal ? commonReq === null || commonReq === void 0 ? void 0 : commonReq.stream : { package_limit: commonReq === null || commonReq === void 0 ? void 0 : commonReq.package_limit, onData: (_res) => { if (!response.status) { response = _res; } else { response = (0, utils_1.mergeUqlResponse)(response, _res); } }, onEnd: () => __awaiter(this, void 0, void 0, function* () { if (onErrorCache_go_on_exec_onEnd) { return; } addReq(); let { canRetry, nextRetry } = yield utils_1.retryHelper.check(this, response, commonReq, goGraphName); if (canRetry) { let res = yield this.uql(uql, Object.assign(Object.assign({}, commonReq), { retry: nextRetry })); resolve(res); return; } timeRecordManager.stop(_TIME_MAP.uql); timeRecordManager.stopTotal(); if (response.req) { response.req.time_record = timeRecordManager.toString(); } if (logUql) { console.log(`${getDateString()} SDK_LOG: [${host}-${goGraphName}] ${chalk_1.default.green(uql)} END! ${(response.status.code === types_1.ULTIPA.Code.SUCCESS ? "✅" : "❌")} ${JSON.stringify(response.status)}`); } let res = types_1.ULTIPA.formatBaseResponse(response); resolve(res); }), onError: (err) => __awaiter(this, void 0, void 0, function* () { addReq(); // resolve here,and onData should be stop onErrorCache_go_on_exec_onEnd = err; stream.cancel(); let e = err; if (e.code === 14 && !(commonReq === null || commonReq === void 0 ? void 0 : commonReq.forceRefresh)) { let res = yield this.uql(uql, Object.assign(Object.assign({}, commonReq), { forceRefresh: true })); resolve(res); return; } response = utils_1.FormatResponse.unknownError(err, response); if (logUql) { console.log(`${getDateString()} SDK_LOG: [${host}-${goGraphName}] ${chalk_1.default.green(uql)} END! ${(response.status.code === types_1.ULTIPA.Code.SUCCESS ? "✅" : "❌")} ${JSON.stringify(response.status)}`); } let res = types_1.ULTIPA.formatBaseResponse(response); resolve(res); }), }; utils_1.streamHelper.commonDeal(stream, dealReq, (_res) => { let res = _res; return utils_1.FormatType.uqlResponse(res, this.getTimeZoneType(commonReq)); }); if (dataCustomDeal) { resolve(null); } } catch (error) { reject(error); } })); }); } /** * 通过UQLMaker运行uql */ uqlSingle(uqlMaker) { return __awaiter(this, void 0, void 0, function* () { let res = yield this.uql(uqlMaker.toString(), uqlMaker.commonParams); let uqlReply = res.data; if (uqlReply) { return { responseWithoutData: { status: res.status, statistics: uqlReply.statistics, req: res.req, }, uqlReply: uqlReply, }; } return { responseWithoutData: { status: res.status, req: res.req, }, }; }); } auth(req, commonReq) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { let authReq = new ultipa_pb_1.AuthenticateRequest(); authReq.setType(req.authType); if (req.uql) { authReq.setUql(req.uql); } let clientInfo = yield this.getClientInfo({ type: ClientType.Leader, graphSetName: commonReq === null || commonReq === void 0 ? void 0 : commonReq.graphSetName, clusterId: commonReq === null || commonReq === void 0 ? void 0 : commonReq.clusterId, timeZone: commonReq === null || commonReq === void 0 ? void 0 : commonReq.timeZone, timeZoneOffset: commonReq === null || commonReq === void 0 ? void 0 : commonReq.timeZoneOffset, }); clientInfo.client.controlsClient.authenticate(authReq, clientInfo.metadata, (err, resp) => { let response = new types_1.ULTIPA.UQLResponse(); if (err) { response = utils_1.FormatResponse.unknownError(err, response); resolve(response); return; } response.status = utils_1.FormatType.status(resp.getStatus()); resolve(response); }); })); }); } /** * 得到集群Leader信息 */ getRaftLeader(commonReq) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { let req = new ultipa_pb_1.GetLeaderRequest(); let clientInfo = yield this.getClientInfo({ type: ClientType.Leader, graphSetName: commonReq === null || commonReq === void 0 ? void 0 : commonReq.graphSetName, clusterId: commonReq === null || commonReq === void 0 ? void 0 : commonReq.clusterId, ignoreRaft: true, timeZone: commonReq === null || commonReq === void 0 ? void 0 : commonReq.timeZone, timeZoneOffset: commonReq === null || commonReq === void 0 ? void 0 : commonReq.timeZoneOffset, }); clientInfo.client.controlsClient.getLeader(req, clientInfo.metadata, (err, resp) => { let response = new types_1.ULTIPA.UQLResponse(); if (err) { response = utils_1.FormatResponse.unknownError(err, response); resolve(response); return; } response.status = utils_1.FormatType.status(resp.getStatus(), { host: clientInfo.host, }); // console.log("--- get raft leader", clientInfo.host, clientInfo.goGraphName) // console.dir(response, {depth: null}) resolve(response); }); })); }); } /** * 根据指定host刷新集群leader信息 * @param redirectHost 重跳host */ refreshRaftLeader(redirectHost, commonReq) { return __awaiter(this, void 0, void 0, function* () { let _autoGetRaftLeader = (host, retry = 1) => __awaiter(this, void 0, void 0, function* () { // console.log(host, retry, this.username, this.password, this.crt) let conn = new ConnectionBase(host, this.username, this.password, this.crt, this.defaultConfig, true); let resRaftLeader = yield conn.getRaftLeader(commonReq); let { code, clusterInfo } = resRaftLeader.status; if (code == types_1.ULTIPA.Code.SUCCESS) { return { code, leaderHost: host, followersPeerInfos: clusterInfo === null || clusterInfo === void 0 ? void 0 : clusterInfo.raftPeers.filter((info) => { return info.host != host; }), }; } if (code == types_1.ULTIPA.Code.NOT_RAFT_MODE) { return { code: types_1.ULTIPA.Code.SUCCESS, leaderHost: host, followersPeerInfos: null, }; } if ([ types_1.ULTIPA.Code.RAFT_NO_AVAILABLE_FOLLOWERS, types_1.ULTIPA.Code.RAFT_NO_AVAILABLE_ALGO_SERVERS, types_1.ULTIPA.Code.RAFT_LEADER_NOT_YET_ELECTED, types_1.ULTIPA.Code.RAFT_REDIRECT, ].includes(code)) { if (retry > 2) { return { code, }; } if (code != types_1.ULTIPA.Code.RAFT_REDIRECT) { yield (0, utils_1.sleep)(300); } // console.log(1111, code, clusterInfo) return yield _autoGetRaftLeader((clusterInfo === null || clusterInfo === void 0 ? void 0 : clusterInfo.redirect) || host, retry + 1); } return { code, }; }); let hosts = redirectHost ? [redirectHost] : this.hostManagerControl.getAllHosts(); let goGraphName = this.getGraphSetName(commonReq === null || commonReq === void 0 ? void 0 : commonReq.graphSetName); // console.log(hosts) for (let index = 0; index < hosts.length; index++) { const h = hosts[index]; let resRaftLeader = yield _autoGetRaftLeader(h); let { code } = resRaftLeader; if (code == types_1.ULTIPA.Code.SUCCESS) { let { leaderHost, followersPeerInfos } = resRaftLeader; let hostManager = this.hostManagerControl.upsetHostManger(goGraphName, leaderHost); hostManager.setClients(leaderHost, followersPeerInfos); return true; } } return false; }); } /** * 登录 */ login(commonReq) { return __awaiter(this, void 0, void 0, function* () { network_manager_1.grpcNetworkManager.removeUltipaRpcsClient(this.hostManagerControl.initHost, this.crt); return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { let v = yield this.test_has_message(commonReq); if (v.connect) { resolve(true); } else { reject(v.msg); } })); }); } /** * 测试连接 */ test(commonReq) { return __awaiter(this, void 0, void 0, function* () { let v = yield this.test_has_message(commonReq); return v.connect; }); } /** * 测试连接 */ test_has_message(commonReq) { return __awaiter(this, void 0, void 0, function* () { let createResult = (connect, msg) => { return { connect, msg, }; }; if (commonReq === null || commonReq === void 0 ? void 0 : commonReq.useHost.includes("UNAVAILABLE")) { yield (0, utils_1.sleepSeconds)(3); return createResult(false, `14 UNAVAILABLE: Name resolution failed for target dns: ${commonReq === null || commonReq === void 0 ? void 0 : commonReq.useHost}`); } return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { setTimeout(() => { resolve(createResult(false, "connect timeout")); return; }, 3000); let clientInfo = yield this.getClientInfo({ isGlobal: true, useHost: commonReq === null || commonReq === void 0 ? void 0 : commonReq.useHost, ignoreRaft: true, timeZone: commonReq === null || commonReq === void 0 ? void 0 : commonReq.timeZone, timeZoneOffset: commonReq === null || commonReq === void 0 ? void 0 : commonReq.timeZoneOffset, }); let name = "test"; let req = new ultipa_pb_1.HelloUltipaRequest(); req.setName(name); clientInfo.client.controlsClient.sayHello(req, clientInfo.metadata, (err, res) => { if (err) { resolve(createResult(false, err.message || err.details)); // 发生错误也是连接不成功 return; } let msg = res.getMessage(); if (msg != `${name} Welcome To Ultipa!`) { resolve(createResult(false, res.getStatus().getMsg())); return; } resolve(createResult(true, "ok")); }); })); }); } static UqlUpdateSimple(conn, uqlMaker) { return __awaiter(this, void 0, void 0, function* () { let res = yield conn.uqlSingle(uqlMaker); return res.responseWithoutData; }); } static UqlListSimple(conn, uqlMaker, keyFormat) { var _a; return __awaiter(this, void 0, void 0, function* () { let res = yield ConnectionBase.UqlListSimpleAuto(conn, uqlMaker, keyFormat); let { data } = res, others = __rest(res, ["data"]); return Object.assign(Object.assign({}, others), { data: ((_a = data === null || data === void 0 ? void 0 : data[0]) === null || _a === void 0 ? void 0 : _a.values) || [] }); }); } static UqlListSimpleAuto(conn, uqlMaker, keyFormat) { var _a; return __awaiter(this, void 0, void 0, function* () { let res = yield conn.uqlSingle(uqlMaker); let uqlReply = res.uqlReply; let tables = (uqlReply === null || uqlReply === void 0 ? void 0 : uqlReply.getTables()) || []; let mockTables = (_a = keyFormat === null || keyFormat === void 0 ? void 0 : keyFormat.mockData) === null || _a === void 0 ? void 0 : _a.tables; if (mockTables) { tables = mockTables; } let data = []; for (const table of tables) { let d = table.toKV(); d = utils_1.FormatResponse.formatObjects(d, keyFormat); data.push({ name: table.name, values: d, }); } return Object.assign(Object.assign({}, res.responseWithoutData), { data }); }); } static UqlGetSimple(conn, uqlMaker, keyFormat) { var _a, _b; return __awaiter(this, void 0, void 0, function* () { let res = yield conn.uqlSingle(uqlMaker); let uqlReply = res.uqlReply; let data = null; if (uqlReply) { data = (_b = (_a = uqlReply.singleDataTables()) === null || _a === void 0 ? void 0 : _a.toKV()) === null || _b === void 0 ? void 0 : _b[0]; data = utils_1.FormatResponse.formatObject(data, keyFormat); } return Object.assign(Object.assign({}, res.responseWithoutData), { data }); }); } } exports.ConnectionBase = ConnectionBase; //# sourceMappingURL=connection.base.js.map