@sailboat-computer/event-bus
Version:
Standardized event bus for sailboat computer v3 with resilience features and offline capabilities
504 lines • 12.1 kB
TypeScript
/**
* Event bus types
*/
import { common, EventEnvelope, Subscription, PublishOptions, EventBusMetrics } from '@sailboat-computer/sailboat-types';
export type AlertSeverityType = common.AlertSeverity;
export type EventPriorityType = common.EventPriority;
export type EventCategoryType = common.EventCategory;
declare const EventPriority: {
LOW: common.EventPriority;
NORMAL: common.EventPriority;
HIGH: common.EventPriority;
CRITICAL: common.EventPriority;
};
declare const EventCategory: {
DATA: common.EventCategory;
ALERT: common.EventCategory;
CONFIGURATION: common.EventCategory;
SYSTEM: common.EventCategory;
USER_ACTION: common.EventCategory;
};
declare const AlertSeverity: {
INFO: common.AlertSeverity;
WARNING: common.AlertSeverity;
ALARM: common.AlertSeverity;
CRITICAL: common.AlertSeverity;
EMERGENCY: common.AlertSeverity;
};
export { EventPriority, EventCategory, AlertSeverity, EventEnvelope, Subscription, PublishOptions, EventBusMetrics, common };
import { ExtendedEventBusMetrics } from './metrics';
export { ExtendedEventBusMetrics };
/**
* Event handler function
*/
export type EventHandler<T = any> = (event: EventEnvelope) => void | Promise<void>;
/**
* Buffered event for offline storage
*/
export interface BufferedEvent<T = any> {
eventType: string;
data: T;
options?: PublishOptions | undefined;
timestamp: Date;
attempts: number;
}
/**
* Dead letter queue event
*/
export interface DeadLetterEvent<T = any> {
/**
* Event type
*/
eventType: string;
/**
* Event data
*/
data: T;
/**
* Original event ID
*/
originalEventId: string;
/**
* Timestamp when the event was sent to the dead letter queue
*/
timestamp: Date;
/**
* Number of processing attempts before sending to dead letter queue
*/
attempts: number;
/**
* Error that caused the event to be sent to the dead letter queue
*/
error: {
/**
* Error message
*/
message: string;
/**
* Error stack trace
*/
stack?: string;
/**
* Error code
*/
code?: string;
};
}
/**
* Mapping between our severity levels and common-types AlertSeverity
*/
export declare const AlertSeverityMapping: {
INFO: common.AlertSeverity;
WARNING: common.AlertSeverity;
ERROR: common.AlertSeverity;
CRITICAL: common.AlertSeverity;
};
/**
* Alert types
*/
export declare enum AlertType {
/**
* Failed publishes alert
*/
FAILED_PUBLISHES = "failed_publishes",
/**
* Dead letter queue size alert
*/
DEAD_LETTER_QUEUE_SIZE = "dead_letter_queue_size",
/**
* Reconnection attempts alert
*/
RECONNECTION_ATTEMPTS = "reconnection_attempts",
/**
* Processing time alert
*/
PROCESSING_TIME = "processing_time",
/**
* Connection status alert
*/
CONNECTION_STATUS = "connection_status"
}
/**
* Alert interface
*/
export interface Alert {
/**
* Alert ID
*/
id: string;
/**
* Alert type
*/
type: AlertType;
/**
* Alert severity
*/
severity: AlertSeverityType;
/**
* Alert message
*/
message: string;
/**
* Alert timestamp
*/
timestamp: Date;
/**
* Alert details
*/
details?: Record<string, any>;
/**
* Whether the alert is resolved
*/
resolved: boolean;
/**
* Timestamp when the alert was resolved
*/
resolvedAt?: Date;
}
/**
* Alert handler function
*/
export type AlertHandler = (alert: Alert) => void | Promise<void>;
/**
* Event bus interface
*/
export interface EventBus {
/**
* Initialize the event bus
*
* @param config - Event bus configuration
*/
initialize(config: EventBusConfig): Promise<void>;
/**
* Shutdown the event bus
*/
shutdown(): Promise<void>;
/**
* Publish an event
*
* @param eventType - Event type
* @param data - Event data
* @param options - Publish options
* @returns Event ID
*/
publish<T>(eventType: string, data: T, options?: PublishOptions): Promise<string>;
/**
* Subscribe to an event
*
* @param eventType - Event type
* @param handler - Event handler
* @returns Subscription
*/
subscribe<T>(eventType: string, handler: EventHandler<T>): Promise<Subscription>;
/**
* Get event bus metrics
*
* @returns Event bus metrics
*/
getMetrics(): EventBusMetrics;
/**
* Register a schema for an event type
*
* @param eventType - Event type
* @param schema - JSON schema
*/
registerSchema<T>(eventType: string, schema: any): void;
/**
* Check if a schema is registered for an event type
*
* @param eventType - Event type
* @returns True if a schema is registered
*/
hasSchema(eventType: string): boolean;
/**
* Get a schema for an event type
*
* @param eventType - Event type
* @returns JSON schema or null if not found
*/
getSchema(eventType: string): any;
/**
* Get events from the dead letter queue
*
* @param eventType - Optional event type to filter by
* @param limit - Maximum number of events to return
* @returns Dead letter queue events
*/
getDeadLetterEvents(eventType?: string, limit?: number): Promise<DeadLetterEvent[]>;
/**
* Republish an event from the dead letter queue
*
* @param eventId - ID of the event to republish
* @returns New event ID
*/
republishDeadLetterEvent(eventId: string): Promise<string>;
/**
* Remove an event from the dead letter queue
*
* @param eventId - ID of the event to remove
*/
removeDeadLetterEvent(eventId: string): Promise<void>;
/**
* Clear the dead letter queue
*
* @param eventType - Optional event type to filter by
*/
clearDeadLetterQueue(eventType?: string): Promise<void>;
/**
* Register an alert handler
*
* @param handler - Alert handler
* @returns Handler ID
*/
registerAlertHandler(handler: AlertHandler): string;
/**
* Unregister an alert handler
*
* @param handlerId - Handler ID
*/
unregisterAlertHandler(handlerId: string): void;
/**
* Get active alerts
*
* @param type - Optional alert type to filter by
* @returns Active alerts
*/
getActiveAlerts(type?: AlertType): Alert[];
/**
* Get alert history
*
* @param limit - Maximum number of alerts to return
* @param type - Optional alert type to filter by
* @returns Alert history
*/
getAlertHistory(limit?: number, type?: AlertType): Alert[];
/**
* Clear alert history
*/
clearAlertHistory(): void;
/**
* Unsubscribe from all handlers for an event type
*
* @param eventType - Event type to unsubscribe from
*/
unsubscribe(eventType: string): Promise<void>;
/**
* Check if the event bus is healthy
*
* @returns True if the event bus is healthy
*/
isHealthy(): Promise<boolean>;
}
/**
* Event adapter interface
*/
export interface EventAdapter {
/**
* Initialize the adapter
*
* @param config - Adapter configuration
*/
initialize(config: AdapterConfig): Promise<void>;
/**
* Shutdown the adapter
*/
shutdown(): Promise<void>;
/**
* Publish an event
*
* @param event - Event envelope
* @returns Event ID
*/
publish<T>(event: EventEnvelope): Promise<string>;
/**
* Subscribe to an event
*
* @param eventType - Event type
* @param handler - Event handler
* @returns Subscription
*/
subscribe<T>(eventType: string, handler: EventHandler<T>): Promise<Subscription>;
/**
* Unsubscribe from all handlers for an event type
*
* @param eventType - Event type to unsubscribe from
*/
unsubscribe(eventType: string): Promise<void>;
/**
* Acknowledge an event
*
* @param eventId - Event ID
* @param eventType - Event type
*/
acknowledgeEvent(eventId: string, eventType: string): Promise<void>;
/**
* Check if the adapter is connected
*
* @returns True if connected
*/
isConnected(): boolean;
}
/**
* Event bus configuration
*/
export interface EventBusConfig {
/**
* Adapter configuration
*/
adapter: {
/**
* Adapter type
*/
type: 'redis' | 'memory';
/**
* Adapter-specific configuration
*/
config: RedisAdapterConfig | MemoryAdapterConfig;
};
/**
* Offline buffer configuration
*/
offlineBuffer: {
/**
* Maximum number of events to buffer
*/
maxSize: number;
/**
* Whether to prioritize events by priority when buffer is full
*/
priorityRetention: boolean;
};
/**
* Metrics configuration
*/
metrics: {
/**
* Whether to enable metrics collection
*/
enabled: boolean;
/**
* Whether to collect detailed timing metrics
*/
detailedTimings: boolean;
};
/**
* Dead letter queue configuration
*/
deadLetterQueue?: {
/**
* Whether to enable the dead letter queue
*/
enabled?: boolean;
/**
* Maximum number of events to store in the dead letter queue
*/
maxSize?: number;
/**
* Maximum number of processing attempts before sending to dead letter queue
*/
maxAttempts?: number;
};
/**
* Monitoring configuration
*/
monitoring?: {
/**
* Whether to enable monitoring
*/
enabled?: boolean;
/**
* Alert thresholds
*/
alertThresholds?: {
/**
* Failed publishes threshold (percentage)
*/
failedPublishesThreshold?: number;
/**
* Dead letter queue size threshold
*/
deadLetterQueueSizeThreshold?: number;
/**
* Reconnection attempts threshold
*/
reconnectionAttemptsThreshold?: number;
/**
* Processing time threshold (milliseconds)
*/
processingTimeThreshold?: number;
};
/**
* Alert check interval (milliseconds)
*/
checkInterval?: number;
};
}
/**
* Base adapter configuration
*/
export interface AdapterConfig {
/**
* Service name
*/
serviceName: string;
}
/**
* Redis adapter configuration
*/
export interface RedisAdapterConfig extends AdapterConfig {
/**
* Redis URL
*/
url: string;
/**
* Consumer group name
*/
consumerGroup: string;
/**
* Consumer name
*/
consumerName: string;
/**
* Maximum batch size for event processing
*/
maxBatchSize: number;
/**
* Polling interval in milliseconds
*/
pollInterval: number;
/**
* Reconnection options
*/
reconnectOptions: {
/**
* Base delay in milliseconds
*/
baseDelay: number;
/**
* Maximum delay in milliseconds
*/
maxDelay: number;
/**
* Maximum number of retries
*/
maxRetries: number;
};
}
/**
* Memory adapter configuration
*/
export interface MemoryAdapterConfig extends AdapterConfig {
/**
* Event time-to-live in milliseconds
*/
eventTtl?: number;
/**
* Whether to simulate network latency
*/
simulateLatency?: boolean;
/**
* Latency range in milliseconds [min, max]
*/
latencyRange?: [number, number];
}
//# sourceMappingURL=types.d.ts.map