All files / blong-gogo/src RpcClient.ts

48.93% Statements 115/235
100% Branches 5/5
100% Functions 5/5
48.93% Lines 115/235

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 2361x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 10x 10x 10x 10x 10x 10x 10x 1x 1x 1x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 1x 1x 2x 2x 2x 2x 1x 1x 91x 91x 91x 91x 1x 1x 10x 10x 10x                                                                                                                                                                                                                                                 10x 1x  
import type {
    Errors,
    IErrorFactory,
    IErrorMap,
    ILocal,
    ILog,
    IMeta,
    IPlatformApi,
    IRemote,
} from '@feasibleone/blong/types';
import got, {type HttpsOptions} from 'got';
 
import GatewayCodecImpl, {
    type IConfig as IConfigGatewayCodec,
    type IGatewayCodec,
} from './GatewayCodec.ts';
import RemoteImpl from './Remote.ts';
import type {IResolution} from './Resolution.ts';
import tls from './tls.ts';
 
export interface IRpcClient extends IRemote {
    verify: IGatewayCodec['verify'];
}
 
interface IError extends Error {
    type?: string;
    req?: object;
    res?: object;
}
 
const errorMap: IErrorMap = {
    'rpc.actionEmpty': {message: 'Listing actions returned empty response', statusCode: 403},
    'rpc.actionHttp': {message: 'Listing actions returned HTTP error {code}', statusCode: 403},
    'rpc.jsonRpcEmpty': 'JSON RPC response without response and error',
    'rpc.jsonRpcHttp': 'JSON RPC returned HTTP error {code}',
    'rpc.jwtInvalid': {message: 'Invalid authentication ({message})', statusCode: 401},
    'rpc.oidcBadIssuer': {message: "OpenID issuer '{issuerId}' is not supported", statusCode: 401},
    'rpc.oidcEmpty': {message: 'OpenID returned empty response', statusCode: 401},
    'rpc.oidcHttp': {message: 'OpenID returned HTTP error {code}', statusCode: 401},
    'rpc.oidcNoIssuer': {message: 'Missing issuer in authentication token', statusCode: 401},
    'rpc.oidcNoKid': {message: 'Missing key id in JWT', statusCode: 401},
    'rpc.unauthorized': {
        message: 'Operation {method} is not allowed for this user',
        statusCode: 403,
    },
};
 
