From 36dcea7d7c60a5261d9bdaae4feea4844ac1c575 Mon Sep 17 00:00:00 2001 From: "Chakhsu.Lau" Date: Tue, 12 Dec 2023 11:05:40 +0800 Subject: [PATCH] chore: remove types --- types/config/defaultChannelOptions.d.ts | 2 - types/config/defaultChannelOptions.js | 21 -- types/config/defaultLoadOptions.d.ts | 2 - types/config/defaultLoadOptions.js | 10 - types/index.d.ts | 31 --- types/index.js | 235 ------------------- types/proxy/clientProxy.d.ts | 15 -- types/proxy/clientProxy.js | 283 ----------------------- types/proxy/serverProxy.d.ts | 38 ---- types/proxy/serverProxy.js | 291 ------------------------ types/schema/loader.d.ts | 7 - types/schema/loader.js | 42 ---- types/schema/server.d.ts | 5 - types/schema/server.js | 18 -- types/util/compose.d.ts | 11 - types/util/compose.js | 36 --- types/util/iterator.d.ts | 26 --- types/util/iterator.js | 153 ------------- types/util/prefixingDefinition.d.ts | 2 - types/util/prefixingDefinition.js | 21 -- 20 files changed, 1249 deletions(-) delete mode 100644 types/config/defaultChannelOptions.d.ts delete mode 100644 types/config/defaultChannelOptions.js delete mode 100644 types/config/defaultLoadOptions.d.ts delete mode 100644 types/config/defaultLoadOptions.js delete mode 100644 types/index.d.ts delete mode 100644 types/index.js delete mode 100644 types/proxy/clientProxy.d.ts delete mode 100644 types/proxy/clientProxy.js delete mode 100644 types/proxy/serverProxy.d.ts delete mode 100644 types/proxy/serverProxy.js delete mode 100644 types/schema/loader.d.ts delete mode 100644 types/schema/loader.js delete mode 100644 types/schema/server.d.ts delete mode 100644 types/schema/server.js delete mode 100644 types/util/compose.d.ts delete mode 100644 types/util/compose.js delete mode 100644 types/util/iterator.d.ts delete mode 100644 types/util/iterator.js delete mode 100644 types/util/prefixingDefinition.d.ts delete mode 100644 types/util/prefixingDefinition.js diff --git a/types/config/defaultChannelOptions.d.ts b/types/config/defaultChannelOptions.d.ts deleted file mode 100644 index c6aaf26..0000000 --- a/types/config/defaultChannelOptions.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { ChannelOptions } from '@grpc/grpc-js' -export declare const defaultChannelOptions: ChannelOptions diff --git a/types/config/defaultChannelOptions.js b/types/config/defaultChannelOptions.js deleted file mode 100644 index f6aa22e..0000000 --- a/types/config/defaultChannelOptions.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict' -Object.defineProperty(exports, '__esModule', { value: true }) -exports.defaultChannelOptions = void 0 -exports.defaultChannelOptions = { - 'grpc.min_reconnect_backoff_ms': 1000, - 'grpc.max_reconnect_backoff_ms': 10000, - 'grpc.grpclb_call_timeout_ms': 5000, - 'grpc.keepalive_timeout_ms': 20 * 1000, - 'grpc.keepalive_time_ms': 120 * 1000, - 'grpc.keepalive_permit_without_calls': 1, - 'grpc.enable_retries': 1, - 'grpc.service_config': JSON.stringify({ - retryPolicy: { - maxAttempts: 4, - initialBackoff: '0.1s', - maxBackoff: '1s', - backoffMultiplier: 2, - retryableStatusCodes: ['UNAVAILABLE'] - } - }) -} diff --git a/types/config/defaultLoadOptions.d.ts b/types/config/defaultLoadOptions.d.ts deleted file mode 100644 index 684e049..0000000 --- a/types/config/defaultLoadOptions.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { Options } from '@grpc/proto-loader' -export declare const defaultLoadOptions: Options diff --git a/types/config/defaultLoadOptions.js b/types/config/defaultLoadOptions.js deleted file mode 100644 index 1d4728f..0000000 --- a/types/config/defaultLoadOptions.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict' -Object.defineProperty(exports, '__esModule', { value: true }) -exports.defaultLoadOptions = void 0 -exports.defaultLoadOptions = { - keepCase: true, - longs: String, - enums: String, - defaults: false, - oneofs: true -} diff --git a/types/index.d.ts b/types/index.d.ts deleted file mode 100644 index 6438ef3..0000000 --- a/types/index.d.ts +++ /dev/null @@ -1,31 +0,0 @@ -import * as grpc from '@grpc/grpc-js' -import ServerProxy from './proxy/serverProxy' -declare class GrpcLoader { - private _protoFiles - private _clientMap - private _clientAddrMap - private _types - private _packagePrefix? - private _appName? - private _packageDefinition - private _isDev? - private _reflectedRoot - private _insecureCredentials? - private _initDefaultClient? - constructor(protoFileOptions: any) - init({ services, isDev, packagePrefix, loadOptions, channelOptions, appName }?: any): Promise - initClients({ services, channelOptions, credentials }: any): Promise - closeClients(): void - makeCredentials(rootCerts?: any, privateKey?: any, certChain?: any, verifyOptions?: any): grpc.ChannelCredentials - service(name: string): any - type(name: string): any - message(name: string): any - client(name: string, { host, port, timeout, credentials, channelOptions }?: any): any - realClient(name: string, { host, port, credentials, channelOptions }?: any): any - clientWithoutCache(name: string, { addr, timeout, credentials, channelOptions }?: any): any - private _makeClient - private _makeClientWithoutCache - makeMetadata(initialValues: any): grpc.Metadata - initServer(...args: any[]): ServerProxy -} -export default GrpcLoader diff --git a/types/index.js b/types/index.js deleted file mode 100644 index 949ba87..0000000 --- a/types/index.js +++ /dev/null @@ -1,235 +0,0 @@ -'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 __importDefault = - (this && this.__importDefault) || - function (mod) { - return mod && mod.__esModule ? mod : { default: mod } - } -Object.defineProperty(exports, '__esModule', { value: true }) -const node_assert_1 = __importDefault(require('node:assert')) -const grpc = __importStar(require('@grpc/grpc-js')) -const protoLoader = __importStar(require('@grpc/proto-loader')) -const protobuf = __importStar(require('protobufjs')) -const Descriptor = __importStar(require('protobufjs/ext/descriptor')) -const _ = __importStar(require('lodash')) -const Joi = __importStar(require('joi')) -const loader_1 = __importDefault(require('./schema/loader')) -const prefixingDefinition_1 = __importDefault(require('./util/prefixingDefinition')) -const defaultChannelOptions_1 = require('./config/defaultChannelOptions') -const defaultLoadOptions_1 = require('./config/defaultLoadOptions') -const clientProxy_1 = __importDefault(require('./proxy/clientProxy')) -const serverProxy_1 = __importDefault(require('./proxy/serverProxy')) -class GrpcLoader { - constructor(protoFileOptions) { - Joi.assert(protoFileOptions, loader_1.default.constructor, 'new GrpcLoader() params Error') - this._protoFiles = Array.isArray(protoFileOptions) ? protoFileOptions : [protoFileOptions] - this._clientMap = new Map() - this._clientAddrMap = new Map() - } - async init({ services = undefined, isDev = false, packagePrefix = '', loadOptions = {}, channelOptions = {}, appName } = {}) { - Joi.assert({ services, loadOptions, isDev, channelOptions, appName }, loader_1.default.init, 'GrpcLoader.init() params Error') - if (this._types) { - return - } - try { - loadOptions = Object.assign({}, defaultLoadOptions_1.defaultLoadOptions, loadOptions) - this._isDev = isDev - this._packagePrefix = packagePrefix - this._appName = appName - loadOptions.includeDirs = this._protoFiles.map((p) => p.location).concat(loadOptions.includeDirs || []) - const files = this._protoFiles.reduce((result, p) => { - if (p.files && p.files.length > 0) { - result.push(...p.files) - } - return result - }, []) - const packageDefinition = await protoLoader.load(files, loadOptions) - if (this._packagePrefix) { - this._packageDefinition = (0, prefixingDefinition_1.default)(packageDefinition, packagePrefix) - } else { - this._packageDefinition = packageDefinition - } - this._types = grpc.loadPackageDefinition(this._packageDefinition) - } catch (err) { - throw err - } - if (services) { - await this.initClients({ services, channelOptions }) - } - } - async initClients({ services, channelOptions = {}, credentials = undefined }) { - Joi.assert({ services, channelOptions }, loader_1.default.initClients, 'GrpcLoader.initClients() Options Error') - if (this._initDefaultClient) { - return - } - if (!this._packageDefinition) { - await this.init() - } - const serviceNames = Object.keys(services) - serviceNames.forEach((name) => { - const isDefaultClient = true - const addr = _.isString(services[name]) ? services[name] : services[name].host + ':' + services[name].port - this._makeClient(isDefaultClient, name, addr, credentials, channelOptions) - }) - this._initDefaultClient = true - } - closeClients() { - this._clientMap.forEach((client, key) => { - if (client && typeof client.close === 'function') { - client.close() - } - }) - this._clientMap.clear() - this._clientAddrMap.clear() - this._initDefaultClient = false - } - makeCredentials(rootCerts, privateKey, certChain, verifyOptions) { - if (rootCerts && privateKey && certChain) { - return grpc.credentials.createSsl(rootCerts, privateKey, certChain, verifyOptions) - } else { - if (!this._insecureCredentials) { - this._insecureCredentials = grpc.credentials.createInsecure() - } - return this._insecureCredentials - } - } - service(name) { - ;(0, node_assert_1.default)(this._types, 'Must called init() first. proto file has not been loaded.') - const fullName = this._isDev ? `${this._packagePrefix}.${name}` : name - const service = _.get(this._types, `${fullName}.service`) - ;(0, node_assert_1.default)(service, `Cannot find service with name: ${fullName}, please check if the protos file is configured incorrectly or if the corresponding proto file is missing.`) - return service - } - type(name) { - ;(0, node_assert_1.default)(this._types, 'Must called init() first. proto file has not been loaded.') - const fullName = this._isDev ? `${this._packagePrefix}.${name}` : name - const type = _.get(this._types, `${fullName}`) - ;(0, node_assert_1.default)(type, `Cannot find type with name: ${fullName}, please check if the protos file is configured incorrectly or if the corresponding proto file is missing.`) - return type - } - message(name) { - let root = this._reflectedRoot - if (root) { - const found = root.lookupType(name) - if (found) { - return found - } - } - const descriptor = this.type(name).fileDescriptorProtos.map((proto) => Descriptor.FileDescriptorProto.decode(proto)) - root = protobuf.Root.fromDescriptor({ - file: descriptor - }) - this._reflectedRoot = root - return root.lookupType(name) - } - client(name, { host = undefined, port = undefined, timeout = undefined, credentials = undefined, channelOptions = {} } = {}) { - const isDefaultClient = !(host && port) - const addr = `${host}:${port}` - const cacheKeyPrefix = isDefaultClient ? 'defaultAddr' : addr.replace(/\./g, '-') - const cacheKey = `proxy.${cacheKeyPrefix}.${name}.${timeout}` - if (this._clientMap.has(cacheKey)) { - return this._clientMap.get(cacheKey) - } else { - const client = this._makeClient(isDefaultClient, name, addr, credentials, channelOptions) - const appName = this._appName - const proxy = clientProxy_1.default._proxy(client, { timeout }, appName) - this._clientMap.set(cacheKey, proxy) - return proxy - } - } - realClient(name, { host = undefined, port = undefined, credentials = undefined, channelOptions = {} } = {}) { - const isDefaultClient = !(host && port) - const client = this._makeClient(isDefaultClient, name, `${host}:${port}`, credentials, channelOptions) - return client - } - clientWithoutCache(name, { addr, timeout = undefined, credentials = undefined, channelOptions = {} } = {}) { - const client = this._makeClientWithoutCache(false, name, addr, credentials, channelOptions) - const appName = this._appName - const proxy = clientProxy_1.default._proxy(client, { timeout }, appName) - return proxy - } - _makeClient(isDefaultClient, name, addr, credentials, channelOptions = {}) { - const ctBool = !!credentials - const cacheKeyPrefix = isDefaultClient ? 'defaultAddr' : addr.replace(/\./g, '-') - const cacheKeyWithCt = `${cacheKeyPrefix}.${name}.${ctBool}` - const cacheKey = `${cacheKeyPrefix}.${name}` - if (this._clientMap.has(cacheKey)) { - return this._clientMap.get(cacheKey) - } else if (this._clientMap.has(cacheKeyWithCt)) { - return this._clientMap.get(cacheKeyWithCt) - } else { - let cacheAddr = addr - if (addr === 'undefined:undefined') { - cacheAddr = this._clientAddrMap.get(name) || addr - } - const client = this._makeClientWithoutCache(isDefaultClient, name, cacheAddr, credentials, channelOptions) - this._clientAddrMap.set(name, cacheAddr) - this._clientMap.set(cacheKey, client) - return client - } - } - _makeClientWithoutCache(isDefaultClient, name, addr, credentials, channelOptions = {}) { - channelOptions = Object.assign({}, defaultChannelOptions_1.defaultChannelOptions, channelOptions) - const ServiceProto = this.type(name) - const client = new ServiceProto(addr, credentials || this.makeCredentials(), channelOptions) - return client - } - makeMetadata(initialValues) { - ;(0, node_assert_1.default)(this._types, 'Must called init() first. proto file has not been loaded.') - const meta = new grpc.Metadata() - if (typeof initialValues === 'object') { - Object.entries(initialValues).forEach(([key, value]) => { - if (Array.isArray(value)) { - value.map((v) => meta.add(key, _.isString(v) ? v : Buffer.from(v))) - } else { - meta.add(key, _.isString(value) ? value : Buffer.from(value)) - } - }) - } - return meta - } - initServer(...args) { - ;(0, node_assert_1.default)(this._types, 'Must called init() first. proto file has not been loaded.') - const server = new serverProxy_1.default() - return server._init(this, ...args) - } -} -exports.default = GrpcLoader -module.exports = GrpcLoader diff --git a/types/proxy/clientProxy.d.ts b/types/proxy/clientProxy.d.ts deleted file mode 100644 index 83ea610..0000000 --- a/types/proxy/clientProxy.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { UntypedServiceImplementation } from '@grpc/grpc-js' -declare class ClientProxy { - private _getFuncStreamWay - private _prepareMetadata - private _handlerError - private _setDeadline - private _promisifyUnaryMethod - private _promisifyClientStreamMethod - private _promisifyServerStreamMethod - private _promisifyDuplexStreamMethod - private _keepCallbackMethod - _proxy(client: UntypedServiceImplementation, defaultOptions?: Record, appName?: string): any -} -declare const _default: ClientProxy -export default _default diff --git a/types/proxy/clientProxy.js b/types/proxy/clientProxy.js deleted file mode 100644 index 4ce56f7..0000000 --- a/types/proxy/clientProxy.js +++ /dev/null @@ -1,283 +0,0 @@ -'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 __importDefault = - (this && this.__importDefault) || - function (mod) { - return mod && mod.__esModule ? mod : { default: mod } - } -Object.defineProperty(exports, '__esModule', { value: true }) -const grpc_js_1 = require('@grpc/grpc-js') -const os = __importStar(require('node:os')) -const iterator_1 = __importDefault(require('../util/iterator')) -class ClientProxy { - _getFuncStreamWay(func) { - const { requestStream, responseStream } = func - return { requestStream, responseStream } - } - _prepareMetadata(metadata, options, basicMeta) { - if (metadata instanceof grpc_js_1.Metadata) { - options = { ...options } - } else { - options = { ...metadata } - metadata = new grpc_js_1.Metadata() - } - if (basicMeta.hostname) { - metadata.add('x-client-hostname', basicMeta.hostname) - } - if (basicMeta.appName) { - metadata.add('x-client-app-name', basicMeta.appName) - } - return [metadata, options] - } - _handlerError(err, basicMeta) { - const newError = new Error() - newError.name = 'GrpcClientError' - newError.code = err.code - newError.message = `${basicMeta.fullServiceName} (${err.message})` - const stacks = newError.stack.split('\n') - newError.stack = [stacks[0], ...stacks.slice(2), ' ...', ...err.stack.split('\n').slice(1, 3)].join('\n') - return newError - } - _setDeadline(options, defaultOptions, basicMeta) { - if (!options.deadline) { - const timeout = options.timeout || defaultOptions.timeout - const deadline = new Date(Date.now() + timeout) - options.deadline = deadline - delete options.timeout - } - return options - } - _promisifyUnaryMethod(client, func, defaultOptions, basicMeta) { - const asyncUnaryMethod = async (request, metadata, options) => { - if (typeof options === 'function') { - throw new Error('gRPCity: AsyncFunction should not contain a callback function') - } else if (typeof metadata === 'function') { - throw new Error('gRPCity: AsyncFunction should not contain a callback function') - } - ;[metadata, options] = this._prepareMetadata(metadata, options, basicMeta) - options = this._setDeadline(options, defaultOptions, basicMeta) - return new Promise((resolve, reject) => { - const result = {} - const argumentsList = [request, metadata, options] - argumentsList.push((err, response) => { - if (err) { - reject(this._handlerError(err, basicMeta)) - } - result.response = response - }) - const call = func.apply(client, argumentsList) - call.on('metadata', (metadata) => { - result.metadata = metadata - }) - call.on('status', (status) => { - result.status = status - resolve(result) - }) - }) - } - return asyncUnaryMethod - } - _promisifyClientStreamMethod(client, func, defaultOptions, basicMeta) { - const clientStreamMethod = (metadata, options) => { - if (typeof options === 'function') { - throw new Error('gRPCity: asyncStreamFunction should not contain a callback function') - } else if (typeof metadata === 'function') { - throw new Error('gRPCity: asyncStreamFunction should not contain a callback function') - } - ;[metadata, options] = this._prepareMetadata(metadata, options, basicMeta) - options = this._setDeadline(options, defaultOptions, basicMeta) - const result = {} - const argumentsList = [metadata, options] - argumentsList.push((err, response) => { - if (err) { - throw this._handlerError(err, basicMeta) - } - result.response = response - }) - const call = func.apply(client, argumentsList) - call.writeAll = (messages) => { - if (Array.isArray(messages)) { - messages.forEach((message) => { - call.write(message) - }) - } - } - call.writeEnd = async () => { - call.end() - await new Promise((resolve, reject) => { - call.on('metadata', (metadata) => { - result.metadata = metadata - }) - call.on('status', (status) => { - result.status = status - resolve() - }) - }) - return result - } - return call - } - return clientStreamMethod - } - _promisifyServerStreamMethod(client, func, defaultOptions, basicMeta) { - const serverStreamMethod = (request, metadata, options) => { - if (typeof options === 'function') { - throw new Error('gRPCity: asyncStreamFunction should not contain a callback function') - } else if (typeof metadata === 'function') { - throw new Error('gRPCity: asyncStreamFunction should not contain a callback function') - } - ;[metadata, options] = this._prepareMetadata(metadata, options, basicMeta) - options = this._setDeadline(options, defaultOptions, basicMeta) - const call = func.apply(client, [request, metadata, options]) - call.on('error', (err) => { - throw this._handlerError(err, basicMeta) - }) - const result = {} - call.readAll = () => { - call.on('metadata', (metadata) => { - result.metadata = metadata - }) - call.on('status', (status) => { - result.status = status - }) - return (0, iterator_1.default)(call, 'data', { - resolutionEvents: ['status', 'end'] - }) - } - call.readEnd = () => { - return result - } - return call - } - return serverStreamMethod - } - _promisifyDuplexStreamMethod(client, func, defaultOptions, basicMeta) { - const duplexStreamMethod = (metadata, options) => { - if (typeof options === 'function') { - throw new Error('gRPCity: asyncStreamFunction should not contain a callback function') - } else if (typeof metadata === 'function') { - throw new Error('gRPCity: asyncStreamFunction should not contain a callback function') - } - ;[metadata, options] = this._prepareMetadata(metadata, options, basicMeta) - options = this._setDeadline(options, defaultOptions, basicMeta) - const call = func.apply(client, [metadata, options]) - call.writeAll = (messages) => { - if (Array.isArray(messages)) { - messages.forEach((message) => { - call.write(message) - }) - } - } - call.writeEnd = call.end - call.on('error', (err) => { - throw this._handlerError(err, basicMeta) - }) - const result = {} - call.readAll = () => { - call.on('metadata', (metadata) => { - result.metadata = metadata - }) - call.on('status', (status) => { - result.status = status - }) - return (0, iterator_1.default)(call, 'data', { - resolutionEvents: ['status', 'end'] - }) - } - call.readEnd = () => { - return result - } - return call - } - return duplexStreamMethod - } - _keepCallbackMethod(client, func) { - const callbackMethod = (...argumentsList) => { - return func.apply(client, argumentsList) - } - return callbackMethod - } - _proxy(client, defaultOptions = {}, appName) { - defaultOptions = defaultOptions || {} - defaultOptions.timeout = defaultOptions.timeout || 1000 * 10 - const prototype = Object.getPrototypeOf(client) - const methodNames = Object.keys(prototype) - .filter((key) => prototype[key] && prototype[key].path) - .reduce((names, key) => { - names[key.toUpperCase()] = prototype[key].path - return names - }, {}) - const basicMeta = { - hostname: os.hostname(), - appName - } - const target = Object.entries(prototype).reduce( - (target, [name, func]) => { - if (name !== 'constructor' && typeof func === 'function') { - basicMeta.fullServiceName = `${methodNames[name.toUpperCase()]}` - const { requestStream, responseStream } = this._getFuncStreamWay(func) - if (!requestStream && !responseStream) { - // promisify unary method - target[name] = this._promisifyUnaryMethod(client, func, defaultOptions, basicMeta) - } - // stream - if (requestStream && !responseStream) { - // promisify only client stream method - target[name] = this._promisifyClientStreamMethod(client, func, defaultOptions, basicMeta) - } - if (!requestStream && responseStream) { - // promisify only server stream method - target[name] = this._promisifyServerStreamMethod(client, func, defaultOptions, basicMeta) - } - if (requestStream && responseStream) { - // promisify duplex stream method - target[name] = this._promisifyDuplexStreamMethod(client, func, defaultOptions, basicMeta) - } - // keep callback method - target.call[name] = this._keepCallbackMethod(client, func) - } - return target - }, - { call: {} } - ) - return target - } -} -exports.default = new ClientProxy() diff --git a/types/proxy/serverProxy.d.ts b/types/proxy/serverProxy.d.ts deleted file mode 100644 index 3da14c6..0000000 --- a/types/proxy/serverProxy.d.ts +++ /dev/null @@ -1,38 +0,0 @@ -/// -import * as grpc from '@grpc/grpc-js' -import { MiddlewareFunction } from '../util/compose' -declare class ServerProxy { - private _middleware - private _loader? - private _server? - private _insecureServerCredentials? - constructor() - _init(loader: any, ...args: any[]): this - listen(addr: any, credentials?: grpc.ServerCredentials | undefined): Promise - shutdown(): Promise - forceShutdown(): void - makeServerCredentials(rootCerts?: Buffer, keyCertPairs?: grpc.KeyCertPair[], checkClientCertificate?: boolean): grpc.ServerCredentials - addService( - name: string, - implementation: any, - { - exclude, - inherit - }?: { - exclude?: string[] - inherit?: any - } - ): void - removeService(name: string): void - addMiddleware(...args: MiddlewareFunction[]): void - private _use - private _callbackify - private _proxy - private _createContext - private _callUnaryProxyMethod - private _callClientStreamProxyMethod - private _callServerStreamProxyMethod - private _callDuplexStreamProxyMethod - private _createInternalErrorStatus -} -export default ServerProxy diff --git a/types/proxy/serverProxy.js b/types/proxy/serverProxy.js deleted file mode 100644 index 6bf0810..0000000 --- a/types/proxy/serverProxy.js +++ /dev/null @@ -1,291 +0,0 @@ -'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 __importDefault = - (this && this.__importDefault) || - function (mod) { - return mod && mod.__esModule ? mod : { default: mod } - } -Object.defineProperty(exports, '__esModule', { value: true }) -const node_assert_1 = __importDefault(require('node:assert')) -const util = __importStar(require('node:util')) -const grpc = __importStar(require('@grpc/grpc-js')) -const _ = __importStar(require('lodash')) -const Joi = __importStar(require('joi')) -const server_1 = __importDefault(require('../schema/server')) -const iterator_1 = __importDefault(require('../util/iterator')) -const compose_1 = require('../util/compose') -class ServerProxy { - constructor() { - this._middleware = [] - } - _init(loader, ...args) { - if (!this._loader) { - this._loader = loader - } - if (!this._server) { - this._server = new grpc.Server(...args) - } - return this - } - async listen(addr, credentials = undefined) { - ;(0, node_assert_1.default)(this._server, 'must be first init() server before server listen()') - Joi.assert(addr, server_1.default.address, 'server listen() params Error') - const url = _.isString(addr) ? addr : `${addr.host}:${addr.port}` - const bindPort = await new Promise((resolve, reject) => { - this._server.bindAsync(url, credentials || this.makeServerCredentials(), (err, result) => (err ? reject(err) : resolve(result))) - }) - const port = addr.port ? addr.port : Number(addr.match(/:(\d+)/)[1]) - ;(0, node_assert_1.default)(bindPort === port, 'server bind port not to be right') - this._server.start() - } - async shutdown() { - if (!this._server) { - return - } - await new Promise((resolve, reject) => { - this._server.tryShutdown((err) => { - if (err) { - reject(err) - } else { - resolve() - } - }) - }) - delete this._server - delete this._loader - } - forceShutdown() { - if (!this._server) { - return - } - this._server.forceShutdown() - delete this._server - delete this._loader - } - makeServerCredentials(rootCerts, keyCertPairs, checkClientCertificate) { - if (rootCerts && keyCertPairs) { - return grpc.ServerCredentials.createSsl(rootCerts, keyCertPairs, checkClientCertificate) - } else { - if (!this._insecureServerCredentials) { - this._insecureServerCredentials = grpc.ServerCredentials.createInsecure() - } - return this._insecureServerCredentials - } - } - addService(name, implementation, { exclude = [], inherit } = {}) { - const service = this._loader.service(name) - const options = { exclude, inherit, _implementationType: {} } - Object.keys(service).forEach((key) => { - const { requestStream, responseStream } = service[key] - options._implementationType[service[key].originalName] = { - requestStream, - responseStream - } - }) - this._server.addService(service, this._callbackify(implementation, options)) - } - removeService(name) { - ;(0, node_assert_1.default)(this._server, 'must be first init() server before server removeService()') - this._server.removeService(this._loader.service(name)) - } - addMiddleware(...args) { - ;(0, node_assert_1.default)(args.length >= 1, 'server addMiddleware() takes at least one argument.') - if (args.length === 1) { - if (Array.isArray(args[0])) { - args[0].forEach((fn) => { - this._use(fn) - }) - } else { - this._use(args[0]) - } - } else { - args.forEach((fn) => { - this._use(fn) - }) - } - } - _use(fn) { - if (typeof fn !== 'function') throw new TypeError('grpcity loader server middleware must be a function!') - this._middleware.push(fn) - } - _callbackify(target, { exclude = [], inherit, _implementationType }) { - ;(0, node_assert_1.default)(typeof target === 'object', 'Must callbackify an object') - ;(0, node_assert_1.default)(Array.isArray(exclude), 'options.exclude must be an array of strings') - const protoPropertyNames = Object.getOwnPropertyNames(Object.getPrototypeOf({})) - exclude.push(...protoPropertyNames) - const allPropertyNames = [ - ...new Set([...Object.keys(target), ...Object.getOwnPropertyNames(Object.getPrototypeOf(target)), ...(inherit && inherit.prototype ? Object.getOwnPropertyNames(inherit.prototype) : [])]) - ] - const methods = {} - for (const key of allPropertyNames) { - const fn = target[key] - if (typeof fn === 'function' && key !== 'constructor' && !exclude.includes(key)) { - if (util.types.isAsyncFunction(fn)) { - const eglWrapFunction = this._proxy(target, key, _implementationType[key]) - methods[key] = eglWrapFunction - } else { - methods[key] = fn - } - } - } - return methods - } - _proxy(target, key, options = {}) { - const { requestStream, responseStream } = options - const fn = (0, compose_1.compose)(this._middleware) - // unary - if (!requestStream && !responseStream) { - return this._callUnaryProxyMethod(target, key, fn) - } - // client stream - if (requestStream && !responseStream) { - return this._callClientStreamProxyMethod(target, key, fn) - } - // server stream - if (!requestStream && responseStream) { - return this._callServerStreamProxyMethod(target, key, fn) - } - // duplex stream - if (requestStream && responseStream) { - return this._callDuplexStreamProxyMethod(target, key, fn) - } - } - _createContext(call) { - return { - // TODO: maybe need more details - // method: target.constructor.name + '.' + key, - path: call.call.handler.path || '', - request: call.request, - metadata: call.metadata.clone() - } - } - _callUnaryProxyMethod(target, key, composeFunc) { - return (call, callback) => { - const ctx = this._createContext(call) - Promise.resolve().then(async () => { - const handleResponse = async () => { - ctx.response = await target[key](call) - } - await composeFunc(ctx, handleResponse).catch((err) => { - callback(this._createInternalErrorStatus(err)) - }) - callback(null, ctx.response) - }) - } - } - _callClientStreamProxyMethod(target, key, composeFunc) { - return (call, callback) => { - const ctx = this._createContext(call) - call.readAll = () => { - return (0, iterator_1.default)(call, 'data', { - resolutionEvents: ['end'] - }) - } - Promise.resolve().then(async () => { - const handleResponse = async () => { - ctx.response = await target[key](call) - } - await composeFunc(ctx, handleResponse).catch((err) => { - callback(this._createInternalErrorStatus(err)) - }) - callback(null, ctx.response) - }) - } - } - _callServerStreamProxyMethod(target, key, composeFunc) { - return (call) => { - const ctx = this._createContext(call) - call.writeAll = (messages) => { - if (Array.isArray(messages)) { - messages.forEach((message) => { - call.write(message) - }) - } - } - call.writeEnd = call.end - Promise.resolve().then(async () => { - const handleResponse = async () => { - await target[key](call) - } - await composeFunc(ctx, handleResponse).catch((err) => { - call.destroy(this._createInternalErrorStatus(err)) - }) - call.end() - }) - } - } - _callDuplexStreamProxyMethod(target, key, composeFunc) { - return (call) => { - const ctx = this._createContext(call) - call.writeAll = (messages) => { - if (Array.isArray(messages)) { - messages.forEach((message) => { - call.write(message) - }) - } - } - call.readAll = () => { - return (0, iterator_1.default)(call, 'data', { - resolutionEvents: ['end'] - }) - } - Promise.resolve().then(async () => { - const handleResponse = async () => { - await target[key](call) - } - await composeFunc(ctx, handleResponse).catch((err) => { - call.destroy(this._createInternalErrorStatus(err)) - }) - call.end() - }) - } - } - _createInternalErrorStatus(err) { - err.code = err.code || 13 - if (typeof err.stack === 'string') { - const stack = err.stack.split('\n') - err.messages += ` [Error Message From Server, stack: ${stack[1].trim()}]` - } else { - err.messages += ' [Error Message From Server]' - } - return err - } -} -exports.default = ServerProxy diff --git a/types/schema/loader.d.ts b/types/schema/loader.d.ts deleted file mode 100644 index 58d636f..0000000 --- a/types/schema/loader.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import Joi from 'joi' -declare const loaderSchemas: { - constructor: Joi.ArraySchema - init: Joi.ObjectSchema - initClients: Joi.ObjectSchema -} -export default loaderSchemas diff --git a/types/schema/loader.js b/types/schema/loader.js deleted file mode 100644 index 03fb97e..0000000 --- a/types/schema/loader.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict' -var __importDefault = - (this && this.__importDefault) || - function (mod) { - return mod && mod.__esModule ? mod : { default: mod } - } -Object.defineProperty(exports, '__esModule', { value: true }) -const joi_1 = __importDefault(require('joi')) -const addressSchema = joi_1.default.object().pattern( - /\.*/, - joi_1.default.alternatives([ - joi_1.default.string().regex(/:/, 'host and port like 127.0.0.1:9090'), - joi_1.default.object({ - host: joi_1.default.string().required(), - port: joi_1.default.number().integer().min(0).max(65535).required() - }) - ]) -) -const loaderSchemas = { - constructor: joi_1.default - .array() - .items( - joi_1.default.object({ - location: joi_1.default.string().required(), - files: joi_1.default.array().items(joi_1.default.string()).required() - }) - ) - .single(), - init: joi_1.default.object({ - services: addressSchema.optional(), - isDev: joi_1.default.boolean().optional(), - packagePrefix: joi_1.default.string().optional(), - loadOptions: joi_1.default.object().optional(), - channelOptions: joi_1.default.object().optional(), - appName: joi_1.default.string().optional() - }), - initClients: joi_1.default.object({ - services: addressSchema.required(), - channelOptions: joi_1.default.object().optional() - }) -} -exports.default = loaderSchemas diff --git a/types/schema/server.d.ts b/types/schema/server.d.ts deleted file mode 100644 index f3f6e43..0000000 --- a/types/schema/server.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import Joi from 'joi' -declare const serverSchemas: { - address: Joi.AlternativesSchema -} -export default serverSchemas diff --git a/types/schema/server.js b/types/schema/server.js deleted file mode 100644 index b777ef0..0000000 --- a/types/schema/server.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict' -var __importDefault = - (this && this.__importDefault) || - function (mod) { - return mod && mod.__esModule ? mod : { default: mod } - } -Object.defineProperty(exports, '__esModule', { value: true }) -const joi_1 = __importDefault(require('joi')) -const serverSchemas = { - address: joi_1.default.alternatives([ - joi_1.default.string().regex(/:/, 'host and port like 127.0.0.1:9090'), - joi_1.default.object({ - host: joi_1.default.string().required(), - port: joi_1.default.number().integer().min(0).max(65535).required() - }) - ]) -} -exports.default = serverSchemas diff --git a/types/util/compose.d.ts b/types/util/compose.d.ts deleted file mode 100644 index 927f742..0000000 --- a/types/util/compose.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -export type MiddlewareFunction = (context: any, next: () => Promise) => Promise -/** - * Compose `middleware` returning - * a fully valid middleware comprised - * of all those which are passed. - * - * @param {Array} middleware - * @return {Function} - * @api public - */ -export declare const compose: (middleware: MiddlewareFunction[]) => (context: any, next: () => Promise) => Promise diff --git a/types/util/compose.js b/types/util/compose.js deleted file mode 100644 index cf0a42f..0000000 --- a/types/util/compose.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict' -Object.defineProperty(exports, '__esModule', { value: true }) -exports.compose = void 0 -/** - * Compose `middleware` returning - * a fully valid middleware comprised - * of all those which are passed. - * - * @param {Array} middleware - * @return {Function} - * @api public - */ -const compose = (middleware) => { - if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!') - for (const fn of middleware) { - if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!') - } - return function (context, next) { - // last called middleware # - let index = -1 - return dispatch(0) - function dispatch(i) { - if (i <= index) return Promise.reject(new Error('next() called multiple times')) - index = i - let fn = middleware[i] - if (i === middleware.length) fn = next - if (!fn) return Promise.resolve() - try { - return Promise.resolve(fn(context, dispatch.bind(null, i + 1))) - } catch (err) { - return Promise.reject(err) - } - } - } -} -exports.compose = compose diff --git a/types/util/iterator.d.ts b/types/util/iterator.d.ts deleted file mode 100644 index 8614cd3..0000000 --- a/types/util/iterator.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -declare const _default: ( - emitter: any, - event: string | string[], - options: any -) => - | { - [Symbol.asyncIterator](): any - next(): Promise<{ - done: boolean - value: any - }> - return?: undefined - } - | { - [x: symbol]: () => any - next(): Promise<{ - done: boolean - value: any - }> - return(value: any): Promise<{ - done: boolean - value: any - }> - [Symbol.asyncIterator]?: undefined - } -export default _default diff --git a/types/util/iterator.js b/types/util/iterator.js deleted file mode 100644 index c3c4e34..0000000 --- a/types/util/iterator.js +++ /dev/null @@ -1,153 +0,0 @@ -'use strict' -Object.defineProperty(exports, '__esModule', { value: true }) -const symbolAsyncIterator = Symbol.asyncIterator || '@@asyncIterator' -const normalizeEmitter = (emitter) => { - const addListener = emitter.on || emitter.addListener || emitter.addEventListener - const removeListener = emitter.off || emitter.removeListener || emitter.removeEventListener - if (!addListener || !removeListener) { - throw new TypeError('Emitter is not compatible') - } - return { - addListener: addListener.bind(emitter), - removeListener: removeListener.bind(emitter) - } -} -const toArray = (value) => (Array.isArray(value) ? value : [value]) -exports.default = (emitter, event, options) => { - if (typeof options === 'function') { - options = { filter: options } - } - // Allow multiple events - const events = toArray(event) - options = { - rejectionEvents: ['error'], - resolutionEvents: [], - limit: Infinity, - multiArgs: false, - ...options - } - const { limit } = options - const isValidLimit = limit >= 0 && (limit === Infinity || Number.isInteger(limit)) - if (!isValidLimit) { - throw new TypeError('The `limit` option should be a non-negative integer or Infinity') - } - if (limit === 0) { - // Return an empty async iterator to avoid any further cost - return { - [Symbol.asyncIterator]() { - return this - }, - async next() { - return { - done: true, - value: undefined - } - } - } - } - const { addListener, removeListener } = normalizeEmitter(emitter) - let isDone = false - let error - let hasPendingError = false - const nextQueue = [] - const valueQueue = [] - let eventCount = 0 - let isLimitReached = false - const valueHandler = (...args) => { - eventCount++ - isLimitReached = eventCount === limit - const value = options.multiArgs ? args : args[0] - if (nextQueue.length > 0) { - const { resolve } = nextQueue.shift() - resolve({ done: false, value }) - if (isLimitReached) { - cancel() - } - return - } - valueQueue.push(value) - if (isLimitReached) { - cancel() - } - } - const cancel = () => { - isDone = true - for (const event of events) { - removeListener(event, valueHandler) - } - for (const rejectionEvent of options.rejectionEvents) { - removeListener(rejectionEvent, rejectHandler) - } - for (const resolutionEvent of options.resolutionEvents) { - removeListener(resolutionEvent, resolveHandler) - } - while (nextQueue.length > 0) { - const { resolve } = nextQueue.shift() - resolve({ done: true, value: undefined }) - } - } - const rejectHandler = (...args) => { - error = options.multiArgs ? args : args[0] - if (nextQueue.length > 0) { - const { reject } = nextQueue.shift() - reject(error) - } else { - hasPendingError = true - } - cancel() - } - const resolveHandler = (...args) => { - const value = options.multiArgs ? args : args[0] - if (options.filter && !options.filter(value)) { - return - } - if (nextQueue.length > 0) { - const { resolve } = nextQueue.shift() - resolve({ done: true, value }) - } else { - valueQueue.push(value) - } - cancel() - } - for (const event of events) { - addListener(event, valueHandler) - } - for (const rejectionEvent of options.rejectionEvents) { - addListener(rejectionEvent, rejectHandler) - } - for (const resolutionEvent of options.resolutionEvents) { - addListener(resolutionEvent, resolveHandler) - } - return { - [symbolAsyncIterator]() { - return this - }, - async next() { - if (valueQueue.length > 0) { - const value = valueQueue.shift() - return { - done: isDone && valueQueue.length === 0 && !isLimitReached, - value - } - } - if (hasPendingError) { - hasPendingError = false - throw error - } - if (isDone) { - return { - done: true, - value: undefined - } - } - return new Promise((resolve, reject) => nextQueue.push({ resolve, reject })) - }, - async return(value) { - cancel() - return { - done: isDone, - value - } - } - } -} diff --git a/types/util/prefixingDefinition.d.ts b/types/util/prefixingDefinition.d.ts deleted file mode 100644 index 2ca407c..0000000 --- a/types/util/prefixingDefinition.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -declare const _default: (packageDefinition: any, packagePrefix: any) => any -export default _default diff --git a/types/util/prefixingDefinition.js b/types/util/prefixingDefinition.js deleted file mode 100644 index 224836a..0000000 --- a/types/util/prefixingDefinition.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict' -Object.defineProperty(exports, '__esModule', { value: true }) -exports.default = (packageDefinition, packagePrefix) => { - for (const qualifiedName in packageDefinition) { - const definition = packageDefinition[qualifiedName] - const newPackage = `${packagePrefix}.${qualifiedName}` - if (definition.format && definition.type && definition.fileDescriptorProtos) { - packageDefinition[newPackage] = definition - } else { - const newDefinition = {} - for (const method in definition) { - const service = definition[method] - newDefinition[method] = Object.assign({}, service, { - path: service.path.replace(/^\//, `/${packagePrefix}.`) - }) - } - packageDefinition[newPackage] = newDefinition - } - } - return packageDefinition -}