alepha 0.9.4 → 0.9.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/topic.d.ts CHANGED
@@ -39,7 +39,246 @@ type UnSubscribeFn = () => Promise<void>;
39
39
  //#endregion
40
40
  //#region src/descriptors/$topic.d.ts
41
41
  /**
42
- * Create a new topic.
42
+ * Creates a topic descriptor for pub/sub messaging and event-driven architecture.
43
+ *
44
+ * This descriptor provides a powerful publish/subscribe system that enables decoupled communication
45
+ * between different parts of your application. Topics allow multiple publishers to send messages
46
+ * and multiple subscribers to receive them, creating flexible event-driven architectures with
47
+ * support for real-time messaging and asynchronous event processing.
48
+ *
49
+ * **Key Features**
50
+ *
51
+ * - **Publish/Subscribe Pattern**: Decoupled communication between publishers and subscribers
52
+ * - **Multiple Subscribers**: One-to-many message distribution with automatic fan-out
53
+ * - **Type-Safe Messages**: Full TypeScript support with schema validation using TypeBox
54
+ * - **Real-time Processing**: Immediate message delivery to active subscribers
55
+ * - **Event Filtering**: Subscribe to specific message types using filter functions
56
+ * - **Timeout Support**: Wait for specific messages with configurable timeouts
57
+ * - **Multiple Backends**: Support for in-memory, Redis, and custom topic providers
58
+ * - **Error Resilience**: Built-in error handling and message processing recovery
59
+ *
60
+ * **Use Cases**
61
+ *
62
+ * Perfect for event-driven architectures and real-time communication:
63
+ * - User activity notifications
64
+ * - Real-time chat and messaging systems
65
+ * - System event broadcasting
66
+ * - Microservice communication
67
+ * - Live data updates and synchronization
68
+ * - Application state change notifications
69
+ * - Webhook and external API event handling
70
+ *
71
+ * @example
72
+ * **Basic topic with publish/subscribe:**
73
+ * ```ts
74
+ * import { $topic } from "alepha/topic";
75
+ * import { t } from "alepha";
76
+ *
77
+ * class NotificationService {
78
+ * userActivity = $topic({
79
+ * name: "user-activity",
80
+ * schema: {
81
+ * payload: t.object({
82
+ * userId: t.string(),
83
+ * action: t.enum(["login", "logout", "purchase"]),
84
+ * timestamp: t.number(),
85
+ * metadata: t.optional(t.record(t.string(), t.any()))
86
+ * })
87
+ * },
88
+ * handler: async (message) => {
89
+ * // This subscriber runs automatically for all messages
90
+ * console.log(`User ${message.payload.userId} performed ${message.payload.action}`);
91
+ * }
92
+ * });
93
+ *
94
+ * async trackUserLogin(userId: string) {
95
+ * // Publish event - all subscribers will receive it
96
+ * await this.userActivity.publish({
97
+ * userId,
98
+ * action: "login",
99
+ * timestamp: Date.now(),
100
+ * metadata: { source: "web", ip: "192.168.1.1" }
101
+ * });
102
+ * }
103
+ *
104
+ * async setupAdditionalSubscriber() {
105
+ * // Add another subscriber dynamically
106
+ * await this.userActivity.subscribe(async (message) => {
107
+ * if (message.payload.action === "purchase") {
108
+ * await this.sendPurchaseConfirmation(message.payload.userId);
109
+ * }
110
+ * });
111
+ * }
112
+ * }
113
+ * ```
114
+ *
115
+ * @example
116
+ * **Real-time chat system with multiple subscribers:**
117
+ * ```ts
118
+ * class ChatService {
119
+ * messagesTopic = $topic({
120
+ * name: "chat-messages",
121
+ * description: "Real-time chat messages for all rooms",
122
+ * schema: {
123
+ * payload: t.object({
124
+ * messageId: t.string(),
125
+ * roomId: t.string(),
126
+ * userId: t.string(),
127
+ * content: t.string(),
128
+ * timestamp: t.number(),
129
+ * messageType: t.enum(["text", "image", "file"])
130
+ * })
131
+ * }
132
+ * });
133
+ *
134
+ * async sendMessage(roomId: string, userId: string, content: string) {
135
+ * await this.messagesTopic.publish({
136
+ * messageId: generateId(),
137
+ * roomId,
138
+ * userId,
139
+ * content,
140
+ * timestamp: Date.now(),
141
+ * messageType: "text"
142
+ * });
143
+ * }
144
+ *
145
+ * // Different services can subscribe to the same topic
146
+ * async setupMessageLogging() {
147
+ * await this.messagesTopic.subscribe(async (message) => {
148
+ * // Log all messages for compliance
149
+ * await this.auditLogger.log({
150
+ * action: "message_sent",
151
+ * roomId: message.payload.roomId,
152
+ * userId: message.payload.userId,
153
+ * timestamp: message.payload.timestamp
154
+ * });
155
+ * });
156
+ * }
157
+ *
158
+ * async setupNotificationService() {
159
+ * await this.messagesTopic.subscribe(async (message) => {
160
+ * // Send push notifications to offline users
161
+ * const offlineUsers = await this.getOfflineUsersInRoom(message.payload.roomId);
162
+ * await this.sendPushNotifications(offlineUsers, {
163
+ * title: `New message in ${message.payload.roomId}`,
164
+ * body: message.payload.content
165
+ * });
166
+ * });
167
+ * }
168
+ * }
169
+ * ```
170
+ *
171
+ * @example
172
+ * **Event filtering and waiting for specific messages:**
173
+ * ```ts
174
+ * class OrderService {
175
+ * orderEvents = $topic({
176
+ * name: "order-events",
177
+ * schema: {
178
+ * payload: t.object({
179
+ * orderId: t.string(),
180
+ * status: t.union([
181
+ * t.literal("created"),
182
+ * t.literal("paid"),
183
+ * t.literal("shipped"),
184
+ * t.literal("delivered"),
185
+ * t.literal("cancelled")
186
+ * ]),
187
+ * timestamp: t.number(),
188
+ * data: t.optional(t.record(t.string(), t.any()))
189
+ * })
190
+ * }
191
+ * });
192
+ *
193
+ * async processOrder(orderId: string) {
194
+ * // Publish order created event
195
+ * await this.orderEvents.publish({
196
+ * orderId,
197
+ * status: "created",
198
+ * timestamp: Date.now()
199
+ * });
200
+ *
201
+ * // Wait for payment confirmation with timeout
202
+ * try {
203
+ * const paymentEvent = await this.orderEvents.wait({
204
+ * timeout: [5, "minutes"],
205
+ * filter: (message) =>
206
+ * message.payload.orderId === orderId &&
207
+ * message.payload.status === "paid"
208
+ * });
209
+ *
210
+ * console.log(`Order ${orderId} was paid at ${paymentEvent.payload.timestamp}`);
211
+ *
212
+ * // Continue with shipping...
213
+ * await this.initiateShipping(orderId);
214
+ *
215
+ * } catch (error) {
216
+ * if (error instanceof TopicTimeoutError) {
217
+ * console.log(`Payment timeout for order ${orderId}`);
218
+ * await this.cancelOrder(orderId);
219
+ * }
220
+ * }
221
+ * }
222
+ *
223
+ * async setupOrderTracking() {
224
+ * // Subscribe only to shipping events
225
+ * await this.orderEvents.subscribe(async (message) => {
226
+ * if (message.payload.status === "shipped") {
227
+ * await this.updateTrackingInfo(message.payload.orderId, message.payload.data);
228
+ * await this.notifyCustomer(message.payload.orderId, "Your order has shipped!");
229
+ * }
230
+ * });
231
+ * }
232
+ * }
233
+ * ```
234
+ *
235
+ * @example
236
+ * **Redis-backed topic for distributed systems:**
237
+ * ```ts
238
+ * class DistributedEventSystem {
239
+ * systemEvents = $topic({
240
+ * name: "system-events",
241
+ * provider: RedisTopicProvider, // Use Redis for cross-service communication
242
+ * schema: {
243
+ * payload: t.object({
244
+ * eventType: t.string(),
245
+ * serviceId: t.string(),
246
+ * data: t.record(t.string(), t.any()),
247
+ * timestamp: t.number(),
248
+ * correlationId: t.optional(t.string())
249
+ * })
250
+ * },
251
+ * handler: async (message) => {
252
+ * // Central event handler for all system events
253
+ * await this.processSystemEvent(message.payload);
254
+ * }
255
+ * });
256
+ *
257
+ * async publishServiceHealth(serviceId: string, healthy: boolean) {
258
+ * await this.systemEvents.publish({
259
+ * eventType: "service.health",
260
+ * serviceId,
261
+ * data: { healthy, checkedAt: new Date().toISOString() },
262
+ * timestamp: Date.now()
263
+ * });
264
+ * }
265
+ *
266
+ * async setupHealthMonitoring() {
267
+ * await this.systemEvents.subscribe(async (message) => {
268
+ * if (message.payload.eventType === "service.health") {
269
+ * await this.updateServiceStatus(
270
+ * message.payload.serviceId,
271
+ * message.payload.data.healthy
272
+ * );
273
+ *
274
+ * if (!message.payload.data.healthy) {
275
+ * await this.alertOnCall(`Service ${message.payload.serviceId} is down`);
276
+ * }
277
+ * }
278
+ * });
279
+ * }
280
+ * }
281
+ * ```
43
282
  */
