-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathevents.zod.ts
More file actions
763 lines (649 loc) · 21 KB
/
events.zod.ts
File metadata and controls
763 lines (649 loc) · 21 KB
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
import { z } from 'zod';
import { EventNameSchema } from '../shared/identifiers.zod';
// ==========================================
// Event Priority
// ==========================================
/**
* Event Priority Enum
* Priority levels for event processing
* Lower numbers = higher priority
*/
export const EventPriority = z.enum([
'critical', // 0 - Process immediately, block if necessary
'high', // 1 - Process soon, minimal delay
'normal', // 2 - Default priority
'low', // 3 - Process when resources available
'background', // 4 - Process during idle time
]);
export type EventPriority = z.infer<typeof EventPriority>;
/**
* Event Priority Values
* Maps priority names to numeric values for sorting
*/
export const EVENT_PRIORITY_VALUES: Record<EventPriority, number> = {
critical: 0,
high: 1,
normal: 2,
low: 3,
background: 4,
};
// ==========================================
// Event Metadata
// ==========================================
/**
* Event Metadata Schema
* Metadata associated with every event
*/
export const EventMetadataSchema = z.object({
source: z.string().describe('Event source (e.g., plugin name, system component)'),
timestamp: z.string().datetime().describe('ISO 8601 datetime when event was created'),
userId: z.string().optional().describe('User who triggered the event'),
tenantId: z.string().optional().describe('Tenant identifier for multi-tenant systems'),
correlationId: z.string().optional().describe('Correlation ID for event tracing'),
causationId: z.string().optional().describe('ID of the event that caused this event'),
priority: EventPriority.optional().default('normal').describe('Event priority'),
});
// ==========================================
// Event Schema
// ==========================================
/**
* Event Type Definition Schema
* Defines the structure of an event type
*
* @example
* {
* "name": "order.created",
* "version": "1.0.0",
* "schema": {
* "type": "object",
* "properties": {
* "orderId": { "type": "string" },
* "customerId": { "type": "string" },
* "total": { "type": "number" }
* }
* }
* }
*/
export const EventTypeDefinitionSchema = z.object({
name: EventNameSchema.describe('Event type name (lowercase with dots)'),
version: z.string().default('1.0.0').describe('Event schema version'),
schema: z.unknown().optional().describe('JSON Schema for event payload validation'),
description: z.string().optional().describe('Event type description'),
deprecated: z.boolean().optional().default(false).describe('Whether this event type is deprecated'),
tags: z.array(z.string()).optional().describe('Event type tags'),
});
export type EventTypeDefinition = z.infer<typeof EventTypeDefinitionSchema>;
/**
* Event Schema
* Base schema for all events in the system
*
* Event names follow dot notation for namespacing (e.g., 'user.created', 'order.paid').
* This aligns with industry standards for event-driven architectures and message queues.
*/
export const EventSchema = z.object({
/**
* Event identifier (for tracking and deduplication)
*/
id: z.string().optional().describe('Unique event identifier'),
/**
* Event name
*/
name: EventNameSchema.describe('Event name (lowercase with dots, e.g., user.created, order.paid)'),
/**
* Event payload
*/
payload: z.unknown().describe('Event payload schema'),
/**
* Event metadata
*/
metadata: EventMetadataSchema.describe('Event metadata'),
});
export type Event = z.infer<typeof EventSchema>;
// ==========================================
// Event Handlers
// ==========================================
/**
* Event Handler Schema
* Defines how to handle a specific event
*/
export const EventHandlerSchema = z.object({
/**
* Handler identifier
*/
id: z.string().optional().describe('Unique handler identifier'),
/**
* Event name pattern
*/
eventName: z.string().describe('Name of event to handle (supports wildcards like user.*)'),
/**
* Handler function
*/
handler: z.unknown()
.describe('Handler function'),
/**
* Execution priority
*/
priority: z.number().int().default(0).describe('Execution priority (lower numbers execute first)'),
/**
* Async execution
*/
async: z.boolean().default(true).describe('Execute in background (true) or block (false)'),
/**
* Retry configuration
*/
retry: z.object({
maxRetries: z.number().int().min(0).default(3).describe('Maximum retry attempts'),
backoffMs: z.number().int().positive().default(1000).describe('Initial backoff delay'),
backoffMultiplier: z.number().positive().default(2).describe('Backoff multiplier'),
}).optional().describe('Retry policy for failed handlers'),
/**
* Timeout
*/
timeoutMs: z.number().int().positive().optional().describe('Handler timeout in milliseconds'),
/**
* Filter function
*/
filter: z.unknown()
.optional()
.describe('Optional filter to determine if handler should execute'),
});
export type EventHandler = z.infer<typeof EventHandlerSchema>;
/**
* Event Route Schema
* Routes events from one pattern to multiple targets with optional transformation
*/
export const EventRouteSchema = z.object({
from: z.string().describe('Source event pattern (supports wildcards, e.g., user.* or *.created)'),
to: z.array(z.string()).describe('Target event names to route to'),
transform: z.unknown().optional().describe('Optional function to transform payload'),
});
export type EventRoute = z.infer<typeof EventRouteSchema>;
/**
* Event Persistence Schema
* Configuration for persisting events to storage
*/
export const EventPersistenceSchema = z.object({
enabled: z.boolean().default(false).describe('Enable event persistence'),
retention: z.number().int().positive().describe('Days to retain persisted events'),
filter: z.unknown().optional().describe('Optional filter function to select which events to persist'),
storage: z.enum(['database', 'file', 's3', 'custom']).default('database')
.describe('Storage backend for persisted events'),
});
export type EventPersistence = z.infer<typeof EventPersistenceSchema>;
// ==========================================
// Event Queue
// ==========================================
/**
* Event Queue Configuration Schema
* Configuration for async event processing queue
*
* @example
* {
* "name": "event_queue",
* "concurrency": 10,
* "retryPolicy": {
* "maxRetries": 3,
* "backoffStrategy": "exponential"
* }
* }
*/
export const EventQueueConfigSchema = z.object({
/**
* Queue name
*/
name: z.string().default('events').describe('Event queue name'),
/**
* Concurrency
*/
concurrency: z.number().int().min(1).default(10).describe('Max concurrent event handlers'),
/**
* Retry policy
*/
retryPolicy: z.object({
maxRetries: z.number().int().min(0).default(3).describe('Max retries for failed events'),
backoffStrategy: z.enum(['fixed', 'linear', 'exponential']).default('exponential')
.describe('Backoff strategy'),
initialDelayMs: z.number().int().positive().default(1000).describe('Initial retry delay'),
maxDelayMs: z.number().int().positive().default(60000).describe('Maximum retry delay'),
}).optional().describe('Default retry policy for events'),
/**
* Dead letter queue
*/
deadLetterQueue: z.string().optional().describe('Dead letter queue name for failed events'),
/**
* Enable priority processing
*/
priorityEnabled: z.boolean().default(true).describe('Process events based on priority'),
});
export type EventQueueConfig = z.infer<typeof EventQueueConfigSchema>;
// ==========================================
// Event Replay
// ==========================================
/**
* Event Replay Configuration Schema
* Configuration for replaying historical events
*
* @example
* {
* "fromTimestamp": "2024-01-01T00:00:00Z",
* "toTimestamp": "2024-01-31T23:59:59Z",
* "eventTypes": ["order.created", "order.updated"],
* "speed": 10
* }
*/
export const EventReplayConfigSchema = z.object({
/**
* Start timestamp
*/
fromTimestamp: z.string().datetime().describe('Start timestamp for replay (ISO 8601)'),
/**
* End timestamp
*/
toTimestamp: z.string().datetime().optional().describe('End timestamp for replay (ISO 8601)'),
/**
* Event types to replay
*/
eventTypes: z.array(z.string()).optional().describe('Event types to replay (empty = all)'),
/**
* Event filters
*/
filters: z.record(z.string(), z.unknown()).optional().describe('Additional filters for event selection'),
/**
* Replay speed multiplier
*/
speed: z.number().positive().default(1).describe('Replay speed multiplier (1 = real-time)'),
/**
* Target handlers
*/
targetHandlers: z.array(z.string()).optional().describe('Handler IDs to execute (empty = all)'),
});
export type EventReplayConfig = z.infer<typeof EventReplayConfigSchema>;
// ==========================================
// Event Sourcing
// ==========================================
/**
* Event Sourcing Configuration Schema
* Configuration for event sourcing pattern
*
* Event sourcing stores all changes to application state as a sequence of events.
* The current state can be reconstructed by replaying the events.
*
* @example
* {
* "enabled": true,
* "snapshotInterval": 100,
* "retention": 365
* }
*/
export const EventSourcingConfigSchema = z.object({
/**
* Enable event sourcing
*/
enabled: z.boolean().default(false).describe('Enable event sourcing'),
/**
* Snapshot interval
*/
snapshotInterval: z.number().int().positive().default(100)
.describe('Create snapshot every N events'),
/**
* Snapshot retention
*/
snapshotRetention: z.number().int().positive().default(10)
.describe('Number of snapshots to retain'),
/**
* Event retention
*/
retention: z.number().int().positive().default(365)
.describe('Days to retain events'),
/**
* Aggregate types
*/
aggregateTypes: z.array(z.string()).optional()
.describe('Aggregate types to enable event sourcing for'),
/**
* Storage configuration
*/
storage: z.object({
type: z.enum(['database', 'file', 's3', 'eventstore']).default('database')
.describe('Storage backend'),
options: z.record(z.string(), z.unknown()).optional().describe('Storage-specific options'),
}).optional().describe('Event store configuration'),
});
export type EventSourcingConfig = z.infer<typeof EventSourcingConfigSchema>;
// ==========================================
// Dead Letter Queue
// ==========================================
/**
* Dead Letter Queue Entry Schema
* Represents a failed event in the dead letter queue
*/
export const DeadLetterQueueEntrySchema = z.object({
/**
* Entry identifier
*/
id: z.string().describe('Unique entry identifier'),
/**
* Original event
*/
event: EventSchema.describe('Original event'),
/**
* Failure reason
*/
error: z.object({
message: z.string().describe('Error message'),
stack: z.string().optional().describe('Error stack trace'),
code: z.string().optional().describe('Error code'),
}).describe('Failure details'),
/**
* Retry count
*/
retries: z.number().int().min(0).describe('Number of retry attempts'),
/**
* Timestamps
*/
firstFailedAt: z.string().datetime().describe('When event first failed'),
lastFailedAt: z.string().datetime().describe('When event last failed'),
/**
* Handler that failed
*/
failedHandler: z.string().optional().describe('Handler ID that failed'),
});
export type DeadLetterQueueEntry = z.infer<typeof DeadLetterQueueEntrySchema>;
// ==========================================
// Event Log
// ==========================================
/**
* Event Log Entry Schema
* Represents a logged event
*/
export const EventLogEntrySchema = z.object({
/**
* Log entry ID
*/
id: z.string().describe('Unique log entry identifier'),
/**
* Event
*/
event: EventSchema.describe('The event'),
/**
* Status
*/
status: z.enum(['pending', 'processing', 'completed', 'failed']).describe('Processing status'),
/**
* Handlers executed
*/
handlersExecuted: z.array(z.object({
handlerId: z.string().describe('Handler identifier'),
status: z.enum(['success', 'failed', 'timeout']).describe('Handler execution status'),
durationMs: z.number().int().optional().describe('Execution duration'),
error: z.string().optional().describe('Error message if failed'),
})).optional().describe('Handlers that processed this event'),
/**
* Timestamps
*/
receivedAt: z.string().datetime().describe('When event was received'),
processedAt: z.string().datetime().optional().describe('When event was processed'),
/**
* Total duration
*/
totalDurationMs: z.number().int().optional().describe('Total processing time'),
});
export type EventLogEntry = z.infer<typeof EventLogEntrySchema>;
// ==========================================
// Webhook Integration
// ==========================================
/**
* Event Webhook Configuration Schema
* Configuration for sending events to webhooks
*
* @example
* {
* "eventPattern": "order.*",
* "url": "https://api.example.com/webhooks/orders",
* "method": "POST",
* "headers": { "Authorization": "Bearer token" }
* }
*/
export const EventWebhookConfigSchema = z.object({
/**
* Webhook identifier
*/
id: z.string().optional().describe('Unique webhook identifier'),
/**
* Event pattern to match
*/
eventPattern: z.string().describe('Event name pattern (supports wildcards)'),
/**
* Target URL
*/
url: z.string().url().describe('Webhook endpoint URL'),
/**
* HTTP method
*/
method: z.enum(['GET', 'POST', 'PUT', 'PATCH']).default('POST').describe('HTTP method'),
/**
* Headers
*/
headers: z.record(z.string(), z.string()).optional().describe('HTTP headers'),
/**
* Authentication
*/
authentication: z.object({
type: z.enum(['none', 'bearer', 'basic', 'api-key']).describe('Auth type'),
credentials: z.record(z.string(), z.string()).optional().describe('Auth credentials'),
}).optional().describe('Authentication configuration'),
/**
* Retry policy
*/
retryPolicy: z.object({
maxRetries: z.number().int().min(0).default(3).describe('Max retry attempts'),
backoffStrategy: z.enum(['fixed', 'linear', 'exponential']).default('exponential'),
initialDelayMs: z.number().int().positive().default(1000).describe('Initial retry delay'),
maxDelayMs: z.number().int().positive().default(60000).describe('Max retry delay'),
}).optional().describe('Retry policy'),
/**
* Timeout
*/
timeoutMs: z.number().int().positive().default(30000).describe('Request timeout in milliseconds'),
/**
* Event transformation
*/
transform: z.unknown()
.optional()
.describe('Transform event before sending'),
/**
* Enabled
*/
enabled: z.boolean().default(true).describe('Whether webhook is enabled'),
});
export type EventWebhookConfig = z.infer<typeof EventWebhookConfigSchema>;
// ==========================================
// Message Queue Integration
// ==========================================
/**
* Event Message Queue Configuration Schema
* Configuration for publishing events to message queues
*
* @example
* {
* "provider": "kafka",
* "topic": "events",
* "eventPattern": "*",
* "partitionKey": "metadata.tenantId"
* }
*/
export const EventMessageQueueConfigSchema = z.object({
/**
* Provider
*/
provider: z.enum(['kafka', 'rabbitmq', 'aws-sqs', 'redis-pubsub', 'google-pubsub', 'azure-service-bus'])
.describe('Message queue provider'),
/**
* Topic/Queue name
*/
topic: z.string().describe('Topic or queue name'),
/**
* Event pattern
*/
eventPattern: z.string().default('*').describe('Event name pattern to publish (supports wildcards)'),
/**
* Partition key
*/
partitionKey: z.string().optional().describe('JSON path for partition key (e.g., "metadata.tenantId")'),
/**
* Message format
*/
format: z.enum(['json', 'avro', 'protobuf']).default('json').describe('Message serialization format'),
/**
* Include metadata
*/
includeMetadata: z.boolean().default(true).describe('Include event metadata in message'),
/**
* Compression
*/
compression: z.enum(['none', 'gzip', 'snappy', 'lz4']).default('none').describe('Message compression'),
/**
* Batch size
*/
batchSize: z.number().int().min(1).default(1).describe('Batch size for publishing'),
/**
* Flush interval
*/
flushIntervalMs: z.number().int().positive().default(1000).describe('Flush interval for batching'),
});
export type EventMessageQueueConfig = z.infer<typeof EventMessageQueueConfigSchema>;
// ==========================================
// Real-time Notifications
// ==========================================
/**
* Real-time Notification Configuration Schema
* Configuration for real-time event notifications via WebSocket/SSE
*
* @example
* {
* "enabled": true,
* "protocol": "websocket",
* "eventPattern": "notification.*",
* "userFilter": true
* }
*/
export const RealTimeNotificationConfigSchema = z.object({
/**
* Enable real-time notifications
*/
enabled: z.boolean().default(true).describe('Enable real-time notifications'),
/**
* Protocol
*/
protocol: z.enum(['websocket', 'sse', 'long-polling']).default('websocket')
.describe('Real-time protocol'),
/**
* Event pattern
*/
eventPattern: z.string().default('*').describe('Event pattern to broadcast'),
/**
* User-specific filtering
*/
userFilter: z.boolean().default(true).describe('Filter events by user'),
/**
* Tenant-specific filtering
*/
tenantFilter: z.boolean().default(true).describe('Filter events by tenant'),
/**
* Channels
*/
channels: z.array(z.object({
name: z.string().describe('Channel name'),
eventPattern: z.string().describe('Event pattern for channel'),
filter: z.unknown()
.optional()
.describe('Additional filter function'),
})).optional().describe('Named channels for event broadcasting'),
/**
* Rate limiting
*/
rateLimit: z.object({
maxEventsPerSecond: z.number().int().positive().describe('Max events per second per client'),
windowMs: z.number().int().positive().default(1000).describe('Rate limit window'),
}).optional().describe('Rate limiting configuration'),
});
export type RealTimeNotificationConfig = z.infer<typeof RealTimeNotificationConfigSchema>;
// ==========================================
// Complete Event Bus Configuration
// ==========================================
/**
* Event Bus Configuration Schema
* Complete configuration for the event bus system
*
* @example
* {
* "persistence": { "enabled": true, "retention": 365 },
* "queue": { "concurrency": 20 },
* "eventSourcing": { "enabled": true },
* "webhooks": [],
* "messageQueue": { "provider": "kafka", "topic": "events" },
* "realtime": { "enabled": true, "protocol": "websocket" }
* }
*/
export const EventBusConfigSchema = z.object({
/**
* Event persistence
*/
persistence: EventPersistenceSchema.optional().describe('Event persistence configuration'),
/**
* Event queue
*/
queue: EventQueueConfigSchema.optional().describe('Event queue configuration'),
/**
* Event sourcing
*/
eventSourcing: EventSourcingConfigSchema.optional().describe('Event sourcing configuration'),
/**
* Event replay
*/
replay: z.object({
enabled: z.boolean().default(true).describe('Enable event replay capability'),
}).optional().describe('Event replay configuration'),
/**
* Webhooks
*/
webhooks: z.array(EventWebhookConfigSchema).optional().describe('Webhook configurations'),
/**
* Message queue integration
*/
messageQueue: EventMessageQueueConfigSchema.optional().describe('Message queue integration'),
/**
* Real-time notifications
*/
realtime: RealTimeNotificationConfigSchema.optional().describe('Real-time notification configuration'),
/**
* Event type definitions
*/
eventTypes: z.array(EventTypeDefinitionSchema).optional().describe('Event type definitions'),
/**
* Global handlers
*/
handlers: z.array(EventHandlerSchema).optional().describe('Global event handlers'),
});
export type EventBusConfig = z.infer<typeof EventBusConfigSchema>;
// ==========================================
// Helper Functions
// ==========================================
/**
* Helper to create event bus configuration
*/
export function createEventBusConfig<T extends z.input<typeof EventBusConfigSchema>>(config: T): T {
return config;
}
/**
* Helper to create event type definition
*/
export function createEventTypeDefinition<T extends z.input<typeof EventTypeDefinitionSchema>>(definition: T): T {
return definition;
}
/**
* Helper to create event webhook configuration
*/
export function createEventWebhookConfig<T extends z.input<typeof EventWebhookConfigSchema>>(config: T): T {
return config;
}