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 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 | 1x 1x 1x 1x 19x 19x 19x 2x 1x 2x 1x 1x 19x 1x | /**
* @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
*/
// NOTE: dotenv.config() removed to avoid side effects in library code
// Consumers are responsible for loading their own .env
const runtimeCfg = require('./config');
// Re-export all connectors
module.exports = {
// MQ Client for RabbitMQ communication
MQClient: require('@onlineapps/conn-infra-mq'),
// Service Registry client for registration and event consumption
...require('@onlineapps/conn-orch-registry'),
// Cookbook validation and processing
...require('@onlineapps/conn-orch-cookbook'),
// Storage connector for MinIO with fingerprinting
StorageConnector: require('@onlineapps/conn-base-storage'),
// Monitoring connector
MonitoringConnector: require('@onlineapps/conn-base-monitoring'),
// Legacy createLogger for backward compatibility
createLogger: (() => {
const monitoring = require('@onlineapps/conn-base-monitoring');
return async function(config) {
// Initialize monitoring and return logger-like interface (API returned by init)
return monitoring.init(config);
};
})(),
// Convenience factory for creating a fully configured microservice
createMicroservice: function(config) {
const { ServiceRegistryClient, MQClient, StorageConnector, createLogger } = module.exports;
// Logger instance is created lazily in init() to avoid side effects during construction.
// This also prevents unhandled promise rejections when env/config is incomplete in tests/dev.
let loggerApi = null;
const logger = {
info: (message, data) => (loggerApi ? loggerApi.info(message, data) : console.log(message, data)),
warn: (message, data) => (loggerApi ? loggerApi.warn(message, data) : console.warn(message, data)),
error: (message, data) => (loggerApi ? loggerApi.error(message, data) : console.error(message, data)),
debug: (message, data) => (loggerApi ? loggerApi.debug(message, data) : console.debug(message, data)),
close: async () => {
Iif (loggerApi && typeof loggerApi.shutdown === 'function') {
await loggerApi.shutdown();
}
}
};
return {
logger,
// Initialize Registry Client
registry: config.registry ? new ServiceRegistryClient({
// Priority: explicit registry config → top-level config → ENV
amqpUrl: config.registry?.amqpUrl || config.registry?.url || config.amqpUrl || runtimeCfg.get('rabbitmqUrl'),
serviceName: config.serviceName,
version: config.version || '1.0.0',
...config.registry
}) : null,
// Initialize MQ Client
mq: config.mq ? new MQClient({
type: runtimeCfg.get('mqType'),
// Priority: explicit mq config → top-level config → ENV
host: config.mq?.host || config.mq?.url || config.amqpUrl || runtimeCfg.get('rabbitmqUrl'),
queue: `${config.serviceName}${runtimeCfg.get('mqDefaultServiceQueueSuffix')}`,
...config.mq
}) : null,
// Initialize Storage (all MinIO config MUST come from env or config - no fallbacks)
storage: config.storage ? new StorageConnector({
// Priority: explicit storage config → ENV (resolved via runtimeCfg)
endPoint: runtimeCfg.get('minioEndpoint', config.storage?.endPoint),
port: runtimeCfg.get('minioPort', config.storage?.port),
useSSL: runtimeCfg.get('minioUseSSL', config.storage?.useSSL),
accessKey: runtimeCfg.get('minioAccessKey', config.storage?.accessKey),
secretKey: runtimeCfg.get('minioSecretKey', config.storage?.secretKey),
...config.storage
}) : null,
// Initialize all components
async init() {
const results = {};
// Initialize Logger (Monitoring) - optional, keep microservice usable even if monitoring can't start
try {
loggerApi = await createLogger({
serviceName: config.serviceName,
version: config.version,
...config.logger
});
results.logger = true;
} catch (err) {
console.warn(
`[conn-base-hub] Monitoring init failed - Continuing with console logger. Fix: set RABBITMQ_URL or pass logger.rabbitmq.url. (${err.message})`
);
results.logger = false;
}
// Initialize Registry
if (this.registry) {
await this.registry.initialize();
// Optionally subscribe to changes
if (config.subscribeToRegistry) {
await this.registry.subscribeToChanges();
}
// Start heartbeat
this.registry.startHeartbeat();
results.registry = true;
}
// Initialize MQ
if (this.mq) {
await this.mq.connect();
results.mq = true;
}
// Initialize Storage
if (this.storage) {
await this.storage.initialize();
results.storage = true;
}
return results;
},
// Graceful shutdown
async shutdown() {
const promises = [];
if (this.registry) {
promises.push(this.registry.dispose());
}
if (this.mq) {
promises.push(this.mq.disconnect());
}
if (this.logger && typeof this.logger.close === 'function') {
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}${runtimeCfg.get('workflowDefaultServiceQueueSuffix')}`;
},
/**
* 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
* V2.1: steps is an array, current_step is step_id (string)
* @param {Object} message - Workflow message
* @returns {string} - Next queue name
*/
getNextQueueFromMessage(message) {
const { current_step, cookbook } = message;
if (!cookbook?.steps) {
return runtimeCfg.get('workflowCompletedQueue');
}
// V2.1: steps is array, find current step by step_id
if (Array.isArray(cookbook.steps)) {
const currentIndex = cookbook.steps.findIndex(s => s.step_id === current_step);
if (currentIndex >= 0 && currentIndex < cookbook.steps.length - 1) {
const nextStep = cookbook.steps[currentIndex + 1];
return `${nextStep.service}${runtimeCfg.get('workflowDefaultServiceQueueSuffix')}`;
}
return runtimeCfg.get('workflowCompletedQueue');
}
// V2.0 (deprecated): steps is object, current_step is step_id
const stepIds = Object.keys(cookbook.steps);
const currentIndex = stepIds.indexOf(current_step);
if (currentIndex >= 0 && currentIndex < stepIds.length - 1) {
const nextStepId = stepIds[currentIndex + 1];
const nextStep = cookbook.steps[nextStepId];
return `${nextStep.service}${runtimeCfg.get('workflowDefaultServiceQueueSuffix')}`;
}
return runtimeCfg.get('workflowCompletedQueue');
}
}
};
// For backward compatibility
module.exports.ConnectorCore = module.exports; |