imean-service-engine
Version:
microservice engine
418 lines (402 loc) • 11.8 kB
text/typescript
import { z } from 'zod';
export * from 'zod';
import { Redis, Cluster } from 'ioredis';
import { LRUCache } from 'lru-cache';
import { Lease, Etcd3 } from 'etcd3';
import { MiddlewareHandler, Context, Hono } from 'hono';
export { default as dayjs } from 'dayjs';
import winston from 'winston';
import * as hono_utils_html from 'hono/utils/html';
import * as hono_jsx_jsx_dev_runtime from 'hono/jsx/jsx-dev-runtime';
declare abstract class CacheAdapter {
abstract get(key: string): Promise<any>;
abstract set(key: string, value: any, ttl: number): Promise<any>;
}
declare class RedisCacheAdapter extends CacheAdapter {
private readonly redis;
constructor(redis: Redis | Cluster);
get(key: string): Promise<any>;
set(key: string, value: string, ttl: number): Promise<"OK">;
}
declare class MemoryCacheAdapter extends CacheAdapter {
private cache;
constructor(options?: LRUCache.Options<string, any, any>);
get(key: string): Promise<any>;
set(key: string, value: any, ttl: number): Promise<void>;
}
type CacheFn = (...args: any[]) => any;
interface ActionOptions {
params?: z.ZodType<any>[];
returns?: z.ZodType<any>;
idempotence?: boolean;
description?: string;
printError?: boolean;
cache?: boolean | CacheFn;
ttl?: number;
stream?: boolean;
}
interface PageOptions {
method?: "get" | "post" | "put" | "delete" | "patch" | "options";
middlewares?: MiddlewareHandler[];
path: string | string[];
absolutePath?: boolean;
description?: string;
}
interface PageMetadata extends PageOptions {
name: string;
method: "get" | "post" | "put" | "delete" | "patch" | "options";
}
interface ActionMetadata extends ActionOptions {
name: string;
idempotence: boolean;
cache?: boolean | CacheFn;
ttl?: number;
stream?: boolean;
}
interface ModuleOptions {
/** 模块名称 */
name?: string;
/** 模块版本 */
version?: string;
/** 模块描述 */
description?: string;
/** 打印错误 */
printError?: boolean;
}
interface ModuleMetadata {
name: string;
options: Required<ModuleOptions>;
}
declare enum ScheduleMode {
/** 固定间隔触发,不管上次任务是否完成 */
FIXED_RATE = "FIXED_RATE",
/** 任务完成后再等待间隔时间,再执行下一次 */
FIXED_DELAY = "FIXED_DELAY"
}
interface ScheduleOptions {
/** 执行间隔(毫秒) */
interval: number;
/** 调度模式 */
mode?: ScheduleMode;
}
interface ScheduleMetadata extends ScheduleOptions {
name: string;
electionKey: string;
}
interface EtcdConfig {
hosts: string[];
auth?: {
username: string;
password: string;
};
/** 服务注册的 TTL,默认 10 秒 */
ttl?: number;
/** etcd 的命名空间 */
namespace?: string;
}
interface ServiceStats {
totalCalls: number;
successCalls: number;
failureCalls: number;
avgResponseTime: number;
maxResponseTime: number;
minResponseTime: number;
lastUpdateTime: number;
cacheHit: number;
}
interface StatisticsEventOptions {
/** 统计事件触发间隔,默认 5 秒 */
interval?: number;
/** 是否在服务停止时强制触发未发送的统计事件 */
forceEmitOnShutdown?: boolean;
}
interface ServiceInfo {
id: string;
name: string;
version?: string;
prefix?: string;
env?: string;
modules: Record<string, ModuleInfo>;
}
interface EventServiceInfo {
id: string;
name: string;
version?: string;
env?: string;
}
interface StatisticsEvent {
service: EventServiceInfo;
module: string;
action: string;
stats: ServiceStats;
startTime: number;
endTime: number;
}
interface ActionErrorEvent {
service: EventServiceInfo;
module: string;
action: string;
requestHash: string;
params: any[];
time: number;
error: string;
}
interface MicroserviceOptions {
name?: string;
version?: string;
prefix?: string;
env?: string;
printError?: boolean;
disableCache?: boolean;
modules: (new () => any)[];
generateClient?: URL | boolean;
etcd?: EtcdConfig | false;
events?: StatisticsEventOptions & {
onStats?: (event: StatisticsEvent) => void | Promise<void>;
onRegister?: (serviceInfo: ServiceInfo) => void | Promise<void>;
onError?: (event: ActionErrorEvent) => void | Promise<void>;
};
websocket?: {
enabled?: boolean;
timeout?: number;
};
cacheAdapter?: CacheAdapter;
plugins?: Plugin[];
gracefulShutdown?: {
/** 优雅停机超时时间(毫秒),默认 30 秒 */
timeout?: number;
/** 清理hook列表 */
cleanupHooks?: CleanupHook[];
};
}
interface CleanupHook {
/** hook名称 */
name: string;
/** 清理函数 */
cleanup: () => Promise<void> | void;
/** 超时时间(毫秒),默认 5 秒 */
timeout?: number;
}
interface RequestInfo {
/** 请求ID */
id: string;
/** 模块名称 */
moduleName: string;
/** 动作名称 */
actionName: string;
/** 开始时间 */
startTime: number;
/** 请求参数 */
params?: any;
}
interface ModuleInfo extends ModuleOptions {
actions: Record<string, ActionMetadata>;
name: string;
}
interface StreamResponse<T = any> {
value?: T;
done: boolean;
error?: string;
}
declare abstract class Plugin {
abstract initialize(engine: Microservice): Promise<void>;
}
declare class ActionHandler {
private moduleInstance;
private actionName;
metadata: ActionMetadata;
private microservice;
private moduleName;
constructor(moduleInstance: any, actionName: string, metadata: ActionMetadata, microservice: Microservice, moduleName: string);
handle(req: string | any[], ctx: Context): Promise<any>;
private _validate;
private _handle;
}
declare const ServiceContext: {
service?: Microservice;
lease?: Lease;
etcdClient?: Etcd3;
};
declare class Microservice {
private app;
private nodeWebSocket;
private codeCache?;
private waitingInitialization;
private etcdClient?;
private serviceKey?;
private statsMap;
private lease?;
private scheduler?;
private abortController?;
private statisticsTimer?;
private wsHandler?;
private actionHandlers;
private pageHandlers;
private activeRequests;
private status;
modules: Map<string, ModuleInfo>;
readonly fetch: typeof fetch;
options: Required<MicroserviceOptions>;
cache: CacheAdapter;
serviceId: string;
constructor(options: MicroserviceOptions);
private initialize;
private initModules;
private initRoutes;
private generateClientCode;
private clientCode;
private initEtcd;
/**
* 注册服务
*/
private registerService;
/**
* 更新方法统计信息
*/
updateMethodStats(moduleName: string, methodName: string, responseTime: number, success: boolean, cacheHit?: boolean): void;
/**
* 获取 Hono 应用实例
*/
getApp(): Hono;
/**
* 启动服务
*/
start(port?: number, silent?: boolean): Promise<void>;
/**
* 获取所有模块的元数据
*/
getModules(withTypes?: boolean): Record<string, ModuleInfo>;
/**
* 停止服务
*/
private stop;
/**
* 初始化停机处理
*/
private initShutdownHandlers;
/**
* 优雅停机
*/
shutdown(): Promise<void>;
/**
* 等待所有活跃请求完成
*/
private waitForActiveRequests;
/**
* 执行清理hook
*/
private executeCleanupHooks;
private initStatsEventManager;
private updateStats;
getActionHandler(moduleName: string, actionName: string): ActionHandler;
/**
* 添加活跃请求跟踪
*/
private addActiveRequest;
/**
* 移除活跃请求跟踪
*/
private removeActiveRequest;
/**
* 获取当前活跃请求数量
*/
getActiveRequestCount(): number;
/**
* 获取当前活跃请求信息
*/
getActiveRequests(): RequestInfo[];
private handleRequest;
private initPlugins;
init(): Promise<void>;
}
declare const BaseLayout: (props?: {
children?: any;
title?: string;
heads?: any;
}) => hono_utils_html.HtmlEscapedString | Promise<hono_utils_html.HtmlEscapedString>;
declare const HtmxLayout: (props?: {
children?: any;
title: string;
favicon?: any;
}) => hono_utils_html.HtmlEscapedString | Promise<hono_utils_html.HtmlEscapedString>;
declare const ServiceInfoCards: ({ serviceInfo, }: {
serviceInfo: ServiceInfo;
}) => hono_jsx_jsx_dev_runtime.JSX.Element;
declare const ServiceStatusPage: ({ serviceInfo, }: {
serviceInfo: ServiceInfo;
}) => hono_jsx_jsx_dev_runtime.JSX.Element;
interface PageRenderPluginOptions {
useDefaultStatusPage?: boolean;
}
declare class PageRenderPlugin extends Plugin {
private readonly options;
constructor(options?: PageRenderPluginOptions);
initialize: (engine: Microservice) => Promise<void>;
}
interface PreStartChecker {
name: string;
check: () => Promise<void> | void;
skip?: boolean;
}
declare function startCheck(checkers: PreStartChecker[], pass?: () => void | Promise<void>): Promise<void>;
/**
* IMean ID Generator - 基于 nanoid 的 ID 生成器
*
* 使用自定义字符集(仅包含大小写字母和数字)生成唯一 ID
* 字符集:A-Z, a-z, 0-9 (共62个字符)
*
* @example
* ```typescript
* import { imeanId } from "imean-service-engine";
*
* // 生成默认长度(12)的 ID
* const id1 = imeanId();
* console.log(id1); // 例如: "V1StGXR8IZ5j"
*
* // 生成指定长度的 ID
* const id2 = imeanId(10);
* console.log(id2); // 例如: "V1StGXR8IZ"
* ```
*/
/**
* IMean ID 字符集
* 仅包含大小写字母和数字(A-Z, a-z, 0-9),不包含下划线和横线
*/
declare const IMEAN_ID_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
/**
* 生成 IMean ID
*
* @param length - ID 长度(默认 12)
* @returns 生成的 ID 字符串
*
* @example
* ```typescript
* // 生成默认长度的 ID
* const id1 = imeanId();
*
* // 生成指定长度的 ID
* const id2 = imeanId(10);
* const id3 = imeanId(32);
* ```
*/
declare function imeanId(length?: number): string;
/**
* 用于给微服务模块方法添加的注解
*/
declare function Action(options: ActionOptions): Function;
/**
* 用于标注一个类是微服务模块的装饰器
* @param name 模块名称
* @param options 模块配置选项
*/
declare function Module(name: string, options?: ModuleOptions): Function;
/**
* 用于给微服务模块方法添加的页面注解
*/
declare function Page(options: PageOptions): Function;
/**
* 用于给微服务模块方法添加的调度注解
*/
declare function Schedule(options: ScheduleOptions): Function;
declare const logger: winston.Logger;
export { Action, type ActionErrorEvent, type ActionMetadata, type ActionOptions, BaseLayout, CacheAdapter, type CacheFn, type CleanupHook, type EtcdConfig, type EventServiceInfo, HtmxLayout, IMEAN_ID_ALPHABET, MemoryCacheAdapter, Microservice, type MicroserviceOptions, Module, type ModuleInfo, type ModuleMetadata, type ModuleOptions, Page, type PageMetadata, type PageOptions, PageRenderPlugin, type PageRenderPluginOptions, Plugin, type PreStartChecker, RedisCacheAdapter, type RequestInfo, Schedule, type ScheduleMetadata, ScheduleMode, type ScheduleOptions, ServiceContext, type ServiceInfo, ServiceInfoCards, type ServiceStats, ServiceStatusPage, type StatisticsEvent, type StreamResponse, imeanId, logger, startCheck };