UNPKG

@klsakura/rocketmq-native-sdk

Version:

High-performance Node.js client SDK for RocketMQ with Native Addon support (Node.js 16+)

349 lines 13.1 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.MQClient = exports.Consumer = exports.Producer = exports.MessageProperties = void 0; // 动态导入平台加载器(支持ESM和CommonJS) let loadNativeAddon; try { // 尝试使用require (CommonJS) loadNativeAddon = require('./platform-loader').loadNativeAddon; } catch (e) { // 如果require失败,将在运行时使用动态import (ESM) loadNativeAddon = null; } // MessageProperties类 class MessageProperties { constructor() { this.properties = {}; this.message_key = ''; this.sharding_key = ''; this.start_deliver_time = 0; this.trans_check_immunity_time = 0; } putProperty(key, value) { this.properties[key] = String(value); return this; } messageKey(key) { this.message_key = String(key); return this; } shardingKey(key) { this.sharding_key = String(key); return this; } startDeliverTime(time) { this.start_deliver_time = Number(time); // 同时设置RocketMQ标准属性 this.properties['__STARTDELIVERTIME'] = String(time); return this; } transCheckImmunityTime(time) { this.trans_check_immunity_time = Number(time); return this; } toJSON() { const result = { properties: this.properties, messageKey: this.message_key, shardingKey: this.sharding_key, transCheckImmunityTime: this.trans_check_immunity_time }; // 只有在没有设置 __STARTDELIVERTIME 属性时才包含 startDeliverTime if (!this.properties['__STARTDELIVERTIME'] && this.start_deliver_time > 0) { result.startDeliverTime = this.start_deliver_time; } return result; } } exports.MessageProperties = MessageProperties; // Native客户端实现 class NativeClient { constructor(config) { this.config = config; } async initNativeClient() { try { // 如果是ESM环境,使用动态导入 if (!loadNativeAddon) { // @ts-ignore - 动态导入平台加载器 const module = await Promise.resolve().then(() => __importStar(require('./platform-loader.js'))); loadNativeAddon = module.loadNativeAddon; } // 使用平台加载器加载Native Addon const addon = loadNativeAddon(); this.nativeClient = new addon.RocketMQClient(); // 初始化RocketMQ const configJson = { endpoint: this.config.endpoint, accessKeyId: this.config.accessKeyId, accessKeySecret: this.config.accessKeySecret, instanceId: this.config.instanceId, ...(this.config.logLevel && { logLevel: this.config.logLevel }), ...(this.config.thread && { thread: this.config.thread }) }; const result = this.nativeClient.initRocketMQ(configJson); if (!result.success) { throw new Error(`Failed to initialize RocketMQ: ${result.message}`); } console.log('🚀 RocketMQ Native Client initialized successfully'); } catch (error) { throw new Error(`Failed to load Native Addon: ${error.message}`); } } async getProducer(instanceId, topic) { const configJson = JSON.stringify(this.config); const producer = this.nativeClient.createProducer(configJson, topic); if (producer.success === false) { throw new Error(`Failed to create producer: ${producer.message}`); } return new NativeProducer(producer, this.nativeClient); } async getConsumer(instanceId, topic, groupId, tagExpression = '*') { const configJson = JSON.stringify(this.config); const consumer = this.nativeClient.createConsumer(configJson, topic, groupId, tagExpression); if (consumer.success === false) { throw new Error(`Failed to create consumer: ${consumer.message}`); } return new NativeConsumer(consumer, this.nativeClient); } async healthCheck() { return { status: 'healthy', mode: 'native', timestamp: Date.now() }; } } // 生产者抽象类 class Producer { } exports.Producer = Producer; // Native生产者实现 class NativeProducer extends Producer { constructor(producerInfo, nativeClient) { super(); this.producerInfo = producerInfo; this.nativeClient = nativeClient; } async publishMessage(messageBody, tag = '', properties = null) { const body = typeof messageBody === 'object' ? JSON.stringify(messageBody) : String(messageBody); const props = properties ? JSON.stringify(properties.toJSON()) : '{}'; const result = this.nativeClient.sendMessage(this.producerInfo.producerId, body, tag, props); if (!result || typeof result === 'string') { // 如果返回字符串,假设是成功的消息ID return { messageId: result || 'unknown', receiptHandle: result || 'unknown' }; } if (!result.success) { throw new Error(`Failed to send message: ${result.message}`); } return { messageId: result.messageId, receiptHandle: result.receiptHandle }; } async publishOrderedMessage(messageBody, tag = '', properties = null, shardingKey) { const body = typeof messageBody === 'object' ? JSON.stringify(messageBody) : String(messageBody); const props = properties ? JSON.stringify(properties.toJSON()) : '{}'; const result = this.nativeClient.sendOrderedMessage(this.producerInfo.producerId, body, tag, props, shardingKey || ''); if (!result || typeof result === 'string') { // 如果返回字符串,假设是成功的消息ID return { messageId: result || 'unknown', receiptHandle: result || 'unknown' }; } if (!result.success) { throw new Error(`Failed to send ordered message: ${result.message}`); } return { messageId: result.messageId, receiptHandle: result.receiptHandle }; } async publishDelayMessage(messageBody, tag = '', properties = null, options = {}) { // 对于延迟消息,将延迟时间设置到properties中 const props = properties ? properties.toJSON() : {}; // RocketMQ任意精度延迟消息:使用 __STARTDELIVERTIME 属性 if (options.startDeliverTime) { props.properties = props.properties || {}; props.properties['__STARTDELIVERTIME'] = String(options.startDeliverTime); } // RocketMQ传统延迟等级:使用 delayTimeLevel if (options.delayTimeLevel) { props.delayTimeLevel = options.delayTimeLevel; } const body = typeof messageBody === 'object' ? JSON.stringify(messageBody) : String(messageBody); const result = this.nativeClient.sendMessage(this.producerInfo.producerId, body, tag, JSON.stringify(props)); if (!result || typeof result === 'string') { // 如果返回字符串,假设是成功的消息ID return { messageId: result || 'unknown', receiptHandle: result || 'unknown' }; } if (!result.success) { throw new Error(`Failed to send delay message: ${result.message}`); } return { messageId: result.messageId, receiptHandle: result.receiptHandle }; } async shutdown() { const result = this.nativeClient.shutdownProducer(this.producerInfo.producerId); if (!result || typeof result === 'string') { return { success: true, message: 'Producer shutdown' }; } if (!result.success) { throw new Error(`Failed to shutdown producer: ${result.message}`); } return result; } } // 消费者抽象类 class Consumer { constructor() { this.messageHandlers = []; } } exports.Consumer = Consumer; // Native消费者实现 class NativeConsumer extends Consumer { constructor(consumerInfo, nativeClient) { super(); this.consumerInfo = consumerInfo; this.nativeClient = nativeClient; } onMessage(handler) { this.messageHandlers.push(handler); // 注册消息处理器到Native Addon this.nativeClient.registerMessageHandler(this.consumerInfo.consumerId, (messageJson) => { try { // 解析消息JSON const messageData = JSON.parse(messageJson); // 调用所有注册的处理器 for (const h of this.messageHandlers) { try { h(messageData); } catch (error) { console.error('Error in message handler:', error); } } } catch (error) { console.error('Error parsing message JSON:', error); } }); } startReceiving(tagExpression = '*') { const result = this.nativeClient.startConsumer(this.consumerInfo.consumerId, this.consumerInfo.topic || '', tagExpression); if (!result || typeof result === 'string') { return { success: true, message: 'Consumer started' }; } if (!result.success) { throw new Error(`Failed to start receiving: ${result.message}`); } return result; } async ackMessage(receiptHandle) { const result = this.nativeClient.ackMessage(this.consumerInfo.consumerId, receiptHandle); if (!result || typeof result === 'string') { return { success: true, message: 'Message acknowledged' }; } if (!result.success) { throw new Error(`Failed to ack message: ${result.message}`); } return result; } async shutdown() { const result = this.nativeClient.shutdownConsumer(this.consumerInfo.consumerId); if (!result || typeof result === 'string') { return { success: true, message: 'Consumer shutdown' }; } if (!result.success) { throw new Error(`Failed to shutdown consumer: ${result.message}`); } return result; } } // 主客户端类 class MQClient { constructor(config) { this.initialized = false; this.client = new NativeClient(config); } async ensureInitialized() { if (!this.initialized) { await this.client.initNativeClient(); this.initialized = true; } } /** * 创建生产者 * @param instanceId 实例ID * @param topic 主题 * @returns 生产者实例 */ async getProducer(instanceId, topic) { await this.ensureInitialized(); return this.client.getProducer(instanceId, topic); } /** * 创建消费者 * @param instanceId 实例ID * @param topic 主题 * @param groupId 消费者组ID * @param tagExpression 标签表达式 (默认为'*') * @returns 消费者实例 */ async getConsumer(instanceId, topic, groupId, tagExpression = '*') { await this.ensureInitialized(); return this.client.getConsumer(instanceId, topic, groupId, tagExpression); } /** * 健康检查 */ async healthCheck() { await this.ensureInitialized(); return this.client.healthCheck(); } /** * 获取客户端模式 */ getMode() { return 'native'; } } exports.MQClient = MQClient; // 导出所有类型和类 exports.default = MQClient; //# sourceMappingURL=index.js.map