@sailboat-computer/event-bus
Version:
Standardized event bus for sailboat computer v3 with resilience features and offline capabilities
180 lines (158 loc) • 4.93 kB
text/typescript
/**
* Redis adapter example for the event bus
*/
import {
createEventBus,
EventPriority,
EventCategory
} from '../src';
// Define event types
interface SensorReadingEvent {
sensorId: string;
value: number;
unit: string;
timestamp: Date;
}
interface SystemStatusEvent {
status: 'online' | 'offline' | 'degraded';
components: Array<{
name: string;
status: 'ok' | 'warning' | 'error';
message?: string;
}>;
timestamp: Date;
}
async function main() {
console.log('Starting Redis event bus example...');
// Create event bus with Redis adapter
const eventBus = createEventBus({
adapter: {
type: 'redis',
config: {
url: process.env.REDIS_URL || 'redis://localhost:6379',
consumerGroup: 'example-service-group',
consumerName: `example-consumer-${process.pid}`,
maxBatchSize: 100,
pollInterval: 1000,
reconnectOptions: {
baseDelay: 1000,
maxDelay: 30000,
maxRetries: 10
},
serviceName: 'example-service'
}
},
offlineBuffer: {
maxSize: 1000,
priorityRetention: true
},
metrics: {
enabled: true,
detailedTimings: true
}
});
// Initialize event bus
await eventBus.initialize({
adapter: {
type: 'redis',
config: {
url: process.env.REDIS_URL || 'redis://localhost:6379',
consumerGroup: 'example-service-group',
consumerName: `example-consumer-${process.pid}`,
maxBatchSize: 100,
pollInterval: 1000,
reconnectOptions: {
baseDelay: 1000,
maxDelay: 30000,
maxRetries: 10
},
serviceName: 'example-service'
}
},
offlineBuffer: {
maxSize: 1000,
priorityRetention: true
},
metrics: {
enabled: true,
detailedTimings: true
}
});
console.log('Event bus initialized with Redis adapter');
// Subscribe to sensor reading events
const sensorSubscription = await eventBus.subscribe<SensorReadingEvent>('sensor.reading.v1', async (event) => {
console.log(`Sensor reading: ${event.data.sensorId} = ${event.data.value} ${event.data.unit}`);
});
console.log(`Subscribed to sensor reading events with ID: ${sensorSubscription.id}`);
// Subscribe to system status events
const statusSubscription = await eventBus.subscribe<SystemStatusEvent>('system.status.v1', async (event) => {
console.log(`System status: ${event.data.status}`);
console.log(`Components: ${event.data.components.length}`);
// Log components with issues
const issueComponents = event.data.components.filter(c => c.status !== 'ok');
if (issueComponents.length > 0) {
console.log('Components with issues:');
for (const component of issueComponents) {
console.log(`- ${component.name}: ${component.status} ${component.message || ''}`);
}
}
});
console.log(`Subscribed to system status events with ID: ${statusSubscription.id}`);
// Publish a sensor reading event
await eventBus.publish<SensorReadingEvent>(
'sensor.reading.v1',
{
sensorId: 'temp-cabin-main',
value: 22.5,
unit: '°C',
timestamp: new Date()
},
{
priority: EventPriority.NORMAL,
category: EventCategory.DATA,
tags: ['sensor', 'temperature']
}
);
// Publish a system status event
await eventBus.publish<SystemStatusEvent>(
'system.status.v1',
{
status: 'degraded',
components: [
{ name: 'navigation', status: 'ok' },
{ name: 'communication', status: 'warning', message: 'Weak signal' },
{ name: 'power', status: 'ok' },
{ name: 'propulsion', status: 'error', message: 'Engine overheating' }
],
timestamp: new Date()
},
{
priority: EventPriority.HIGH,
category: EventCategory.SYSTEM,
tags: ['status', 'monitoring']
}
);
// Wait for events to be processed
console.log('Waiting for events to be processed...');
await new Promise(resolve => setTimeout(resolve, 2000));
// Get metrics
const metrics = eventBus.getMetrics();
console.log('\nEvent Bus Metrics:');
console.log(`- Published events: ${metrics.publishedEvents}`);
console.log(`- Failed publishes: ${metrics.failedPublishes}`);
console.log(`- Processed events: ${metrics.processedEvents}`);
console.log(`- Active subscriptions: ${metrics.activeSubscriptions}`);
console.log(`- Average processing time: ${metrics.averageProcessingTime.toFixed(2)}ms`);
// Unsubscribe
await sensorSubscription.unsubscribe();
await statusSubscription.unsubscribe();
console.log('\nUnsubscribed from all events');
// Close event bus
await eventBus.close();
console.log('Event bus closed');
}
// Run the example
main().catch(error => {
console.error('Error in example:', error);
process.exit(1);
});