imean-service-engine
Version:
microservice engine
290 lines (278 loc) • 8.08 kB
TypeScript
import { z } from 'zod';
export * from 'zod';
import { Redis, Cluster } from 'ioredis';
import { LRUCache } from 'lru-cache';
import { Lease, Etcd3 } from 'etcd3';
import { Hono } from 'hono';
export { default as dayjs } from 'dayjs';
import winston from 'winston';
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;
type McpOptions = {
type: "tool";
};
interface ActionOptions {
params?: z.ZodType<any>[];
returns?: z.ZodType<any>;
idempotence?: boolean;
description?: string;
printError?: boolean;
cache?: boolean | CacheFn;
ttl?: number;
stream?: boolean;
mcp?: McpOptions;
}
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[];
}
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[]): 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 isShuttingDown;
private statisticsTimer?;
private wsHandler?;
private actionHandlers;
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>;
/**
* 停止服务
*/
stop(): Promise<void>;
/**
* 初始化停机处理
*/
private initShutdownHandlers;
/**
* 优雅停机
*/
private gracefulShutdown;
private initStatsEventManager;
private updateStats;
getActionHandler(moduleName: string, actionName: string): ActionHandler;
private handleRequest;
private initPlugins;
init(): Promise<void>;
}
interface PreStartChecker {
name: string;
check: () => Promise<void> | void;
skip?: boolean;
}
declare function startCheck(checkers: PreStartChecker[], pass?: () => void | Promise<void>): Promise<void>;
declare class ModelContextProtocolPlugin extends Plugin {
private mcpServer;
private transports;
private registerMcpTools;
initialize: (engine: Microservice) => Promise<void>;
}
/**
* 用于给微服务模块方法添加的注解
*/
declare function Action(options: ActionOptions): Function;
/**
* 用于标注一个类是微服务模块的装饰器
* @param name 模块名称
* @param options 模块配置选项
*/
declare function Module(name: string, options?: ModuleOptions): Function;
/**
* 用于给微服务模块方法添加的调度注解
*/
declare function Schedule(options: ScheduleOptions): Function;
declare const logger: winston.Logger;
export { Action, type ActionErrorEvent, type ActionMetadata, type ActionOptions, CacheAdapter, type CacheFn, type EtcdConfig, type EventServiceInfo, type McpOptions, MemoryCacheAdapter, Microservice, type MicroserviceOptions, ModelContextProtocolPlugin, Module, type ModuleInfo, type ModuleMetadata, type ModuleOptions, Plugin, type PreStartChecker, RedisCacheAdapter, Schedule, type ScheduleMetadata, ScheduleMode, type ScheduleOptions, ServiceContext, type ServiceInfo, type ServiceStats, type StatisticsEvent, type StreamResponse, logger, startCheck };