44
283
  declare const $topic: {
45
284
  <T extends TopicMessageSchema>(options: TopicDescriptorOptions<T>): TopicDescriptor<T>;
@@ -47,29 +286,176 @@ declare const $topic: {
47
286
  };
48
287
  interface TopicDescriptorOptions<T extends TopicMessageSchema> {
49
288
  /**
50
- * Topic key.
289
+ * Unique name identifier for the topic.
290
+ *
291
+ * This name is used for:
292
+ * - Topic identification across the pub/sub system
293
+ * - Message routing between publishers and subscribers
294
+ * - Logging and debugging topic-related operations
295
+ * - Provider-specific topic management (channels, keys, etc.)
51
296
  *
52
- * If not provided, the propertyKey is used as the topic name.
297
+ * If not provided, defaults to the property key where the topic is declared.
298
+ *
299
+ * **Naming Conventions**:
300
+ * - Use descriptive, hierarchical names: "user.activity", "order.events"
301
+ * - Avoid spaces and special characters
302
+ * - Consider using dot notation for categorization
303
+ * - Keep names concise but meaningful
304
+ *
305
+ * @example "user-activity"
306
+ * @example "chat.messages"
307
+ * @example "system.health.checks"
308
+ * @example "payment.webhooks"
53
309
  */
54
310
  name?: string;
55
311
  /**
56
- * Describe the topic. For documentation purposes.
312
+ * Human-readable description of the topic's purpose and usage.
313
+ *
314
+ * Used for:
315
+ * - Documentation generation and API references
316
+ * - Developer onboarding and understanding
317
+ * - Monitoring dashboards and admin interfaces
318
+ * - Team communication about system architecture
319
+ *
320
+ * **Description Best Practices**:
321
+ * - Explain what events/messages this topic handles
322
+ * - Mention key use cases and subscribers
323
+ * - Include any important timing or ordering guarantees
324
+ * - Note any special processing requirements
325
+ *
326
+ * @example "Real-time user activity events for analytics and notifications"
327
+ * @example "Order lifecycle events from creation to delivery"
328
+ * @example "Chat messages broadcast to all room participants"
329
+ * @example "System health checks and service status updates"
57
330
  */
58
331
  description?: string;
59
332
  /**
60
- * Override the default topic provider.
333
+ * Topic provider configuration for message storage and delivery.
334
+ *
335
+ * Options:
336
+ * - **"memory"**: In-memory provider (default for development, lost on restart)
337
+ * - **Service<TopicProvider>**: Custom provider class (e.g., RedisTopicProvider)
338
+ * - **undefined**: Uses the default topic provider from dependency injection
339
+ *
340
+ * **Provider Selection Guidelines**:
341
+ * - **Development**: Use "memory" for fast, simple testing without external dependencies
342
+ * - **Production**: Use Redis or message brokers for persistence and scalability
343
+ * - **Distributed systems**: Use Redis/RabbitMQ for cross-service communication
344
+ * - **High-throughput**: Use specialized providers with connection pooling
345
+ * - **Real-time**: Ensure provider supports low-latency message delivery
61
346
  *
62
- * If not provided, the default provider is used.
63
- * If "memory" is provided, the default in-memory provider is used.
64
- * If a class is provided, it must extend `TopicProvider`.
347
+ * **Provider Capabilities**:
348
+ * - Message persistence and durability
349
+ * - Subscriber management and connection handling
350
+ * - Message ordering and delivery guarantees
351
+ * - Horizontal scaling and load distribution
352
+ *
353
+ * @default Uses injected TopicProvider
354
+ * @example "memory"
355
+ * @example RedisTopicProvider
356
+ * @example RabbitMQTopicProvider
65
357
  */
66
358
  provider?: "memory" | Service<TopicProvider>;
67
359
  /**
68
- * Topic message schema.
360
+ * TypeBox schema defining the structure of messages published to this topic.
361
+ *
362
+ * The schema must include:
363
+ * - **payload**: Required schema for the main message data
364
+ * - **headers**: Optional schema for message metadata
365
+ *
366
+ * This schema:
367
+ * - Validates all messages published to the topic
368
+ * - Provides full TypeScript type inference for subscribers
369
+ * - Ensures type safety between publishers and subscribers
370
+ * - Enables automatic serialization/deserialization
371
+ *
372
+ * **Schema Design Best Practices**:
373
+ * - Keep payload schemas focused and cohesive
374
+ * - Use optional fields for data that might not always be present
375
+ * - Include timestamp fields for event ordering
376
+ * - Consider versioning for schema evolution
377
+ * - Use union types for different event types in the same topic
378
+ *
379
+ * @example
380
+ * ```ts
381
+ * {
382
+ * payload: t.object({
383
+ * eventId: t.string(),
384
+ * eventType: t.enum(["created", "updated"]),
385
+ * data: t.record(t.string(), t.any()),
386
+ * timestamp: t.number(),
387
+ * userId: t.optional(t.string())
388
+ * }),
389
+ * headers: t.optional(t.object({
390
+ * source: t.string(),
391
+ * correlationId: t.string()
392
+ * }))
393
+ * }
394
+ * ```
69
395
  */
70
396
  schema: T;
71
397
  /**
72
- * Add a subscriber handler.
398
+ * Default subscriber handler function that processes messages published to this topic.
399
+ *
400
+ * This handler:
401
+ * - Automatically subscribes when the topic is initialized
402
+ * - Receives all messages published to the topic
403
+ * - Runs for every message without additional subscription setup
404
+ * - Can be supplemented with additional subscribers via `subscribe()` method
405
+ * - Should handle errors gracefully to avoid breaking other subscribers
406
+ *
407
+ * **Handler Design Guidelines**:
408
+ * - Keep handlers focused on a single responsibility
409
+ * - Use proper error handling and logging
410
+ * - Consider performance impact for high-frequency topics
411
+ * - Make handlers idempotent when possible
412
+ * - Validate business rules within the handler logic
413
+ * - Log important processing steps for debugging
414
+ *
415
+ * **Error Handling Strategy**:
416
+ * - Log errors but don't re-throw to avoid affecting other subscribers
417
+ * - Use try-catch blocks for external service calls
418
+ * - Consider implementing circuit breakers for resilience
419
+ * - Monitor error rates and patterns for system health
420
+ *
421
+ * @param message - The topic message with validated payload and headers
422
+ * @param message.payload - The typed message data based on the schema
423
+ * @returns Promise that resolves when processing is complete
424
+ *
425
+ * @example
426
+ * ```ts
427
+ * handler: async (message) => {
428
+ * const { eventType, data, timestamp } = message.payload;
429
+ *
430
+ * try {
431
+ * // Log message receipt
432
+ * this.logger.info(`Processing ${eventType} event`, { timestamp, data });
433
+ *
434
+ * // Process based on event type
435
+ * switch (eventType) {
436
+ * case "created":
437
+ * await this.handleCreation(data);
438
+ * break;
439
+ * case "updated":
440
+ * await this.handleUpdate(data);
441
+ * break;
442
+ * default:
443
+ * this.logger.warn(`Unknown event type: ${eventType}`);
444
+ * }
445
+ *
446
+ * this.logger.info(`Successfully processed ${eventType} event`);
447
+ *
448
+ * } catch (error) {
449
+ * // Log error but don't re-throw to avoid affecting other subscribers
450
+ * this.logger.error(`Failed to process ${eventType} event`, {
451
+ * error: error.message,
452
+ * eventType,
453
+ * timestamp,
454
+ * data
455
+ * });
456
+ * }
457
+ * }
458
+ * ```
73
459
  */
74
460
  handler?: TopicHandler<T>;
75
461
  }
@@ -101,14 +487,420 @@ type TopicHandler<T extends TopicMessageSchema = TopicMessageSchema> = (message:
101
487
  //#endregion
102
488
  //#region src/descriptors/$subscriber.d.ts
103
489
  /**
104
- * Subscribe to a $topic.
490
+ * Creates a subscriber descriptor to listen for messages from a specific topic.
491
+ *
492
+ * This descriptor creates a dedicated message subscriber that connects to a topic and processes
493
+ * its messages using a custom handler function. Subscribers provide a clean way to separate
494
+ * message publishing from consumption, enabling scalable pub/sub architectures where multiple
495
+ * subscribers can react to the same events independently.
496
+ *
497
+ * ## Key Features
498
+ *
499
+ * - **Topic Integration**: Seamlessly connects to any $topic descriptor
500
+ * - **Type Safety**: Full TypeScript support inherited from the connected topic's schema
501
+ * - **Dedicated Processing**: Isolated message processing logic separate from the topic
502
+ * - **Real-time Processing**: Immediate message delivery when events are published
503
+ * - **Error Isolation**: Subscriber errors don't affect other subscribers or the topic
504
+ * - **Scalability**: Multiple subscribers can listen to the same topic independently
505
+ *
506
+ * ## Use Cases
507
+ *
508
+ * Perfect for creating specialized event handlers:
509
+ * - Notification services for user events
510
+ * - Analytics and logging systems
511
+ * - Data synchronization between services
512
+ * - Real-time UI updates
513
+ * - Event-driven workflow triggers
514
+ * - Audit and compliance logging
515
+ *
516
+ * @example
517
+ * **Basic subscriber setup:**
518
+ * ```ts
519
+ * import { $topic, $subscriber } from "alepha/topic";
520
+ * import { t } from "alepha";
521
+ *
522
+ * class UserActivityService {
523
+ * // Define the topic
524
+ * userEvents = $topic({
525
+ * name: "user-activity",
526
+ * schema: {
527
+ * payload: t.object({
528
+ * userId: t.string(),
529
+ * action: t.enum(["login", "logout", "purchase"]),
530
+ * timestamp: t.number(),
531
+ * metadata: t.optional(t.record(t.string(), t.any()))
532
+ * })
533
+ * }
534
+ * });
535
+ *
536
+ * // Create a dedicated subscriber for this topic
537
+ * activityLogger = $subscriber({
538
+ * topic: this.userEvents,
539
+ * handler: async (message) => {
540
+ * const { userId, action, timestamp } = message.payload;
541
+ *
542
+ * await this.auditLogger.log({
543
+ * event: 'user_activity',
544
+ * userId,
545
+ * action,
546
+ * timestamp,
547
+ * source: 'user-activity-topic'
548
+ * });
549
+ *
550
+ * this.log.info(`User ${userId} performed ${action} at ${new Date(timestamp).toISOString()}`);
551
+ * }
552
+ * });
553
+ *
554
+ * async trackUserLogin(userId: string, metadata: Record<string, any>) {
555
+ * // Publish to topic - subscriber will automatically process it
556
+ * await this.userEvents.publish({
557
+ * userId,
558
+ * action: "login",
559
+ * timestamp: Date.now(),
560
+ * metadata
561
+ * });
562
+ * }
563
+ * }
564
+ * ```
565
+ *
566
+ * @example
567
+ * **Multiple specialized subscribers for different concerns:**
568
+ * ```ts
569
+ * class OrderEventHandlers {
570
+ * orderEvents = $topic({
571
+ * name: "order-events",
572
+ * schema: {
573
+ * payload: t.object({
574
+ * orderId: t.string(),
575
+ * customerId: t.string(),
576
+ * status: t.union([
577
+ * t.literal("created"),
578
+ * t.literal("paid"),
579
+ * t.literal("shipped"),
580
+ * t.literal("delivered")
581
+ * ]),
582
+ * data: t.optional(t.record(t.string(), t.any()))
583
+ * })
584
+ * }
585
+ * });
586
+ *
587
+ * // Analytics subscriber
588
+ * analyticsSubscriber = $subscriber({
589
+ * topic: this.orderEvents,
590
+ * handler: async (message) => {
591
+ * await this.analytics.track('order_status_changed', {
592
+ * orderId: message.payload.orderId,
593
+ * customerId: message.payload.customerId,
594
+ * status: message.payload.status,
595
+ * timestamp: Date.now()
596
+ * });
597
+ * }
598
+ * });
599
+ *
600
+ * // Email notification subscriber
601
+ * emailSubscriber = $subscriber({
602
+ * topic: this.orderEvents,
603
+ * handler: async (message) => {
604
+ * const { customerId, orderId, status } = message.payload;
605
+ *
606
+ * const templates = {
607
+ * 'paid': 'order-confirmation',
608
+ * 'shipped': 'order-shipped',
609
+ * 'delivered': 'order-delivered'
610
+ * };
611
+ *
612
+ * const template = templates[status];
613
+ * if (template) {
614
+ * await this.emailService.send({
615
+ * customerId,
616
+ * template,
617
+ * data: { orderId, status }
618
+ * });
619
+ * }
620
+ * }
621
+ * });
622
+ *
623
+ * // Inventory management subscriber
624
+ * inventorySubscriber = $subscriber({
625
+ * topic: this.orderEvents,
626
+ * handler: async (message) => {
627
+ * if (message.payload.status === 'paid') {
628
+ * await this.inventoryService.reserveItems(message.payload.orderId);
629
+ * } else if (message.payload.status === 'delivered') {
630
+ * await this.inventoryService.confirmDelivery(message.payload.orderId);
631
+ * }
632
+ * }
633
+ * });
634
+ * }
635
+ * ```
636
+ *
637
+ * @example
638
+ * **Subscriber with advanced error handling and filtering:**
639
+ * ```ts
640
+ * class NotificationSubscriber {
641
+ * systemEvents = $topic({
642
+ * name: "system-events",
643
+ * schema: {
644
+ * payload: t.object({
645
+ * eventType: t.string(),
646
+ * severity: t.enum(["info", "warning", "error"]),
647
+ * serviceId: t.string(),
648
+ * message: t.string(),
649
+ * data: t.optional(t.record(t.string(), t.any()))
650
+ * })
651
+ * }
652
+ * });
653
+ *
654
+ * alertSubscriber = $subscriber({
655
+ * topic: this.systemEvents,
656
+ * handler: async (message) => {
657
+ * const { eventType, severity, serviceId, message: eventMessage, data } = message.payload;
658
+ *
659
+ * try {
660
+ * // Only process error events for alerting
661
+ * if (severity !== 'error') {
662
+ * return;
663
+ * }
664
+ *
665
+ * // Log the event
666
+ * this.logger.error(`System alert from ${serviceId}`, {
667
+ * eventType,
668
+ * message: eventMessage,
669
+ * data
670
+ * });
671
+ *
672
+ * // Send alerts based on service criticality
673
+ * const criticalServices = ['payment', 'auth', 'database'];
674
+ * const isCritical = criticalServices.includes(serviceId);
675
+ *
676
+ * if (isCritical) {
677
+ * // Immediate alert for critical services
678
+ * await this.alertService.sendImmediate({
679
+ * title: `Critical Error in ${serviceId}`,
680
+ * message: eventMessage,
681
+ * severity: 'critical',
682
+ * metadata: { eventType, serviceId, data }
683
+ * });
684
+ * } else {
685
+ * // Queue non-critical alerts for batching
686
+ * await this.alertService.queueAlert({
687
+ * title: `Error in ${serviceId}`,
688
+ * message: eventMessage,
689
+ * severity: 'error',
690
+ * metadata: { eventType, serviceId, data }
691
+ * });
692
+ * }
693
+ *
694
+ * // Update service health status
695
+ * await this.healthMonitor.recordError(serviceId, eventType);
696
+ *
697
+ * } catch (error) {
698
+ * // Log subscriber errors but don't re-throw
699
+ * // This prevents one failing subscriber from affecting others
700
+ * this.log.error(`Alert subscriber failed`, {
701
+ * originalEvent: { eventType, serviceId, severity },
702
+ * subscriberError: error.message
703
+ * });
704
+ * }
705
+ * }
706
+ * });
707
+ * }
708
+ * ```
709
+ *
710
+ * @example
711
+ * **Subscriber for real-time data aggregation:**
712
+ * ```ts
713
+ * class MetricsAggregator {
714
+ * userActivityTopic = $topic({
715
+ * name: "user-metrics",
716
+ * schema: {
717
+ * payload: t.object({
718
+ * userId: t.string(),
719
+ * sessionId: t.string(),
720
+ * eventType: t.string(),
721
+ * timestamp: t.number(),
722
+ * duration: t.optional(t.number()),
723
+ * metadata: t.optional(t.record(t.string(), t.any()))
724
+ * })
725
+ * }
726
+ * });
727
+ *
728
+ * metricsSubscriber = $subscriber({
729
+ * topic: this.userActivityTopic,
730
+ * handler: async (message) => {
731
+ * const { userId, sessionId, eventType, timestamp, duration, metadata } = message.payload;
732
+ *
733
+ * // Update real-time metrics
734
+ * await Promise.all([
735
+ * // Update user activity counters
736
+ * this.metricsStore.increment(`user:${userId}:events:${eventType}`, 1),
737
+ * this.metricsStore.increment(`global:events:${eventType}`, 1),
738
+ *
739
+ * // Track session activity
740
+ * this.sessionStore.updateActivity(sessionId, timestamp),
741
+ *
742
+ * // Record duration metrics if provided
743
+ * duration ? this.metricsStore.recordDuration(`events:${eventType}:duration`, duration) : Promise.resolve(),
744
+ *
745
+ * // Update time-based aggregations
746
+ * this.timeSeriesStore.addPoint({
747
+ * metric: `user_activity.${eventType}`,
748
+ * timestamp,
749
+ * value: 1,
750
+ * tags: { userId, sessionId }
751
+ * })
752
+ * ]);
753
+ *
754
+ * // Trigger real-time dashboard updates
755
+ * await this.dashboardService.updateRealTimeStats({
756
+ * eventType,
757
+ * userId,
758
+ * timestamp
759
+ * });
760
+ *
761
+ * this.logger.debug(`Processed metrics for ${eventType}`, {
762
+ * userId,
763
+ * eventType,
764
+ * timestamp
765
+ * });
766
+ * }
767
+ * });
768
+ * }
769
+ * ```
105
770
  */
106
771
  declare const $subscriber: {
107
772
  <T extends TopicMessageSchema>(options: SubscriberDescriptorOptions<T>): SubscriberDescriptor<T>;
108
773
  [KIND]: typeof SubscriberDescriptor;
109
774
  };
110
775
  interface SubscriberDescriptorOptions<T extends TopicMessageSchema> {
776
+ /**
777
+ * The topic descriptor that this subscriber will listen to for messages.
778
+ *
779
+ * This establishes the connection between the subscriber and its source topic:
780
+ * - The subscriber inherits the topic's message schema for type safety
781
+ * - Messages published to the topic will be automatically delivered to this subscriber
782
+ * - Multiple subscribers can listen to the same topic independently
783
+ * - The subscriber will use the topic's provider and configuration settings
784
+ *
785
+ * **Topic Integration Benefits**:
786
+ * - Type safety: Subscriber handler gets fully typed message payloads
787
+ * - Schema validation: Messages are validated before reaching the subscriber
788
+ * - Real-time delivery: Messages are delivered immediately upon publication
789
+ * - Error isolation: Subscriber errors don't affect the topic or other subscribers
790
+ * - Monitoring: Topic metrics include subscriber processing statistics
791
+ *
792
+ * @example
793
+ * ```ts
794
+ * // First, define a topic
795
+ * userEvents = $topic({
796
+ * name: "user-activity",
797
+ * schema: {
798
+ * payload: t.object({ userId: t.string(), action: t.string() })
799
+ * }
800
+ * });
801
+ *
802
+ * // Then, create a subscriber for that topic
803
+ * activitySubscriber = $subscriber({
804
+ * topic: this.userEvents, // Reference the topic descriptor
805
+ * handler: async (message) => { } // Process messages here
806
+ * });
807
+ * ```
808
+ */
111
809
  topic: TopicDescriptor<T>;
810
+ /**
811
+ * Message handler function that processes individual messages from the topic.
812
+ *
813
+ * This function:
814
+ * - Receives fully typed and validated message payloads from the connected topic
815
+ * - Executes immediately when messages are published to the topic
816
+ * - Should implement the core business logic for reacting to these events
817
+ * - Runs independently of other subscribers to the same topic
818
+ * - Should handle errors gracefully to avoid affecting other subscribers
819
+ * - Has access to the full Alepha dependency injection container
820
+ *
821
+ * **Handler Design Guidelines**:
822
+ * - Keep handlers focused on a single responsibility
823
+ * - Use proper error handling and logging
824
+ * - Consider performance impact for high-frequency topics
825
+ * - Make handlers idempotent when possible for reliability
826
+ * - Validate business rules within the handler logic
827
+ * - Log important processing steps for debugging and monitoring
828
+ *
829
+ * **Error Handling Strategy**:
830
+ * - Log errors but don't re-throw to avoid affecting other subscribers
831
+ * - Use try-catch blocks for external service calls
832
+ * - Implement circuit breakers for resilience with external systems
833
+ * - Monitor error rates and patterns for system health
834
+ * - Consider implementing retry logic for temporary failures
835
+ *
836
+ * **Performance Considerations**:
837
+ * - Keep handler execution time minimal for high-throughput topics
838
+ * - Use background queues for heavy processing triggered by events
839
+ * - Implement batching for efficiency when processing many similar events
840
+ * - Consider async processing patterns for non-critical operations
841
+ *
842
+ * @param message - The topic message with validated payload and optional headers
843
+ * @param message.payload - The typed message data based on the topic's schema
844
+ * @returns Promise that resolves when processing is complete
845
+ *
846
+ * @example
847
+ * ```ts
848
+ * handler: async (message) => {
849
+ * const { userId, eventType, timestamp } = message.payload;
850
+ *
851
+ * try {
852
+ * // Log event receipt
853
+ * this.logger.info(`Processing ${eventType} event for user ${userId}`, {
854
+ * timestamp,
855
+ * userId,
856
+ * eventType
857
+ * });
858
+ *
859
+ * // Perform event-specific processing
860
+ * switch (eventType) {
861
+ * case 'user.login':
862
+ * await this.updateLastLogin(userId, timestamp);
863
+ * await this.sendWelcomeNotification(userId);
864
+ * break;
865
+ * case 'user.logout':
866
+ * await this.updateSessionDuration(userId, timestamp);
867
+ * break;
868
+ * case 'user.purchase':
869
+ * await this.updateRewardsPoints(userId, message.payload.purchaseAmount);
870
+ * await this.triggerRecommendations(userId);
871
+ * break;
872
+ * default:
873
+ * this.logger.warn(`Unknown event type: ${eventType}`);
874
+ * }
875
+ *
876
+ * // Update analytics
877
+ * await this.analytics.track(eventType, {
878
+ * userId,
879
+ * timestamp,
880
+ * source: 'topic-subscriber'
881
+ * });
882
+ *
883
+ * this.logger.info(`Successfully processed ${eventType} for user ${userId}`);
884
+ *
885
+ * } catch (error) {
886
+ * // Log error but don't re-throw to avoid affecting other subscribers
887
+ * this.logger.error(`Failed to process ${eventType} for user ${userId}`, {
888
+ * error: error.message,
889
+ * stack: error.stack,
890
+ * userId,
891
+ * eventType,
892
+ * timestamp
893
+ * });
894
+ *
895
+ * // Optionally send to error tracking service
896
+ * await this.errorTracker.captureException(error, {
897
+ * context: { userId, eventType, timestamp },
898
+ * tags: { component: 'topic-subscriber' }
899
+ * });
900
+ * }
901
+ * }
902
+ * ```
903
+ */
112
904
  handler: TopicHandler<T>;
113
905
  }
114
906
  declare class SubscriberDescriptor<T extends TopicMessageSchema> extends Descriptor<SubscriberDescriptorOptions<T>> {}