All files / core/blong-gogo/src ApiGateway.ts

100% Statements 167/167
85.18% Branches 23/27
100% Functions 4/4
100% Lines 167/167

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 1681x 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 26x 26x 26x 26x 26x 26x 26x 26x 26x 1x 1x 1x 26x 26x 26x 26x 1x 1x 26x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 5x 7x 7x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 7x 7x 7x 7x 7x 7x 7x 3x 3x 7x 1x 1x 1x 1x 1x 3x 7x 3x 3x 3x 2x 2x 2x 2x 2x 3x 3x 3x 3x 3x 3x 3x 7x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 7x 7x 7x 7x 7x 7x 7x 7x 1x  
import type {IGateway, ILocal, ILog} from '@feasibleone/blong/types';
import {Internal} from '@feasibleone/blong/types';
import type {FastifyInstance, FastifyReply, FastifyRequest} from 'fastify';
import fp from 'fastify-plugin';
 
interface IConfig {
    /**
     * When false (default) the plugin registers nothing and is a no-op.
     */
    enabled: boolean;
    /**
     * Handler (semantic triple) that performs metering for a request.
     * It must accept `{bundle, creditCost}` and return
     * `{allowed, reason, creditsRemaining, rateLimit, rateCount, rateResetAt}`.
     */
    meterHandler: string;
    /**
     * HTTP status codes for each blocking reason.
     */
    statusCodes: {
        rate: number;
        credits: number;
        subscription: number;
    };
}
 
interface IGatewayWithPlugins extends IGateway {
    registerPlugin(plugin: unknown, options?: unknown): void;
}
 
interface IApiRef {
    log?: ILog;
    gateway?: IGatewayWithPlugins;
    local?: ILocal;
}
 
interface IMeterDecision {
    allowed: boolean;
    reason: 'ok' | 'rate' | 'credits' | 'subscription';
    creditsRemaining?: number;
    rateLimit?: number;
    rateCount?: number;
    rateResetAt?: number;
}
 
interface IRouteConfig {
    bundle?: string;
    creditCost?: number;
    meter?: boolean;
    methodName?: string;
}
 
export default class ApiGateway extends Internal {
    #config: IConfig = {
        enabled: false,
        meterHandler: 'gateway.meter.check',
        statusCodes: {
            rate: 429,
            credits: 429,
            subscription: 403,
        },
    };
 
    #apiRef: IApiRef;
 
    public constructor(config: IConfig, apiRef: IApiRef) {
        super({log: apiRef.log});
        this.merge(this.#config, config);
        this.#apiRef = apiRef;
    }
 
    public async init(): Promise<void> {
        if (!this.#config.enabled || !this.#apiRef.gateway) return;
 
        const config = this.#config;
        const apiRef = this.#apiRef;
        const [subject] = config.meterHandler.split('.');
        const reqName = `ports.${subject}.request`;
 
        const plugin = fp(
            async (server: FastifyInstance) => {
                // Runs AFTER the jwt plugin (auth + authorize). Metering is the
                // last gate before the route handler — it does NOT authorize.
                server.addHook(
                    'preHandler',
                    async (request: FastifyRequest, reply: FastifyReply) => {
                        const routeConfig = request.routeOptions?.config as
                            | IRouteConfig
                            | undefined;
                        // Opt-in per route: only routes that declare a `bundle`
                        // are metered.  `meter: false` opts a route out.
                        if (!routeConfig || routeConfig.bundle === undefined) return;
                        if (routeConfig.meter === false) return;
 
                        const handler = apiRef.local?.get(reqName);
                        if (!handler) {
                            request.log.error(
                                {meterHandler: config.meterHandler},
                                'gateway metering handler unavailable',
                            );
                            return reply.code(503).send({error: 'Service Unavailable'});
                        }
 
                        let result: IMeterDecision;
                        try {
                            const [res] = (await handler.method(
                                {
                                    bundle: routeConfig.bundle,
                                    creditCost: routeConfig.creditCost ?? 0,
                                },
                                {
                                    method: config.meterHandler,
                                    mtid: 'request',
                                    auth: request.auth?.credentials,
                                },
                            )) as [IMeterDecision, unknown];
                            result = res;
                        } catch (error) {
                            // Fail-closed: any metering error (e.g. Redis down)
                            // blocks the request with 503.
                            request.log.error({err: error}, 'gateway metering error');
                            return reply.code(503).send({error: 'Service Unavailable'});
                        }
 
                        if (result && typeof result === 'object') {
                            if (result.rateLimit !== undefined)
                                reply.header('X-RateLimit-Limit', String(result.rateLimit));
                            if (result.rateLimit !== undefined && result.rateCount !== undefined) {
                                reply.header(
                                    'X-RateLimit-Remaining',
                                    String(Math.max(0, result.rateLimit - result.rateCount)),
                                );
                            }
                            if (result.creditsRemaining !== undefined)
                                reply.header(
                                    'X-Credits-Remaining',
                                    String(result.creditsRemaining),
                                );
                        }
 
                        if (!result || result.allowed === false) {
                            const reason = result?.reason ?? 'subscription';
                            const status =
                                (config.statusCodes as Record<string, number>)[reason] ?? 429;
                            if (result?.rateResetAt)
                                reply.header(
                                    'Retry-After',
                                    String(
                                        Math.max(
                                            1,
                                            Math.ceil(result.rateResetAt - Date.now() / 1000),
                                        ),
                                    ),
                                );
                            return reply
                                .code(status)
                                .send({error: reason, message: `request ${reason} blocked`});
                        }
                    },
                );
            },
            {name: 'api-gateway'},
        );
 
        apiRef.gateway!.registerPlugin(plugin);
    }
}