interface IConfig extends IConfigGatewayCodec {
    tls?: {ca?: string | string[]; key?: string; cert?: string; crl?: string};
    logLevel?: Parameters<ILog['logger']>[0];
    latency: number;
    debug: boolean;
}
export default class RpcClientImpl extends RemoteImpl implements IRpcClient {
    #config: IConfig = {
        latency: 50,
        debug: false,
    };
 
    #https: HttpsOptions;
    #gatewayCodec: IGatewayCodec;
    #resolution: IResolution;
    #errors: Errors<typeof errorMap>;
    #platform: IPlatformApi;
 
    public constructor(
        config: IConfig,
        {
            log,
            error,
            resolution,
            local,
            platform,
        }: {
            log: ILog;
            error: IErrorFactory;
            resolution: IResolution;
            local: ILocal;
            platform: IPlatformApi;
        },
    ) {
        super(config, {log, error, local, platform});
        config = this.merge(this.#config, config);
        this.#resolution = resolution;
        this.#platform = platform;
        this.#errors = error.register(errorMap);
        this.#https = tls(config, true) as unknown as HttpsOptions;
        this.#gatewayCodec = new GatewayCodecImpl(
            config,
            'http',
            '8091',
            this.#errors,
            this.sender('request'),
            this.#resolution,
        );
    }
 
    public verify(
        ...params: Parameters<IGatewayCodec['verify']>
    ): ReturnType<IGatewayCodec['verify']> {
        return this.#gatewayCodec.verify(...params);
    }
 
    public gateway(
        ...params: Parameters<IGatewayCodec['gateway']>
    ): ReturnType<IGatewayCodec['gateway']> {
        return this.#gatewayCodec.gateway(...params);
    }
 
    protected sender(
        methodType: 'request' | 'publish',
    ): (...params: unknown[]) => Promise<unknown> {
        return async (msg, ...rest) => {
            const callerMeta = rest.pop() as IMeta;
            const {stream, ...$meta} = callerMeta;
            const {encode, decode, requestParams} = await this.#gatewayCodec.codec(
                $meta,
                methodType,
            );
            const {params, headers, method = $meta.method} = await encode(msg, ...rest, $meta);
            const sendRequest = async (): Promise<unknown> => {
                try {
                    const response = await got.post<{
                        jsonrpc?: string;
                        error?: unknown;
                        validation?: unknown;
                        debug?: unknown;
                    }>(
                        `${requestParams.protocol}://${requestParams.hostname}:${requestParams.port}${requestParams.path}`,
                        {
                            https: this.#https,
                            followRedirect: false,
                            json: {
                                jsonrpc: '2.0',
                                method,
                                id: 1,
                                ...($meta.timeout &&
                                    $meta.timeout[0] && {
                                        timeout: this.#platform.timing.spare(
                                            $meta.timeout,
                                            this.#config.latency,
                                        ),
                                    }),
                                params,
                            },
                            responseType: 'json',
                            headers: {
                                'x-envoy-decorator-operation': method,
                                ...$meta.forward,
                                ...headers,
                            },
                        },
                    );
                    const {body} = response;
                    if (body?.error !== undefined) {
                        const error: IError = body.jsonrpc
                            ? Object.assign(new Error(), await decode(body.error, true))
                            : typeof body.error === 'string'
                              ? new Error(body.error)
                              : Object.assign(new Error(), body.error);
                        if (error.type)
                            Object.defineProperty(error, 'name', {
                                value: error.type,
                                configurable: true,
                                enumerable: false,
                            });
                        error.req = response.request && {
                            httpVersion: response.httpVersion,
                            url: response.request.requestUrl,
                            method: response.request.options.method,
                            ...(this.#config.debug && this.sanitize(params, $meta)),
                        };
                        error.res = {
                            httpVersion: response.httpVersion,
                            statusCode: response.statusCode,
                        };
                        throw error;
                    } else if (response.statusCode < 200 || response.statusCode >= 300) {
                        throw this.#errors['rpc.jsonRpcHttp']({
                            statusCode: response.statusCode,
                            // statusText: response.statusText,
                            statusMessage: response.statusMessage,
                            httpVersion: response.httpVersion,
                            validation: response.body?.validation,
                            debug: response.body?.debug,
                            params: {
                                code: response.statusCode,
                            },
                            ...(response.request && {
                                url: response.request.requestUrl,
                                method: response.request.options.method,
                            }),
                        });
                    } else if (typeof body === 'object' && 'result' in body && !('error' in body)) {
                        const result = await decode(body.result);
                        if (/\.service\.get$/.test(method!))
                            Object.assign((result as Record<string, unknown>[])[0], requestParams);
                        if ((body as unknown as {checkpoints?: unknown[]}).checkpoints?.length) {
                            ((callerMeta as {checkpoints?: unknown[]}).checkpoints ??= []).push(
                                ...(body as unknown as {checkpoints: unknown[]}).checkpoints,
                            );
                        }
                        return result;
                    } else {
                        throw this.#errors['rpc.jsonRpcEmpty']();
                    }
                } catch (error) {
                    const typedError = error as {code?: string; connect?: unknown};
                    if (this.#resolution && requestParams.cache) {
                        // invalidate cache and retry upon connection fail
                        switch (typedError.code) {
                            case 'ETIMEDOUT':
                            case 'ESOCKETTIMEDOUT':
                                if (!typedError.connect) break; // https://www.npmjs.com/package/request#timeouts
                            case 'ENOTFOUND':
                            case 'ECONNREFUSED':
                                Object.assign(
                                    requestParams,
                                    await this.#resolution.resolve(
                                        requestParams.cache,
                                        true,
                                        requestParams.namespace!,
                                    ),
                                );
                                delete requestParams.cache;
                                return sendRequest();
                        }
                    }
                    throw error;
                }
            };
            return stream ? [sendRequest()] : sendRequest();
        };
    }
}