@gravity-ui/出入口 #

一个灵活而强大的Express控制器,用于在Node.js应用程序中与REST和gRPC API合作.
目录
安装
npm install --save @gravity-ui/gateway
基本用途
首先,通过导入网关和您的 API 计划创建控制器 :
import {getGatewayControllers} from '@gravity-ui/gateway';
import Schema from '<schemas package>';
const config = {
installation: 'external',
env: 'production',
includeProtoRoots: ['...'],
};
const {controller: gatewayController} = getGatewayControllers({root: Schema}, config);
export default gatewayController;
然后,将控制器连接到您的快递路线(使用 表达式:
{
'POST /<prefix>/:scope/:service/:action': {target: '<controller>', afterAuth: ['credentials']}
}
这个 prefix 可以是 API 端点的任何前缀(例如, /gateway/:service/:action) (中文(简体) ).
配置
import {AxiosRequestConfig} from 'axios';
import {IncomingHttpHeaders} from 'http';
import {IAxiosRetryConfig} from 'axios-retry';
interface OnUnknownActionData {
service?: string;
action?: string;
}
interface Stats {
service: string;
action: string;
restStatus: number;
grpcStatus?: number;
responseSize: number;
requestId: string;
requestTime: number;
requestMethod: string;
requestUrl: string;
timestamp: number;
userId?: string;
traceId: string;
}
type SendStats = (
stats: Stats,
headers: IncomingHttpHeaders,
ctx: CoreContext,
meta: {debugHeaders: Headers},
) => void;
type GrpcRetryCondition = (error: ServiceError) => boolean;
type AxiosRetryCondition = IAxiosRetryConfig['retryCondition'];
type ControllerType = 'rest' | 'grpc';
type ProxyHeadersFunctionExtra = {
service: string;
action: string;
protopath?: string;
protokey?: string;
};
type ProxyHeadersFunction = (
headers: IncomingHttpHeaders,
type: ControllerType,
extra: ProxyHeadersFunctionExtra,
) => IncomingHttpHeaders;
type ProxyHeaders = string[] | ProxyHeadersFunction;
type ResponseContentType = AxiosResponse['headers']['Content-Type'];
type GetAuthHeadersParams<AuthArgs = Record<string, unknown>> = {
actionType: ControllerType;
serviceName: string;
requestHeaders: Headers;
authArgs: AuthArgs | undefined;
};
interface AppErrorArgs {
code?: string | number;
details?: object;
debug?: object;
}
interface AppErrorWrapArgs extends AppErrorArgs {
message?: string;
}
interface AppErrorConstructor {
new (message?: string, args?: AppErrorArgs): Error;
wrap: (error: Error, args?: AppErrorWrapArgs) => Error;
}
interface GatewayConfig {
// Gateway Installation (external/internal/...). If not provided, determined from process.env.APP_INSTALLATION.
installation?: string;
// Gateway Environment (production/testing/...). If not provided, determined from process.env.APP_ENV.
env?: string;
// Additional gRPC client options.
grpcOptions?: object;
// Additional Axios client options.
axiosConfig?: AxiosRequestConfig;
// List of actions to connect from the schema. By default, all actions are connected.
actions?: string[];
// Called when an unknown service or action is provided.
onUnknownAction?: (req: Request, res: Response, data: OnUnknownActionData) => any;
// Called before the request is executed.
// Return {responseData, responseHeaders?, debugHeaders?} to skip the action and send responseData
// as a regular successful response (onRequestSuccess is still called). Throw to fail the request:
// the thrown value is sent as the error body with its `status` (500 by default).
onBeforeAction?: (
req: Request,
res: Response,
scope: string,
service: string,
action: string,
config?: ApiServiceActionConfig,
) => any;
// Called upon successful completion of the request.
onRequestSuccess?: (req: Request, res: Response, data: any) => any;
// Called in case of unsuccessful request execution.
onRequestFailed?: (req: Request, res: Response, error: any) => any;
// List of paths to the necessary proto files for the gateway.
includeProtoRoots?: string[];
// Configuration of the path to the CA certificate in gRPC.
// Set to null to use system certificates by default.
caCertificatePath?: string | null;
// Configuration of the path to the client certificate for mTLS in gRPC.
clientCertificatePath?: string | null;
// Configuration of the path to the client private key for mTLS in gRPC.
clientKeyPath?: string | null;
// Telemetry sending configuration.
sendStats?: SendStats;
// Configuration of headers sent to the API.
proxyHeaders?: ProxyHeaders;
// When passing a boolean value, it enables/disables debug headers in the response to the request.
// For unary requests to gRPC backends, debug headers will include information from the trailing metadata returned by the backend.
withDebugHeaders?: boolean | ((req: Request, res: Response) => boolean);
// Validation schema for parameters used when no schema is present in the action.
// You can use DEFAULT_VALIDATION_SCHEMA from lib/constants.ts.
validationSchema?: object;
// Enables encoding of REST path arguments (default is true).
encodePathArgs?: boolean;
// Configuration for automatic connection re-establishment upon connection error through L3 load balancer (default is true).
grpcRecreateService?: boolean;
// Customize retry behavior for grpc requests
grpcRetryCondition?: GrpcRetryCondition;
// Customize retry behavior for rest (axios) requests
axiosRetryCondition?: AxiosRetryCondition;
// Enable verification of response contentType header. Actual only for REST actions.
// This value can be set/redefined in the action config.
expectedResponseContentType?: ResponseContentType | ResponseContentType[];
// Function to get authentication arguments for API requests
getAuthArgs: (req: Request, res: Response) => Record<string, unknown> | undefined;
// Function to get authentication headers for API requests
getAuthHeaders: (params: GetAuthHeadersParams) => Record<string, string> | undefined;
// Error constructor for handling errors
ErrorConstructor: AppErrorConstructor;
// Axios interceptors configuration
axiosInterceptors?: AxiosInterceptorsConfig;
}
proxyHeaders
GatewayConfig.proxyHeaders 是一种可选方法, 允许为整个请求设置标题 gateway 级别 :
const proxyHeaders = (headers, actionType, extra) => {
const normalizedHeaders = {...headers};
const {service, action, protopath, protokey} = extra;
if (actionType === 'rest' && service === 'mail') {
normalizedHeaders['x-mail-service-action'] = action;
}
return normalizedHeaders;
};
const {controller: gatewayController} = getGatewayControllers(
{root: Schema},
{...config, proxyHeaders},
);
这个 extra 参数包含关于请求的更多信息:
service: 服务名称action: 动作名称protopath: 原生路径(用于 gRPC 动作)protokey: 原型密钥(用于GRPC动作)
在访问信头时,网关会首先尝试用用户提供的确切大小写来获取信头. 如果信头与该确切的大小写不存在,那么它就回到小写中寻找同名标题. 这种行为确保了与各种HTTP客户端的相容性,这些客户端可能发送不同外壳的头像.
您可以使用 ApiServiceBaseActionConfig.proxyHeaders数字 :
const schema = {
userService: {
serviceName: 'users',
endpoints: {...},
actions: {
getProfile: {
path: () => '/profile',
method: 'GET',
proxyHeaders: (headers) => ({...headers, ['x-users-service-action']: 'get-profile'}),
},
},
},
};
这个 GatewayConfig.proxyHeaders 财务报告和审定财务报表 ApiServiceBaseActionConfig.proxyHeaders 当动作被调用时合并。 合并标题的战略没有保障.
建议使用 GatewayConfig.proxyHeaders 用于指定整个应用程序或大量动作共有的标题。 否则,最好使用 ApiServiceBaseActionConfig.proxyHeaders。 。 。 .
验证Schema
默认情况下,对于 REST 动作中的路径参数,使用以下正则exp : /^((?!(\.\.|\?|#|\\|\/)).)*$/i。 。 。 .
如果参数值没有通过验证,则请求以状态被拒绝 400 代码 INVALID_PARAMS。错误细节包含标题 Invalid path params 和第一个无效参数的路径 description (例如, items[0].id) (中文(简体) ). 不向上游服务机构发送请求.
你可以用这个 DEFAULT_VALIDATION_SCHEMA 从 lib/constants.ts 作为起点:
export const DEFAULT_VALIDATION_SCHEMA = {
additionalProperties: {
oneOf: [
{
type: 'number',
},
{
type: 'string',
pattern: '^((?!(\\.\\.|\\?|#|\\\\|\\/)).)*$',
},
{
type: 'object',
},
],
},
};
使用节点.js中的 API
除了快递控制器外,该网关还输出一个 api 对后端服务直接请求的对象 :
import {getGatewayControllers} from '@gravity-ui/gateway';
import Schema from '<schemas package>';
const config = {
installation: 'external',
env: 'production',
includeProtoRoots: ['...'],
timeout: 25000, // default 25 seconds
caCertificatePath: '...',
// Optional: paths for mTLS client certificate and key
clientCertificatePath: '...',
clientKeyPath: '...',
};
const {api: gatewayApi} = getGatewayControllers({root: Schema}, config);
// Use the API to make requests
const result = await gatewayApi.serviceName.actionName({
authArgs: {token: 'auth-token'},
requestId: '123',
headers: {},
args: {param1: 'value1'},
ctx: context,
});
这个 actionConfig 参数的结构如下:
interface ApiActionConfig<Context, TRequestData> {
requestId: string;
headers: Headers;
args: TRequestData;
ctx: Context;
timeout?: number;
callback?: (response: TResponseData) => void;
authArgs?: Record<string, unknown>;
userId?: string;
abortSignal?: AbortSignal;
}
Schema 范围
每个计划都属于自己的命名空间. 服务与行动名称在计划之间是完全独立的,可以相通. 每个范围都有独立的gRPC上下文,它消除了原生文件中的chemas之间的命名冲突.
瞄准镜名称是包含计数对象的第一个参数中的密钥:
const schemasByScopes = {scope1: schema1, scope2: schema2};
有两个范围命名空间的示例: root 财务报告和审定财务报表 anotherScope数字 :
import {getGatewayControllers} from '@gravity-ui/gateway';
const {
controller, // Controller
api, // API (for Node.js environment)
} = getGatewayControllers({root: rootSchema, anotherScope: anotherSchema}, config);
// API calls are made by specifying the scope
const resultFromRoot = api.root.rootService.rootAction(params);
const resultFromAnother = api.anotherScope.anotherService.anotherAction(params);
有一个特殊的范围叫 root在不明确说明其范围的情况下可以援引其方法:
const resultFromRoot = api.root.rootService.rootAction(params);
// Same result
const sameResultFromRoot = api.rootService.rootAction(params);
速记控制器也会期望 :scope 参数。 如果未指定范围参数,默认范围假定为 root。 。 。 .
{
'POST /<prefix>/:scope/:service/:action': gatewayController
}
连接特定动作
您可以使用 actions 字段中的字段。 如果未提供动作,则默认会连接所有来自计划的行动.
import {getGatewayControllers} from '@gravity-ui/gateway';
import rootSchema from '<schemas package>';
import localSchema from '../shared/schemas';
const config = {
installation: 'external',
env: 'production',
includeProtoRoots: ['...'],
actions: [
'local.*', // All actions from the 'local' scope
'root.serviceA.*', // All actions from 'serviceA' in the 'root' scope
'root.serviceB.getUser', // Only the 'getUser' action from 'serviceB' in the 'root' scope
],
};
const {api: gatewayApi} = getGatewayControllers({root: rootSchema, local: localSchema}, config);
指定行动的现有模式:
<scope>.*- 来自指定范围的所有行动<scope>.<service>.*- 来自指定服务的所有动作<scope>.<service>.<action>- 只有指定的动作
说明: 此配置仅会影响客户端访问. 所有动作在服务器一侧仍可访问 .
覆盖终点
您可以使用 GATEWAY_ENDPOINTS_OVERRIDES 环境变量。 这对于测试环境是有用的.
示例格式 :
GATEWAY_ENDPOINTS_OVERRIDES = JSON.stringify({
serviceName: {
endpoint: 'https://example.com',
},
'example.exampleService': {
endpoint: 'https://overrided.example.com',
},
});
认证
网关支持通过 getAuthArgs 财务报告和审定财务报表 getAuthHeaders 配置选项 :
const config = {
// ...other config options
// Get authentication arguments for request
getAuthArgs: (req, res) => ({
token: req.authorization.token,
}),
// Generate authentication headers for backend requests
getAuthHeaders: (params) => {
if (!params?.token) return undefined;
return {
Authorization: `Bearer ${params.token}`,
};
},
};
您可以在三个级别上定义认证: |
- 网关级别 (全球)-如上所示
- 服务级别 - 在服务定义中增加认证方法
- 行动层面 (最具体的) - 在单个动作中添加认证方法 | 认证方法按以下顺序检查: 动作 > 服务 > 网关. | 服务级认证 : |
const schema = {
userService: {
serviceName: 'users',
endpoints: {...},
// Service-level authentication
getAuthHeaders: (params) => ({
'X-User-Service-Auth': params.token,
}),
getAuthArgs: (req, res) => ({
token: req.authorization.token,
serviceSpecificData: req.headers['x-service-data'],
}),
actions: {
getProfile: {
path: () => '/profile',
method: 'GET',
// Uses service-level authentication
},
updateProfile: {
path: () => '/profile',
method: 'PUT',
// Action-level authentication (overrides service-level)
getAuthHeaders: (params) => ({
'X-Special-Auth': params.token,
}),
},
},
},
};
处理错误
网关提供了几种处理错误的方法:
- 错误构建器 通过
ErrorConstructor(重排字段) 配置选项 :
class CustomError extends Error {
constructor(message, options = {}) {
super(message);
this.name = 'CustomError';
this.code = options.code || 'UNKNOWN_ERROR';
this.status = options.status || 500;
this.details = options.details;
}
static wrap(error) {
if (error instanceof CustomError) return error;
return new CustomError(error.message, {
code: error.code || 'INTERNAL_ERROR',
status: error.status || 500,
});
}
}
const config = {
// ...other config options
ErrorConstructor: CustomError,
};
- 自定义请求错误处理 通过
onRequestFailed配置选项 :
const config = {
// ...other config options
onRequestFailed: (req, res, error) => {
console.error('Request failed:', error);
return res.status(error.status || 500).json({
error: error.message,
code: error.code,
});
},
};
- 未关闭
params错误: 如果一个动作定义了params处理器和它扔出,请求以状态被拒绝500代码GETTING_PARAMS_FAILED;上游服务不叫. 行动不包含params处理器不受影响.
可重试错误
REST行动
这个 默认 rEST-Action的再试验条件包括下列条件:
- 网络出错( 由
axiosRetry.isNetworkError(中文(简体) ) - HTTP 429和5xx的答复(由
axiosRetry.isRetryableError)),包括请求《波恩协定》
默认已禁用复读 。 设定 retries 在动作计划或API呼叫中允许它们.
值是附加尝试的次数 : retries: 2 允许最多三次请求.
复数使用指数回放与焦急并尊重 Retry-After 响应头, 表示
作为秒或 HTTP 日期。 超时涵盖所有尝试并重试延迟; 如果不够的话
下一次重试所剩时间, 请求会因最后一个错误而失败 .
复用原请求正文. 部分或全部消耗的可读流
无法自动重放, 因此重试可能发送不完整或空的正文 。 设定 retries: 0
请求使用一发子弹的流体.
您可以使用 axiosRetryCondition 配置选项 :
const config = {
// ...other config options
axiosRetryCondition: (error) => {
// Custom logic to determine if the request should be retried
return error.code === 'TIMEOUT';
},
};
您也可以在动作关卡设置重试条件 。 行动的条件高于
全球状况。 自定义条件取代默认条件, 因此返回 false (单位:千美元)
防止重试 HTTP 429 和 5xx 回复 :
const schema = {
userService: {
serviceName: 'users',
endpoints: {...},
actions: {
getProfile: {
path: () => '/profile',
method: 'GET',
retries: 2,
axiosRetryCondition: (error) => {
// Custom logic for this specific action
return error.code === 'ECONNRESET';
},
},
},
},
};
gRPC-行动
这个 默认 gRPC-动作的再试条件包括某些gRPC状态代码:
UNAVAILABLECANCELLEDABORTEDUNKNOWN
您可以使用 grpcRetryCondition 配置选项 :
const config = {
// ...other config options
grpcRetryCondition: (error) => {
// Custom logic to determine if the request should be retried
return error.code === 'RESOURCE_EXHAUSTED';
},
};
图书馆输出 isRetryableGrpcError 函数,用于检查 gRPC 错误根据默认条件是否可以重试 :
import {isRetryableGrpcError} from '@gravity-ui/gateway';
// Use in your custom retry condition
const customGrpcRetryCondition = (error) => {
return isRetryableGrpcError(error) || error.code === 'RESOURCE_EXHAUSTED';
};
除非配置选项 grpcRecreateService 设置为 false,当可能断开时,服务连接被重新创建:
- 请求因连接出错而失败( q)
UNAVAILABLE, (中文(简体) ),CANCELLED, (中文(简体) ),ABORTED, (中文(简体) ),UNKNOWN或者说DEADLINE_EXCEEDED) 频道处于断裂状态(CONNECTING, (中文(简体) ),TRANSIENT_FAILURE或者说SHUTDOWN) ——连接在再试之前被重新创建,因此再试不会再用被卡住的通道; - 请求失败
DEADLINE_EXCEEDED当频道是READY(最后期限最有可能由慢后端所造成)——只有在所有回覆被耗尽后才能重新创建连接.
请求取消
当客户端断开时, 网关支持取消请求 。 这对长期运行的操作有用,因为如果客户端不再等待响应,您想要避免不必要的处理.
对导出控制器默认启用此特性 。 API 请求时,您可以通过 AbortSignal 取消请求:
const abortController = new AbortController();
const result = await gatewayApi.serviceName.actionName({
authArgs: {token: 'auth-token'},
requestId: '123',
headers: {},
args: {param1: 'value1'},
ctx: context,
abortSignal: abortController.signal,
});
您也可以使用 abortOnClientDisconnect 选项 :
const schema = {
userService: {
serviceName: 'users',
endpoints: {...},
actions: {
longRunningOperation: {
path: () => '/process',
method: 'POST',
abortOnClientDisconnect: true, // Enable cancellation for this action
},
},
},
};
答复来自 onBeforeAction
onBeforeAction 可以回答一个请求而不是动作,例如为模拟服务. 返回时 createBeforeActionResponse({responseData, responseHeaders?, debugHeaders?}):动作不叫,数据通过正则成功路径 - 页眉被设定, onRequestSuccess 如果配置,则调用,否则数据会以状态200发送。 任何其他返回值,包括 undefined 或普通对象为 responseData,保留默认行为.
后端在此情况下不调用,所以动作的参数验证, getAuthArgs, (中文(简体) ), sendStats 而后端自己的授权和所有权检查也没有运行. 访问检查要靠钩子:在那里决定谁可以得到这种答复,例如,只为工作人员用户或外部制作服务.
要失败请求, 扔出: 抛出值会通过正则错误路径, 并随其作为响应机构发送 status (默认500美元),或转至 onRequestFailed。 。 。 .
import {createBeforeActionResponse} from '@gravity-ui/gateway';
const config = {
onBeforeAction: (req, res, scope, service, action) => {
if (service === 'users' && action === 'getUser') {
return createBeforeActionResponse({
responseData: {id: '1', name: 'Mock'},
responseHeaders: {'x-mock': 'users.getUser'},
});
}
if (service === 'users' && action === 'deleteUser') {
throw {
status: 403,
code: 'GATEWAY_REQUEST_ERROR',
message: 'Permission denied',
details: {grpcCode: 7},
};
}
return undefined;
},
};
响应内容类型验证
对于 REST 动作,您可以验证响应的内容类型,以确保它符合您的预期. 这有利于确保API返回预期格式.
您可以在网关级别设置预期内容类型 :
const config = {
// ...other config options
expectedResponseContentType: 'application/json',
};
在行动层面:
const schema = {
userService: {
serviceName: 'users',
endpoints: {...},
actions: {
getProfile: {
path: () => '/profile',
method: 'GET',
expectedResponseContentType: 'application/json',
},
getDocument: {
path: () => '/document',
method: 'GET',
expectedResponseContentType: ['application/pdf', 'application/octet-stream'],
},
},
},
};
您可以指定一个单一内容类型或一组可接受的内容类型。 如果响应内容类型与任何预期类型不相匹配,则会出错.
流出REST回复
设定 responseType: 'stream' 作为可读流的节点Js接收上游反应机构。 默认控制器在客户端到达时会对这些响应进行管道处理,而不是缓冲. 使用 proxyResponseHeaders ưμ㼯a Content-Type。 。 。 .
const schema = {
events: {
serviceName: 'events',
endpoints: {production: 'https://events.example.com'},
actions: {
subscribe: {
method: 'GET',
path: () => '/subscribe',
responseType: 'stream',
abortOnClientDisconnect: true,
proxyResponseHeaders: ['content-type'],
},
},
},
};
如果上游流中响应失败,则客户端连接被关闭并被记录出错误. 何时 onRequestSuccess 被设定,它接收了溪流 并负责管道它 res。 。 。 .
gRPC 响应大小计算
对于无效的 gRPC 动作, 网关会计算 responseSize 页:1 sendStats 使用 object-sizeof,这对JSON的解码响应进行序列化,可以为大型响应增加大量处理时间.
设定 calculateResponseSize: false 在不需要大小统计时跳过此计算时的动作 :
const schema = {
exportService: {
serviceName: 'exports',
endpoints: {...},
actions: {
getExport: {
protoPath: 'exports/v1/export_service.proto',
protoKey: 'exports.v1.ExportService',
action: 'GetExport',
calculateResponseSize: false,
},
},
},
};
选项默认为 true。当禁用时,仍然会引用成功的无线电话 sendStats不过 responseSize 实值 0 以表示未计算大小。 反应数据和信头不变. 此选项同时与原生文件和反射同时工作,不影响流调或出错统计.
gRPC 对 gRPC 动作的反思
与其使用gRPC proto文件,不如使用gRPC反射来确定服务和方法的结构.
先决条件:
-
安装
grpc-reflection-js软件包 :npm install --save grpc-reflection-js -
将补丁应用到
protobufjs库 :- 添加
npx gateway-reflection-patch到您的项目postinstall剧本. 这假设了原生地取自于节点-模块的根. - 从库的补丁文件夹复制到您的工程根并安装 补丁包中添加补丁包命令
postinstall剧本. 在这种情况下,在更新时需要注意网关中补丁的更新.
- 添加
如果在 Docker 构建过程中遇到“ 无法在 wd 中运行 [......] ” 错误, 您可以添加不安全的- perm = true 到您的. npmrc 文件 .
-
配置您的动作以使用反射 :
import {GrpcReflection} from '@gravity-ui/gateway'; const schema = { userService: { serviceName: 'users', endpoints: {...}, actions: { getUser: { protoKey: 'users.v1.UserService', action: 'GetUser', reflection: GrpcReflection.OnFirstRequest, // Optional: refresh reflection cache every 3600 seconds (1 hour) reflectionRefreshSec: 3600, }, }, }, };
反射选项 :
GrpcReflection.OnFirstRequest- 对第一个请求进行反思。 使用缓存反射 .GrpcReflection.OnEveryRequest- 在每次请求前进行反思。 不要使用缓存反射 .
给 OnFirstRequest 选项 reflectionRefreshSec 参数,这表示反射缓存在秒后在背景中可以多久更新一次. 缓存更新同步发生, 不要屏蔽当前请求 。 初始的反射请求带有空缓存可能会给请求带来一些延迟.
特殊性
反射的缓存密钥包括 protoKey 财务报告和审定财务报表 endpoint因此,带有共享密钥的动作将使用一个共同的缓存版本,该版本将从最早的情景中获得(当第一个动作请求与 OnFirstRequest 战略已经制定).
此功能为实验. 已对 protobufjs 使用 补丁包 基于下列公关协议:
- 参数名称转换为骆驼Case 1073卢比
- 处理地图的修复 PR 1478 (英语) grpc-reflection-js 也被补丁支持自定义选项.
要开发, 您需要使用命令在本地应用补丁 npx patch-package。 。 。 .
频道证书类型错配错误
此错误可能因安装重复而发生 @grpc/grpc-js 图书馆。 建议确保这个图书馆的所有版本都一致并一致地避免这个问题.
发展
运行测试
# Run unit tests
npm test
# Run integration tests
npm run test-integration
捐款
欢迎捐款! 请看 捐款额 详细情况.
许可证
麻省理工学院