File size: 5,028 Bytes
529090e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { EventEmitter } from 'events';
import os from 'os';

type Handler = (payload: any) => Promise<void> | void;

interface EventBusOptions {
  redisUrl?: string;
  streamKey?: string;
  groupName?: string;
  consumerName?: string;
  readCount?: number;
  blockMs?: number;
}

class PersistentEventBus extends EventEmitter {
  private redis: any;
  private ready = false;
  private handlers: Map<string, Set<Handler>> = new Map();
  private polling = false;
  private readonly streamKey: string;
  private readonly group: string;
  private readonly consumer: string;
  private readonly blockMs: number;
  private readonly readCount: number;
  private readonly redisUrl: string;

  constructor(options: EventBusOptions = {}) {
    super();
    this.redisUrl = options.redisUrl || process.env.REDIS_URL || 'redis://localhost:6379';
    this.streamKey = options.streamKey || 'widgetdc:events';
    this.group = options.groupName || 'widgetdc-consumers';
    this.consumer = options.consumerName || `${os.hostname()}-${process.pid}`;
    this.blockMs = options.blockMs ?? 1000;
    this.readCount = options.readCount ?? 20;
  }

  isReady(): boolean {
    return this.ready;
  }

  async init(): Promise<void> {
    if (this.ready) return;
    try {
      const Redis = (await import('ioredis')).default;
      this.redis = new Redis(this.redisUrl, { maxRetriesPerRequest: 3 });
      await this.ensureGroup();
      this.ready = true;
      console.log('🔴 PersistentEventBus: Redis Streams ready');
    } catch (err: any) {
      console.warn(`⚠️ PersistentEventBus fallback to in-memory: ${err?.message || err}`);
      this.ready = false;
    }
  }

  async publish(eventType: string, payload: any): Promise<void> {
    const entry = JSON.stringify({ eventType, payload, ts: Date.now() });
    if (!this.ready || !this.redis) {
      // in-memory fallback
      this.emit(eventType, payload);
      this.emit('*', { eventType, payload });
      return;
    }

    try {
      await this.redis.xadd(this.streamKey, '*', 'type', eventType, 'data', entry);
    } catch (err: any) {
      console.error('Failed to publish event, falling back to memory:', err?.message || err);
      this.emit(eventType, payload);
      this.emit('*', { eventType, payload });
    }
  }

  subscribe(eventType: string, handler: Handler): void {
    if (!this.handlers.has(eventType)) this.handlers.set(eventType, new Set());
    this.handlers.get(eventType)!.add(handler);

    // Local immediate delivery
    this.on(eventType, handler);

    if (this.ready && !this.polling) {
      this.startPolling();
    }
  }

  remove(eventType: string, handler: Handler): void {
    this.off(eventType, handler);
    this.handlers.get(eventType)?.delete(handler);
  }

  private async ensureGroup(): Promise<void> {
    try {
      await this.redis.xgroup('CREATE', this.streamKey, this.group, '0', 'MKSTREAM');
    } catch (err: any) {
      // Ignore BUSYGROUP
      if (!String(err?.message).includes('BUSYGROUP')) {
        throw err;
      }
    }
  }

  private async startPolling(): Promise<void> {
    if (this.polling || !this.redis) return;
    this.polling = true;

    const loop = async () => {
      while (this.polling && this.redis) {
        try {
          const entries = await this.redis.xreadgroup(
            'GROUP', this.group, this.consumer,
            'COUNT', this.readCount,
            'BLOCK', this.blockMs,
            'STREAMS', this.streamKey,
            '>'
          );

          if (entries) {
            const [_, messages] = entries[0];
            for (const [id, fields] of messages) {
              const payload = this.parseFields(fields as any[]);
              this.dispatch(payload);
              await this.redis.xack(this.streamKey, this.group, id);
            }
          }
        } catch (err: any) {
          console.error('PersistentEventBus poll error:', err?.message || err);
          await new Promise(r => setTimeout(r, 500));
        }
      }
    };

    loop();
  }

  private parseFields(fields: any[]): { eventType: string; payload: any } {
    const obj: Record<string, any> = {};
    for (let i = 0; i < fields.length; i += 2) {
      obj[fields[i]] = fields[i + 1];
    }
    try {
      const parsed = JSON.parse(obj['data']);
      return { eventType: parsed.eventType, payload: parsed.payload };
    } catch {
      return { eventType: obj['type'] || 'unknown', payload: obj['data'] };
    }
  }

  private dispatch(entry: { eventType: string; payload: any }) {
    const handlers = this.handlers.get(entry.eventType);
    if (handlers) {
      handlers.forEach(async (handler) => {
        try {
          await handler(entry.payload);
        } catch (err: any) {
          console.error(`Handler error for ${entry.eventType}:`, err?.message || err);
        }
      });
    }
  }

  async shutdown(): Promise<void> {
    this.polling = false;
    if (this.redis) {
      await this.redis.quit();
    }
  }
}

export const persistentEventBus = new PersistentEventBus();