All files / blong-gogo/src RpcServer.ts

72.22% Statements 117/162
92.3% Branches 12/13
58.33% Functions 7/12
72.22% Lines 117/162

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 1631x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 10x 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 1x 1x 242x 242x 242x 242x 242x 242x 242x 242x 242x                                                     242x 242x 224x 224x 224x 224x 224x 224x 224x 224x 224x 242x 242x 242x 242x 242x 1x 1x 192x 192x 192x 192x 192x 192x           192x 192x 242x 242x 242x 242x 242x 242x 242x 242x 242x 242x 192x 192x 1x 1x 10x 10x 1x 1x                 1x 1x     1x 1x 10x 10x 10x 10x 10x 10x 10x 1x 1x 10x 10x 10x 1x 1x         1x  
// import { DaprServer, CommunicationProtocolEnum } from '@dapr/dapr';
import {Internal, type ILog, type IMeta, type IRpcServer} from '@feasibleone/blong/types';
import fastify, {type FastifyReply, type FastifyRequest, type RouteOptions} from 'fastify';
 
import type {IResolution} from './Resolution.ts';
 
interface IConfig {
    port: number;
    host: string;
    logLevel: Parameters<ILog['logger']>[0];
}
export default class RpcServer extends Internal implements IRpcServer {
    #config: IConfig = {
        port: 8091,
        host: '0.0.0.0',
        logLevel: 'info',
    };
 
    // #dapr: DaprServer;
    #server: ReturnType<typeof fastify>;
    #routes: RouteOptions[] = [];
    #resolution: IResolution;
    #handlers: Map<string, {handle: RouteOptions['handler']}> = new Map();
    #attachCheckpoint?: (meta: IMeta) => void;
 
    public constructor(config: IConfig, {log, resolution}: {log: ILog; resolution: IResolution}) {
        // https://docs.dapr.io/developing-applications/sdks/js/js-server/
        // this.#dapr = new DaprServer({
        //     serverHost: '127.0.0.1',
        //     serverPort: '50051',
        //     communicationProtocol: CommunicationProtocolEnum.HTTP,
        //     clientOptions: {
        //         daprHost: '127.0.0.1',
        //         daprPort: '3500'
        //     }
        // });
        super({log});
        this.merge(this.#config, config);
        this.#resolution = resolution;
        this.#server = fastify({
            loggerInstance: log?.child({name: 'rpc'}, {level: this.#config.logLevel}),
        });
    }
 
    private _register(
        namespace: string,
        name: string,
        callback: () => unknown,
        object: object,
        _pkg: unknown,
    ): void {
        const url = `/rpc/${namespace}/${name.split('.').join('/')}`;
        const attachCheckpoint = this.#attachCheckpoint;
        async function handle(request: FastifyRequest, _reply: FastifyReply): Promise<object> {
            const {id, method, params} = request.body as {
                id: string;
                method: string;
                params: object[];
            };
            const meta = params.pop();
            const newMeta = {
                ...meta,
                method,
                // forward: forward(request.headers),
                opcode: method.split('.').pop(),
            };
            attachCheckpoint?.(newMeta as IMeta);
            const result = await (callback as (...args: unknown[]) => Promise<unknown>).apply(
                object,
                [...params, newMeta],
            );
            return {
                jsonrpc: '2.0',
                id,
                result,
                ...((newMeta as {checkpoints?: unknown[]}).checkpoints?.length && {
                    checkpoints: (newMeta as {checkpoints?: unknown[]}).checkpoints,
                }),
            };
        }
        const prevHandler = this.#handlers.get(url);
        if (prevHandler) prevHandler.handle = handle;
        else {
            const handler = {handle};
            this.#handlers.set(url, handler);
            this.#routes.push({
                method: 'post',
                url,
                handler: (request, reply) => handler.handle(request, reply),
            });
        }
        this.#resolution?.announce(
            'rpc-' + name.split('.')[0].replace(/\//g, '-'),
            this.#config.port,
        );
    }
 
    public register(
        methods: object,
        namespace: string,
        reply: boolean,
        pkg: {version: string},
    ): void {
        if (methods instanceof Array) {
            methods.forEach(fn => {
                if (fn instanceof Function && fn.name) {
                    this._register(namespace, fn.name, fn, null as unknown as object, pkg);
                }
            });
        } else {
            Object.keys(methods).forEach(key => {
                if ((methods as Record<string, unknown>)[key] instanceof Function) {
                    this._register(
                        namespace,
                        key,
                        (methods as Record<string, unknown>)[key] as () => unknown,
                        methods,
                        pkg,
                    );
                }
            });
        }
    }
 
    public setAttachCheckpoint(fn: ((meta: IMeta) => void) | undefined): void {
        this.#attachCheckpoint = fn;
    }
 
    private _unregister(namespace: string, name: string): void {
        const url = `/rpc/${namespace}/${name.split('.').join('/')}`;
        const prevHandler = this.#handlers.get(url);
        if (prevHandler) {
            prevHandler.handle = (request, reply) => {
                return reply.code(404).type('text/plain').send('route removed');
            };
        }
    }
 
    public unregister(methods: string[], namespace: string): void {
        methods.forEach(fn => this._unregister(namespace, fn));
    }
 
    public async start(): Promise<IRpcServer> {
        this.#routes.forEach(route => this.#server.route(route));
        await this.#server.listen({
            port: this.#config.port,
            host: this.#config.host,
        });
        return this;
    }
 
    public async stop(): Promise<IRpcServer> {
        await this.#server.close();
        return this;
    }
 
    public info(): object {
        return {
            address: this.#server.server.address(),
        };
    }
}