All files index.js

72.54% Statements 37/51
64.91% Branches 37/57
71.42% Functions 10/14
72.54% Lines 37/51

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 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274                        2x     2x                             2x 2x                                         26x     26x           26x                                                         3x     3x 3x     2x         2x 2x       2x 2x 2x       2x 2x 2x     2x         1x   1x 1x     1x 1x     1x 1x     1x                     1x                           1x                         2x 1x   1x             2x               1x                     1x                                                                                                                                         2x
/**
 * @onlineapps/connector-core
 *
 * Core integration library that bundles all essential connectors
 * for OA Drive microservices. Provides a unified interface for:
 * - Message Queue operations
 * - Service Registry registration and discovery
 * - Workflow cookbook processing
 * - Storage operations with MinIO
 * - Centralized logging
 */
 
require('dotenv').config();
 
// Re-export all connectors
module.exports = {
  // MQ Client for RabbitMQ communication
  MQClient: require('@onlineapps/connector-mq-client'),
 
  // Service Registry client for registration and event consumption
  ...require('@onlineapps/connector-registry-client'),
 
  // Cookbook validation and processing
  ...require('@onlineapps/connector-cookbook'),
 
  // Storage connector for MinIO with fingerprinting
  StorageConnector: require('@onlineapps/connector-storage'),
 
  // Logger (if available)
  createLogger: (() => {
    try {
      return require('@onlineapps/connector-logger');
    } catch (e) {
      // Logger not available, return console as fallback
      return function(config) {
        return {
          info: console.log,
          error: console.error,
          warn: console.warn,
          debug: console.debug,
          api: { info: console.log, error: console.error },
          mq: { info: console.log, error: console.error },
          workflow: { info: console.log, error: console.error },
          registry: { info: console.log, error: console.error },
          close: async () => {}
        };
      };
    }
  })(),
 
  // Convenience factory for creating a fully configured microservice
  createMicroservice: function(config) {
    const { ServiceRegistryClient, MQClient, StorageConnector, createLogger } = module.exports;
 
    // Create logger instance
    const logger = createLogger({
      serviceName: config.serviceName,
      version: config.version,
      ...config.logger
    });
 
    return {
      logger,
      // Initialize Registry Client
      registry: config.registry ? new ServiceRegistryClient({
        amqpUrl: config.amqpUrl || process.env.RABBITMQ_URL,
        serviceName: config.serviceName,
        version: config.version || '1.0.0',
        ...config.registry
      }) : null,
 
      // Initialize MQ Client
      mq: config.mq ? new MQClient({
        type: 'rabbitmq',
        host: config.amqpUrl || process.env.RABBITMQ_URL,
        queue: `${config.serviceName}_queue`,
        ...config.mq
      }) : null,
 
      // Initialize Storage
      storage: config.storage ? new StorageConnector({
        endPoint: process.env.MINIO_ENDPOINT || 'localhost',
        port: parseInt(process.env.MINIO_PORT || 9000),
        accessKey: process.env.MINIO_ACCESS_KEY || 'minioadmin',
        secretKey: process.env.MINIO_SECRET_KEY || 'minioadmin',
        ...config.storage
      }) : null,
 
      // Initialize all components
      async init() {
        const results = {};
 
        // Initialize Registry
        Eif (this.registry) {
          await this.registry.initialize();
 
          // Optionally subscribe to changes
          Iif (config.subscribeToRegistry) {
            await this.registry.subscribeToChanges();
          }
 
          // Start heartbeat
          this.registry.startHeartbeat();
          results.registry = true;
        }
 
        // Initialize MQ
        Eif (this.mq) {
          await this.mq.connect();
          results.mq = true;
        }
 
        // Initialize Storage
        Eif (this.storage) {
          await this.storage.initialize();
          results.storage = true;
        }
 
        return results;
      },
 
      // Graceful shutdown
      async shutdown() {
        const promises = [];
 
        Eif (this.registry) {
          promises.push(this.registry.dispose());
        }
 
        Eif (this.mq) {
          promises.push(this.mq.disconnect());
        }
 
        Eif (this.logger && this.logger.close) {
          promises.push(this.logger.close());
        }
 
        await Promise.all(promises);
      }
    };
  },
 
  // Helper for workflow processing
  WorkflowHelper: {
    /**
     * Create a workflow message
     */
    createMessage(opts) {
      return {
        workflow_id: opts.workflowId,
        cookbook_name: opts.cookbookName,
        step_index: opts.step || 0,
        data: opts.data || {},
        results: [],
        timestamp: new Date().toISOString()
      };
    },
 
    /**
     * Parse a workflow message
     */
    parseMessage(message) {
      return {
        workflowId: message.workflow_id,
        cookbookName: message.cookbook_name,
        step: message.step_index,
        data: message.data,
        results: message.results
      };
    },
 
    /**
     * Get next queue from cookbook step
     */
    getNextQueue(step) {
      if (step.queue) {
        return step.queue;
      }
      return `${step.service}.queue`;
    },
 
    /**
     * Validate workflow message
     */
    isValidMessage(message) {
      return !!(message.workflow_id && message.cookbook_name &&
                typeof message.step_index === 'number' && message.data);
    },
 
    /**
     * Add result to workflow message
     */
    addResult(message, result) {
      return {
        ...message,
        results: [...(message.results || []), result],
        last_result: result
      };
    },
 
    /**
     * Create error message
     */
    createErrorMessage(message, error, serviceName) {
      return {
        ...message,
        status: 'error',
        error: {
          message: error.message,
          stack: error.stack,
          service: serviceName,
          step: message.step_index
        }
      };
    },
 
    /**
     * Process a workflow step
     * @param {Object} message - Workflow message
     * @param {Function} handler - Step handler function
     * @returns {Object} - Updated workflow message
     */
    async processStep(message, handler) {
      const { workflow_id, current_step, cookbook, context = {} } = message;
 
      // Get current step from cookbook
      const step = cookbook?.steps?.[current_step];
      if (!step) {
        throw new Error(`Step ${current_step} not found in cookbook`);
      }
 
      // Execute handler
      const result = await handler(step, context);
 
      // Build response message
      return {
        ...message,
        current_step: current_step + 1,
        context: {
          ...context,
          [`step_${current_step}_result`]: result
        },
        trace: [
          ...(message.trace || []),
          {
            step: current_step,
            service: step.service,
            timestamp: new Date().toISOString(),
            result: result
          }
        ]
      };
    },
 
    /**
     * Determine next queue based on workflow state
     * @param {Object} message - Workflow message
     * @returns {string} - Next queue name
     */
    getNextQueueFromMessage(message) {
      const { current_step, cookbook } = message;
 
      if (cookbook && current_step < cookbook.steps.length) {
        const nextStep = cookbook.steps[current_step];
        return `${nextStep.service}.queue`;
      }
 
      return 'workflow.completed';
    }
  }
};
 
// For backward compatibility
module.exports.ConnectorCore = module.exports;