@omnitron-dev/titan-notifications 0.1.1

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.
Files changed (150) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +19 -0
  3. package/dist/channel/channel-registry.d.ts +40 -0
  4. package/dist/channel/channel-registry.d.ts.map +1 -0
  5. package/dist/channel/channel-registry.js +157 -0
  6. package/dist/channel/channel-registry.js.map +1 -0
  7. package/dist/channel/channel.interface.d.ts +77 -0
  8. package/dist/channel/channel.interface.d.ts.map +1 -0
  9. package/dist/channel/channel.interface.js +9 -0
  10. package/dist/channel/channel.interface.js.map +1 -0
  11. package/dist/channel/channels/email.channel.d.ts +43 -0
  12. package/dist/channel/channels/email.channel.d.ts.map +1 -0
  13. package/dist/channel/channels/email.channel.js +211 -0
  14. package/dist/channel/channels/email.channel.js.map +1 -0
  15. package/dist/channel/channels/inapp.channel.d.ts +41 -0
  16. package/dist/channel/channels/inapp.channel.d.ts.map +1 -0
  17. package/dist/channel/channels/inapp.channel.js +308 -0
  18. package/dist/channel/channels/inapp.channel.js.map +1 -0
  19. package/dist/channel/channels/index.d.ts +11 -0
  20. package/dist/channel/channels/index.d.ts.map +1 -0
  21. package/dist/channel/channels/index.js +6 -0
  22. package/dist/channel/channels/index.js.map +1 -0
  23. package/dist/channel/channels/push.channel.d.ts +51 -0
  24. package/dist/channel/channels/push.channel.d.ts.map +1 -0
  25. package/dist/channel/channels/push.channel.js +179 -0
  26. package/dist/channel/channels/push.channel.js.map +1 -0
  27. package/dist/channel/channels/sms.channel.d.ts +45 -0
  28. package/dist/channel/channels/sms.channel.d.ts.map +1 -0
  29. package/dist/channel/channels/sms.channel.js +170 -0
  30. package/dist/channel/channels/sms.channel.js.map +1 -0
  31. package/dist/channel/channels/webhook.channel.d.ts +39 -0
  32. package/dist/channel/channels/webhook.channel.d.ts.map +1 -0
  33. package/dist/channel/channels/webhook.channel.js +217 -0
  34. package/dist/channel/channels/webhook.channel.js.map +1 -0
  35. package/dist/channel/index.d.ts +5 -0
  36. package/dist/channel/index.d.ts.map +1 -0
  37. package/dist/channel/index.js +4 -0
  38. package/dist/channel/index.js.map +1 -0
  39. package/dist/index.d.ts +35 -0
  40. package/dist/index.d.ts.map +1 -0
  41. package/dist/index.js +17 -0
  42. package/dist/index.js.map +1 -0
  43. package/dist/notifications.decorators.d.ts +14 -0
  44. package/dist/notifications.decorators.d.ts.map +1 -0
  45. package/dist/notifications.decorators.js +24 -0
  46. package/dist/notifications.decorators.js.map +1 -0
  47. package/dist/notifications.events.d.ts +83 -0
  48. package/dist/notifications.events.d.ts.map +1 -0
  49. package/dist/notifications.events.js +118 -0
  50. package/dist/notifications.events.js.map +1 -0
  51. package/dist/notifications.health.d.ts +16 -0
  52. package/dist/notifications.health.d.ts.map +1 -0
  53. package/dist/notifications.health.js +63 -0
  54. package/dist/notifications.health.js.map +1 -0
  55. package/dist/notifications.module.d.ts +27 -0
  56. package/dist/notifications.module.d.ts.map +1 -0
  57. package/dist/notifications.module.js +533 -0
  58. package/dist/notifications.module.js.map +1 -0
  59. package/dist/notifications.service.d.ts +43 -0
  60. package/dist/notifications.service.d.ts.map +1 -0
  61. package/dist/notifications.service.js +394 -0
  62. package/dist/notifications.service.js.map +1 -0
  63. package/dist/notifications.tokens.d.ts +31 -0
  64. package/dist/notifications.tokens.d.ts.map +1 -0
  65. package/dist/notifications.tokens.js +14 -0
  66. package/dist/notifications.tokens.js.map +1 -0
  67. package/dist/notifications.types.d.ts +234 -0
  68. package/dist/notifications.types.d.ts.map +1 -0
  69. package/dist/notifications.types.js +2 -0
  70. package/dist/notifications.types.js.map +1 -0
  71. package/dist/publisher.d.ts +35 -0
  72. package/dist/publisher.d.ts.map +1 -0
  73. package/dist/publisher.js +18 -0
  74. package/dist/publisher.js.map +1 -0
  75. package/dist/redis-preference-store.d.ts +68 -0
  76. package/dist/redis-preference-store.d.ts.map +1 -0
  77. package/dist/redis-preference-store.js +291 -0
  78. package/dist/redis-preference-store.js.map +1 -0
  79. package/dist/redis-rate-limiter.d.ts +67 -0
  80. package/dist/redis-rate-limiter.d.ts.map +1 -0
  81. package/dist/redis-rate-limiter.js +270 -0
  82. package/dist/redis-rate-limiter.js.map +1 -0
  83. package/dist/rotif/dlq-manager.d.ts +53 -0
  84. package/dist/rotif/dlq-manager.d.ts.map +1 -0
  85. package/dist/rotif/dlq-manager.js +249 -0
  86. package/dist/rotif/dlq-manager.js.map +1 -0
  87. package/dist/rotif/index.d.ts +7 -0
  88. package/dist/rotif/index.d.ts.map +1 -0
  89. package/dist/rotif/index.js +7 -0
  90. package/dist/rotif/index.js.map +1 -0
  91. package/dist/rotif/middleware.d.ts +22 -0
  92. package/dist/rotif/middleware.d.ts.map +1 -0
  93. package/dist/rotif/middleware.js +39 -0
  94. package/dist/rotif/middleware.js.map +1 -0
  95. package/dist/rotif/rotif.d.ts +88 -0
  96. package/dist/rotif/rotif.d.ts.map +1 -0
  97. package/dist/rotif/rotif.js +948 -0
  98. package/dist/rotif/rotif.js.map +1 -0
  99. package/dist/rotif/stats.d.ts +12 -0
  100. package/dist/rotif/stats.d.ts.map +1 -0
  101. package/dist/rotif/stats.js +27 -0
  102. package/dist/rotif/stats.js.map +1 -0
  103. package/dist/rotif/types.d.ts +92 -0
  104. package/dist/rotif/types.d.ts.map +1 -0
  105. package/dist/rotif/types.js +2 -0
  106. package/dist/rotif/types.js.map +1 -0
  107. package/dist/rotif/utils.d.ts +40 -0
  108. package/dist/rotif/utils.d.ts.map +1 -0
  109. package/dist/rotif/utils.js +156 -0
  110. package/dist/rotif/utils.js.map +1 -0
  111. package/dist/template-engine.d.ts +97 -0
  112. package/dist/template-engine.d.ts.map +1 -0
  113. package/dist/template-engine.js +290 -0
  114. package/dist/template-engine.js.map +1 -0
  115. package/dist/transport/index.d.ts +4 -0
  116. package/dist/transport/index.d.ts.map +1 -0
  117. package/dist/transport/index.js +3 -0
  118. package/dist/transport/index.js.map +1 -0
  119. package/dist/transport/rotif.transport.d.ts +29 -0
  120. package/dist/transport/rotif.transport.d.ts.map +1 -0
  121. package/dist/transport/rotif.transport.js +301 -0
  122. package/dist/transport/rotif.transport.js.map +1 -0
  123. package/dist/transport/transport.interface.d.ts +130 -0
  124. package/dist/transport/transport.interface.d.ts.map +1 -0
  125. package/dist/transport/transport.interface.js +8 -0
  126. package/dist/transport/transport.interface.js.map +1 -0
  127. package/dist/worker/index.d.ts +4 -0
  128. package/dist/worker/index.d.ts.map +1 -0
  129. package/dist/worker/index.js +3 -0
  130. package/dist/worker/index.js.map +1 -0
  131. package/dist/worker/notification-worker.d.ts +41 -0
  132. package/dist/worker/notification-worker.d.ts.map +1 -0
  133. package/dist/worker/notification-worker.js +229 -0
  134. package/dist/worker/notification-worker.js.map +1 -0
  135. package/dist/worker/worker.interfaces.d.ts +41 -0
  136. package/dist/worker/worker.interfaces.d.ts.map +1 -0
  137. package/dist/worker/worker.interfaces.js +2 -0
  138. package/dist/worker/worker.interfaces.js.map +1 -0
  139. package/dist/worker/worker.tokens.d.ts +6 -0
  140. package/dist/worker/worker.tokens.d.ts.map +1 -0
  141. package/dist/worker/worker.tokens.js +5 -0
  142. package/dist/worker/worker.tokens.js.map +1 -0
  143. package/lua/rotif/ack-message.lua +19 -0
  144. package/lua/rotif/move-scheduled-messages.lua +38 -0
  145. package/lua/rotif/move-to-dlq.lua +41 -0
  146. package/lua/rotif/publish-message.lua +89 -0
  147. package/lua/rotif/requeue-from-dlq.lua +40 -0
  148. package/lua/rotif/retry-message.lua +49 -0
  149. package/lua/rotif/safe-unsubscribe.lua +8 -0
  150. package/package.json +67 -0
@@ -0,0 +1,291 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ var RedisPreferenceStore_1;
14
+ import { Injectable, Optional } from '@omnitron-dev/titan/decorators';
15
+ import { safeJsonParse } from '@omnitron-dev/titan/utils';
16
+ const DEFAULT_PREFERENCES = {
17
+ channels: {
18
+ email: { enabled: true },
19
+ push: { enabled: true },
20
+ sms: { enabled: false },
21
+ inApp: { enabled: true },
22
+ webhook: { enabled: false },
23
+ },
24
+ globalMute: false,
25
+ locale: 'en',
26
+ timezone: 'UTC',
27
+ allowUrgent: true,
28
+ quietHours: {
29
+ enabled: false,
30
+ start: '22:00',
31
+ end: '08:00',
32
+ timezone: 'UTC',
33
+ exceptions: [],
34
+ },
35
+ };
36
+ let RedisPreferenceStore = class RedisPreferenceStore {
37
+ static { RedisPreferenceStore_1 = this; }
38
+ static { this.MAX_MEMORY_PREFERENCES = 10000; }
39
+ static { this.MAX_MEMORY_COUNTERS = 50000; }
40
+ constructor(redis, options) {
41
+ this.redis = redis;
42
+ this.memoryStore = new Map();
43
+ this.counterStore = new Map();
44
+ this.keyPrefix = options?.keyPrefix ?? 'notifications:prefs:';
45
+ this.defaultPreferences = { ...DEFAULT_PREFERENCES, ...options?.defaultPreferences };
46
+ this.counterTTL = options?.counterTTL ?? 86400;
47
+ }
48
+ async getPreferences(recipientId) {
49
+ if (this.redis) {
50
+ const key = this.buildKey(recipientId);
51
+ const data = await this.redis.get(key);
52
+ return data ? safeJsonParse(data) : null;
53
+ }
54
+ return this.memoryStore.get(recipientId) ?? null;
55
+ }
56
+ async setPreferences(recipientId, preferences) {
57
+ const fullPrefs = {
58
+ ...this.defaultPreferences,
59
+ ...preferences,
60
+ channels: {
61
+ ...this.defaultPreferences.channels,
62
+ ...preferences.channels,
63
+ },
64
+ };
65
+ if (this.redis) {
66
+ const key = this.buildKey(recipientId);
67
+ await this.redis.set(key, JSON.stringify(fullPrefs));
68
+ }
69
+ else {
70
+ if (!this.memoryStore.has(recipientId) && this.memoryStore.size >= RedisPreferenceStore_1.MAX_MEMORY_PREFERENCES) {
71
+ const firstKey = this.memoryStore.keys().next().value;
72
+ if (firstKey) {
73
+ this.memoryStore.delete(firstKey);
74
+ }
75
+ }
76
+ this.memoryStore.set(recipientId, fullPrefs);
77
+ }
78
+ }
79
+ async updatePreferences(recipientId, updates) {
80
+ const current = await this.getPreferences(recipientId);
81
+ const merged = this.mergePreferences(current ?? this.defaultPreferences, updates);
82
+ await this.setPreferences(recipientId, merged);
83
+ }
84
+ async deletePreferences(recipientId) {
85
+ if (this.redis) {
86
+ const key = this.buildKey(recipientId);
87
+ await this.redis.del(key);
88
+ const counterPattern = `${this.keyPrefix}counter:${recipientId}:*`;
89
+ const keys = await this.redis.keys(counterPattern);
90
+ if (keys.length > 0) {
91
+ await this.redis.del(...keys);
92
+ }
93
+ }
94
+ else {
95
+ this.memoryStore.delete(recipientId);
96
+ }
97
+ }
98
+ async shouldSend(recipientId, payload, channel) {
99
+ const prefs = (await this.getPreferences(recipientId)) ?? this.defaultPreferences;
100
+ if (prefs.globalMute) {
101
+ return { allowed: false, reason: 'global_mute' };
102
+ }
103
+ const channelPref = prefs.channels[channel];
104
+ if (channelPref && !channelPref.enabled) {
105
+ return { allowed: false, reason: 'channel_disabled' };
106
+ }
107
+ if (channelPref?.types && !channelPref.types.includes(payload.type)) {
108
+ return { allowed: false, reason: 'type_not_allowed' };
109
+ }
110
+ const category = payload.metadata?.category;
111
+ if (category && prefs.categories) {
112
+ const categoryPref = prefs.categories[category];
113
+ if (categoryPref && !categoryPref.enabled) {
114
+ return { allowed: false, reason: 'category_disabled' };
115
+ }
116
+ if (categoryPref?.channels && !categoryPref.channels.includes(channel)) {
117
+ return { allowed: false, reason: 'category_channel_not_allowed' };
118
+ }
119
+ }
120
+ const quietHoursResult = this.checkQuietHours(prefs, payload, channel);
121
+ if (!quietHoursResult.allowed) {
122
+ return quietHoursResult;
123
+ }
124
+ const frequencyResult = await this.checkFrequencyLimits(recipientId, prefs, category);
125
+ if (!frequencyResult.allowed) {
126
+ return frequencyResult;
127
+ }
128
+ return { allowed: true };
129
+ }
130
+ async recordSent(recipientId, category) {
131
+ const now = Date.now();
132
+ const windows = ['minute', 'hour', 'day'];
133
+ const divisors = { minute: 60000, hour: 3600000, day: 86400000 };
134
+ for (const window of windows) {
135
+ const bucket = Math.floor(now / divisors[window]);
136
+ const key = category
137
+ ? `${this.keyPrefix}counter:${recipientId}:${category}:${window}:${bucket}`
138
+ : `${this.keyPrefix}counter:${recipientId}:${window}:${bucket}`;
139
+ if (this.redis) {
140
+ await this.redis.incr(key);
141
+ await this.redis.expire(key, this.counterTTL);
142
+ }
143
+ else {
144
+ const entry = this.counterStore.get(key);
145
+ if (entry && entry.resetAt > now) {
146
+ entry.count++;
147
+ }
148
+ else {
149
+ if (!this.counterStore.has(key) && this.counterStore.size >= RedisPreferenceStore_1.MAX_MEMORY_COUNTERS) {
150
+ for (const [k, v] of this.counterStore.entries()) {
151
+ if (v.resetAt < now) {
152
+ this.counterStore.delete(k);
153
+ }
154
+ }
155
+ if (this.counterStore.size >= RedisPreferenceStore_1.MAX_MEMORY_COUNTERS) {
156
+ const firstKey = this.counterStore.keys().next().value;
157
+ if (firstKey) {
158
+ this.counterStore.delete(firstKey);
159
+ }
160
+ }
161
+ }
162
+ this.counterStore.set(key, {
163
+ count: 1,
164
+ resetAt: now + divisors[window],
165
+ });
166
+ }
167
+ }
168
+ }
169
+ }
170
+ getDefaultPreferences() {
171
+ return { ...this.defaultPreferences };
172
+ }
173
+ buildKey(recipientId) {
174
+ return `${this.keyPrefix}${recipientId}`;
175
+ }
176
+ mergePreferences(current, updates) {
177
+ return {
178
+ ...current,
179
+ ...updates,
180
+ channels: {
181
+ ...current.channels,
182
+ ...updates.channels,
183
+ },
184
+ categories: {
185
+ ...current.categories,
186
+ ...updates.categories,
187
+ },
188
+ quietHours: updates.quietHours ? { ...current.quietHours, ...updates.quietHours } : current.quietHours,
189
+ frequency: updates.frequency ? { ...current.frequency, ...updates.frequency } : current.frequency,
190
+ digest: updates.digest ? { ...current.digest, ...updates.digest } : current.digest,
191
+ };
192
+ }
193
+ checkQuietHours(prefs, payload, channel) {
194
+ const channelPref = prefs.channels[channel];
195
+ if (channelPref?.quietHours) {
196
+ if (this.isInQuietHours(channelPref.quietHours.start, channelPref.quietHours.end, prefs.timezone)) {
197
+ if (prefs.allowUrgent && payload.priority === 'urgent') {
198
+ return { allowed: true };
199
+ }
200
+ return { allowed: false, reason: 'channel_quiet_hours' };
201
+ }
202
+ }
203
+ if (prefs.quietHours?.enabled) {
204
+ if (this.isInQuietHours(prefs.quietHours.start, prefs.quietHours.end, prefs.quietHours.timezone ?? prefs.timezone)) {
205
+ const category = payload.metadata?.category;
206
+ if (category && prefs.quietHours.exceptions?.includes(category)) {
207
+ return { allowed: true };
208
+ }
209
+ if (prefs.allowUrgent && payload.priority === 'urgent') {
210
+ return { allowed: true };
211
+ }
212
+ return { allowed: false, reason: 'quiet_hours' };
213
+ }
214
+ }
215
+ return { allowed: true };
216
+ }
217
+ isInQuietHours(start, end, timezone) {
218
+ const now = new Date();
219
+ const currentMinutes = this.getCurrentMinutesInTimezone(now, timezone);
220
+ const startMinutes = this.parseTimeToMinutes(start);
221
+ const endMinutes = this.parseTimeToMinutes(end);
222
+ if (startMinutes > endMinutes) {
223
+ return currentMinutes >= startMinutes || currentMinutes < endMinutes;
224
+ }
225
+ return currentMinutes >= startMinutes && currentMinutes < endMinutes;
226
+ }
227
+ getCurrentMinutesInTimezone(date, timezone) {
228
+ try {
229
+ if (timezone) {
230
+ const formatter = new Intl.DateTimeFormat('en-US', {
231
+ timeZone: timezone,
232
+ hour: 'numeric',
233
+ minute: 'numeric',
234
+ hour12: false,
235
+ });
236
+ const parts = formatter.formatToParts(date);
237
+ const hour = parseInt(parts.find((p) => p.type === 'hour')?.value ?? '0', 10);
238
+ const minute = parseInt(parts.find((p) => p.type === 'minute')?.value ?? '0', 10);
239
+ return hour * 60 + minute;
240
+ }
241
+ }
242
+ catch {
243
+ }
244
+ return date.getUTCHours() * 60 + date.getUTCMinutes();
245
+ }
246
+ parseTimeToMinutes(time) {
247
+ const [hours, minutes] = time.split(':').map(Number);
248
+ return (hours ?? 0) * 60 + (minutes ?? 0);
249
+ }
250
+ async checkFrequencyLimits(recipientId, prefs, category) {
251
+ const limits = category && prefs.categories?.[category]?.frequency ? prefs.categories[category].frequency : prefs.frequency;
252
+ if (!limits) {
253
+ return { allowed: true };
254
+ }
255
+ const now = Date.now();
256
+ const checks = [
257
+ { window: 'minute', limit: limits.maxPerMinute, divisor: 60000 },
258
+ { window: 'hour', limit: limits.maxPerHour, divisor: 3600000 },
259
+ { window: 'day', limit: limits.maxPerDay, divisor: 86400000 },
260
+ ];
261
+ for (const check of checks) {
262
+ if (!check.limit)
263
+ continue;
264
+ const bucket = Math.floor(now / check.divisor);
265
+ const key = category
266
+ ? `${this.keyPrefix}counter:${recipientId}:${category}:${check.window}:${bucket}`
267
+ : `${this.keyPrefix}counter:${recipientId}:${check.window}:${bucket}`;
268
+ let count = 0;
269
+ if (this.redis) {
270
+ count = parseInt((await this.redis.get(key)) || '0', 10);
271
+ }
272
+ else {
273
+ const entry = this.counterStore.get(key);
274
+ if (entry && entry.resetAt > now) {
275
+ count = entry.count;
276
+ }
277
+ }
278
+ if (count >= check.limit) {
279
+ return { allowed: false, reason: `frequency_${check.window}_exceeded` };
280
+ }
281
+ }
282
+ return { allowed: true };
283
+ }
284
+ };
285
+ RedisPreferenceStore = RedisPreferenceStore_1 = __decorate([
286
+ Injectable(),
287
+ __param(0, Optional()),
288
+ __metadata("design:paramtypes", [Function, Object])
289
+ ], RedisPreferenceStore);
290
+ export { RedisPreferenceStore };
291
+ //# sourceMappingURL=redis-preference-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redis-preference-store.js","sourceRoot":"","sources":["../src/redis-preference-store.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAUA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAwE1D,MAAM,mBAAmB,GAAoC;IAC3D,QAAQ,EAAE;QACR,KAAK,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE;QACxB,IAAI,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE;QACvB,GAAG,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE;QACvB,KAAK,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE;QACxB,OAAO,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE;KAC5B;IACD,UAAU,EAAE,KAAK;IACjB,MAAM,EAAE,IAAI;IACZ,QAAQ,EAAE,KAAK;IACf,WAAW,EAAE,IAAI;IACjB,UAAU,EAAE;QACV,OAAO,EAAE,KAAK;QACd,KAAK,EAAE,OAAO;QACd,GAAG,EAAE,OAAO;QACZ,QAAQ,EAAE,KAAK;QACf,UAAU,EAAE,EAAE;KACf;CACF,CAAC;AAOK,IAAM,oBAAoB,GAA1B,MAAM,oBAAoB;;aAUP,2BAAsB,GAAG,KAAK,AAAR,CAAS;aAM/B,wBAAmB,GAAG,KAAK,AAAR,CAAS;IAOpD,YACc,KAA8B,EAC1C,OAAqC;QADR,UAAK,GAAL,KAAK,CAAQ;QAL3B,gBAAW,GAAG,IAAI,GAAG,EAA2C,CAAC;QAEjE,iBAAY,GAAG,IAAI,GAAG,EAA8C,CAAC;QAMpF,IAAI,CAAC,SAAS,GAAG,OAAO,EAAE,SAAS,IAAI,sBAAsB,CAAC;QAC9D,IAAI,CAAC,kBAAkB,GAAG,EAAE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AAI,MAAM,EAAE;gBACjF,CAAC,CAAC,GAAG,IAAI,CAAC,SAAS,WAAW,WAAW,IAAI,KAAK,CAAC,MAAM,IAAI,MAAM,EAAE,CAAC;YAExE,IAAI,KAAK,GAAG,CAAC,CAAC;YACd,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;gBACf,KAAK,GAAG,QAAQ,CAAC,CAAC,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,IAAI,GAAG,EAAE,EAAE,CAAC,CAAC;YAC3D,CAAC;iBAAM,CAAC;gBACN,MAAM,KAAK,GAAG,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;gBACzC,IAAI,KAAK,IAAI,KAAK,CAAC,OAAO,GAAG,GAAG,EAAE,CAAC;oBACjC,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;gBACtB,CAAC;YACH,CAAC;YAED,IAAI,KAAK,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;gBACzB,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,aAAa,KAAK,CAAC,MAAM,WAAW,EAAE,CAAC;YAC1E,CAAC;QACH,CAAC;QAED,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC3B,CAAC;;AAjWU,oBAAoB;IADhC,UAAU,EAAE;IAyBR,WAAA,QAAQ,EAAE,CAAA;;GAxBF,oBAAoB,CAkWhC"}
@@ -0,0 +1,67 @@
1
+ import type { Redis } from 'ioredis';
2
+ import type { IRateLimiter, NotificationType } from './notifications.types.js';
3
+ export interface RateLimitConfig {
4
+ perMinute?: number;
5
+ perHour?: number;
6
+ perDay?: number;
7
+ burstLimit?: number;
8
+ burstWindowMs?: number;
9
+ }
10
+ export interface RateLimitStatus {
11
+ allowed: boolean;
12
+ remaining: {
13
+ burst?: number;
14
+ minute?: number;
15
+ hour?: number;
16
+ day?: number;
17
+ };
18
+ resetAt: {
19
+ burst?: number;
20
+ minute?: number;
21
+ hour?: number;
22
+ day?: number;
23
+ };
24
+ retryAfter?: number;
25
+ }
26
+ export interface RedisRateLimiterOptions {
27
+ keyPrefix?: string;
28
+ defaultLimits?: RateLimitConfig;
29
+ channelLimits?: Record<string, RateLimitConfig>;
30
+ enableBurstDetection?: boolean;
31
+ }
32
+ export declare class RedisRateLimiter implements IRateLimiter {
33
+ private readonly redis?;
34
+ private readonly keyPrefix;
35
+ private readonly defaultLimits;
36
+ private readonly channelLimits;
37
+ private readonly enableBurstDetection;
38
+ private static readonly MAX_MEMORY_STORE_SIZE;
39
+ private readonly memoryStore;
40
+ constructor(redis?: Redis | undefined, options?: RedisRateLimiterOptions);
41
+ checkLimit(recipientId: string, channel: string, type?: NotificationType): Promise<{
42
+ allowed: boolean;
43
+ retryAfter?: number;
44
+ }>;
45
+ recordSent(recipientId: string, channel: string, type?: NotificationType): Promise<void>;
46
+ reset(recipientId: string, channel?: string): Promise<void>;
47
+ checkBatch(recipients: Array<{
48
+ id: string;
49
+ channel: string;
50
+ type?: NotificationType;
51
+ }>): Promise<Map<string, {
52
+ allowed: boolean;
53
+ retryAfter?: number;
54
+ }>>;
55
+ getStatus(recipientId: string, channel: string, type?: NotificationType): Promise<RateLimitStatus>;
56
+ setCustomLimits(recipientId: string, limits: RateLimitConfig): Promise<void>;
57
+ getCustomLimits(recipientId: string): Promise<RateLimitConfig | null>;
58
+ removeCustomLimits(recipientId: string): Promise<void>;
59
+ private getLimitsFor;
60
+ private buildKey;
61
+ private recordToRedis;
62
+ private recordToMemory;
63
+ private cleanupMemoryStore;
64
+ private resetChannel;
65
+ private resetAll;
66
+ }
67
+ //# sourceMappingURL=redis-rate-limiter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redis-rate-limiter.d.ts","sourceRoot":"","sources":["../src/redis-rate-limiter.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,KAAK,EAAE,YAAY,E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C,cAAc;IAqBtB,OAAO,CAAC,kBAAkB;YAmBZ,YAAY;YAiBZ,QAAQ;CAiBvB"}
@@ -0,0 +1,270 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ var RedisRateLimiter_1;
14
+ import { Injectable, Optional } from '@omnitron-dev/titan/decorators';
15
+ import { safeJsonParse } from '@omnitron-dev/titan/utils';
16
+ const DEFAULT_LIMITS = {
17
+ perMinute: 60,
18
+ perHour: 500,
19
+ perDay: 5000,
20
+ burstLimit: 10,
21
+ burstWindowMs: 1000,
22
+ };
23
+ let RedisRateLimiter = class RedisRateLimiter {
24
+ static { RedisRateLimiter_1 = this; }
25
+ static { this.MAX_MEMORY_STORE_SIZE = 10000; }
26
+ constructor(redis, options) {
27
+ this.redis = redis;
28
+ this.memoryStore = new Map();
29
+ this.keyPrefix = options?.keyPrefix ?? 'notifications:ratelimit:';
30
+ this.defaultLimits = { ...DEFAULT_LIMITS, ...options?.defaultLimits };
31
+ this.channelLimits = options?.channelLimits ?? {};
32
+ this.enableBurstDetection = options?.enableBurstDetection ?? true;
33
+ }
34
+ async checkLimit(recipientId, channel, type) {
35
+ const status = await this.getStatus(recipientId, channel, type);
36
+ return {
37
+ allowed: status.allowed,
38
+ retryAfter: status.retryAfter,
39
+ };
40
+ }
41
+ async recordSent(recipientId, channel, type) {
42
+ const key = this.buildKey(recipientId, channel);
43
+ const now = Date.now();
44
+ if (this.redis) {
45
+ await this.recordToRedis(key, now);
46
+ }
47
+ else {
48
+ this.recordToMemory(key, now);
49
+ }
50
+ }
51
+ async reset(recipientId, channel) {
52
+ if (channel) {
53
+ await this.resetChannel(recipientId, channel);
54
+ }
55
+ else {
56
+ await this.resetAll(recipientId);
57
+ }
58
+ }
59
+ async checkBatch(recipients) {
60
+ const results = new Map();
61
+ const checks = recipients.map(async (r) => {
62
+ const result = await this.checkLimit(r.id, r.channel, r.type);
63
+ results.set(`${r.id}:${r.channel}`, result);
64
+ });
65
+ await Promise.all(checks);
66
+ return results;
67
+ }
68
+ async getStatus(recipientId, channel, type) {
69
+ const limits = await this.getLimitsFor(recipientId, channel);
70
+ const key = this.buildKey(recipientId, channel);
71
+ const now = Date.now();
72
+ let allowed = true;
73
+ let retryAfter;
74
+ const remaining = {};
75
+ const resetAt = {};
76
+ if (this.redis) {
77
+ if (this.enableBurstDetection && limits.burstLimit) {
78
+ const burstKey = `${key}:burst`;
79
+ const windowMs = limits.burstWindowMs ?? 1000;
80
+ const windowStart = now - windowMs;
81
+ await this.redis.zremrangebyscore(burstKey, '-inf', windowStart);
82
+ const burstCount = await this.redis.zcard(burstKey);
83
+ remaining.burst = Math.max(0, limits.burstLimit - burstCount);
84
+ resetAt.burst = now + windowMs;
85
+ if (burstCount >= limits.burstLimit) {
86
+ allowed = false;
87
+ retryAfter = Math.min(retryAfter ?? Infinity, windowMs);
88
+ }
89
+ }
90
+ const minuteKey = limits.perMinute ? `${key}:minute:${Math.floor(now / 60000)}` : null;
91
+ const hourKey = limits.perHour ? `${key}:hour:${Math.floor(now / 3600000)}` : null;
92
+ const dayKey = limits.perDay ? `${key}:day:${Math.floor(now / 86400000)}` : null;
93
+ const keysToFetch = [minuteKey, hourKey, dayKey].filter((k) => k !== null);
94
+ const counts = keysToFetch.length > 0 ? await this.redis.mget(...keysToFetch) : [];
95
+ let countIndex = 0;
96
+ const minuteCount = minuteKey ? parseInt(counts[countIndex++] || '0', 10) : 0;
97
+ const hourCount = hourKey ? parseInt(counts[countIndex++] || '0', 10) : 0;
98
+ const dayCount = dayKey ? parseInt(counts[countIndex] || '0', 10) : 0;
99
+ if (limits.perMinute) {
100
+ remaining.minute = Math.max(0, limits.perMinute - minuteCount);
101
+ resetAt.minute = (Math.floor(now / 60000) + 1) * 60000;
102
+ if (minuteCount >= limits.perMinute) {
103
+ allowed = false;
104
+ retryAfter = Math.min(retryAfter ?? Infinity, resetAt.minute - now);
105
+ }
106
+ }
107
+ if (limits.perHour) {
108
+ remaining.hour = Math.max(0, limits.perHour - hourCount);
109
+ resetAt.hour = (Math.floor(now / 3600000) + 1) * 3600000;
110
+ if (hourCount >= limits.perHour) {
111
+ allowed = false;
112
+ retryAfter = Math.min(retryAfter ?? Infinity, resetAt.hour - now);
113
+ }
114
+ }
115
+ if (limits.perDay) {
116
+ remaining.day = Math.max(0, limits.perDay - dayCount);
117
+ resetAt.day = (Math.floor(now / 86400000) + 1) * 86400000;
118
+ if (dayCount >= limits.perDay) {
119
+ allowed = false;
120
+ retryAfter = Math.min(retryAfter ?? Infinity, resetAt.day - now);
121
+ }
122
+ }
123
+ }
124
+ else {
125
+ const memKey = `${key}:minute`;
126
+ const entry = this.memoryStore.get(memKey);
127
+ if (entry && entry.resetAt > now) {
128
+ remaining.minute = Math.max(0, (limits.perMinute ?? 60) - entry.count);
129
+ resetAt.minute = entry.resetAt;
130
+ if (entry.count >= (limits.perMinute ?? 60)) {
131
+ allowed = false;
132
+ retryAfter = entry.resetAt - now;
133
+ }
134
+ }
135
+ else {
136
+ remaining.minute = limits.perMinute ?? 60;
137
+ resetAt.minute = now + 60000;
138
+ }
139
+ }
140
+ return {
141
+ allowed,
142
+ remaining,
143
+ resetAt,
144
+ retryAfter: retryAfter === Infinity ? undefined : retryAfter,
145
+ };
146
+ }
147
+ async setCustomLimits(recipientId, limits) {
148
+ const key = `${this.keyPrefix}config:${recipientId}`;
149
+ if (this.redis) {
150
+ await this.redis.set(key, JSON.stringify(limits), 'EX', 86400 * 30);
151
+ }
152
+ }
153
+ async getCustomLimits(recipientId) {
154
+ if (!this.redis)
155
+ return null;
156
+ const key = `${this.keyPrefix}config:${recipientId}`;
157
+ const data = await this.redis.get(key);
158
+ return data ? safeJsonParse(data) : null;
159
+ }
160
+ async removeCustomLimits(recipientId) {
161
+ if (this.redis) {
162
+ const key = `${this.keyPrefix}config:${recipientId}`;
163
+ await this.redis.del(key);
164
+ }
165
+ }
166
+ async getLimitsFor(recipientId, channel) {
167
+ const customLimits = await this.getCustomLimits(recipientId);
168
+ if (customLimits) {
169
+ return { ...this.defaultLimits, ...customLimits };
170
+ }
171
+ if (this.channelLimits[channel]) {
172
+ return { ...this.defaultLimits, ...this.channelLimits[channel] };
173
+ }
174
+ return this.defaultLimits;
175
+ }
176
+ buildKey(recipientId, channel) {
177
+ return `${this.keyPrefix}${recipientId}:${channel}`;
178
+ }
179
+ async recordToRedis(key, now) {
180
+ if (!this.redis) {
181
+ throw new Error('recordToRedis called without Redis client');
182
+ }
183
+ const pipeline = this.redis.pipeline();
184
+ if (this.enableBurstDetection) {
185
+ const burstKey = `${key}:burst`;
186
+ pipeline.zadd(burstKey, now, `${now}-${Math.random()}`);
187
+ pipeline.expire(burstKey, 2);
188
+ }
189
+ const minuteKey = `${key}:minute:${Math.floor(now / 60000)}`;
190
+ pipeline.incr(minuteKey);
191
+ pipeline.expire(minuteKey, 120);
192
+ const hourKey = `${key}:hour:${Math.floor(now / 3600000)}`;
193
+ pipeline.incr(hourKey);
194
+ pipeline.expire(hourKey, 7200);
195
+ const dayKey = `${key}:day:${Math.floor(now / 86400000)}`;
196
+ pipeline.incr(dayKey);
197
+ pipeline.expire(dayKey, 172800);
198
+ await pipeline.exec();
199
+ }
200
+ recordToMemory(key, now) {
201
+ const memKey = `${key}:minute`;
202
+ const entry = this.memoryStore.get(memKey);
203
+ const resetAt = (Math.floor(now / 60000) + 1) * 60000;
204
+ if (entry && entry.resetAt > now) {
205
+ entry.count++;
206
+ }
207
+ else {
208
+ this.memoryStore.set(memKey, { count: 1, resetAt });
209
+ }
210
+ if (this.memoryStore.size > RedisRateLimiter_1.MAX_MEMORY_STORE_SIZE) {
211
+ this.cleanupMemoryStore(now);
212
+ }
213
+ }
214
+ cleanupMemoryStore(now) {
215
+ for (const [key, entry] of this.memoryStore.entries()) {
216
+ if (entry.resetAt < now) {
217
+ this.memoryStore.delete(key);
218
+ }
219
+ }
220
+ while (this.memoryStore.size > RedisRateLimiter_1.MAX_MEMORY_STORE_SIZE) {
221
+ const firstKey = this.memoryStore.keys().next().value;
222
+ if (firstKey) {
223
+ this.memoryStore.delete(firstKey);
224
+ }
225
+ else {
226
+ break;
227
+ }
228
+ }
229
+ }
230
+ async resetChannel(recipientId, channel) {
231
+ const key = this.buildKey(recipientId, channel);
232
+ if (this.redis) {
233
+ const keys = await this.redis.keys(`${key}:*`);
234
+ if (keys.length > 0) {
235
+ await this.redis.del(...keys);
236
+ }
237
+ }
238
+ else {
239
+ for (const k of this.memoryStore.keys()) {
240
+ if (k.startsWith(key)) {
241
+ this.memoryStore.delete(k);
242
+ }
243
+ }
244
+ }
245
+ }
246
+ async resetAll(recipientId) {
247
+ const pattern = `${this.keyPrefix}${recipientId}:*`;
248
+ if (this.redis) {
249
+ const keys = await this.redis.keys(pattern);
250
+ if (keys.length > 0) {
251
+ await this.redis.del(...keys);
252
+ }
253
+ }
254
+ else {
255
+ const prefix = `${this.keyPrefix}${recipientId}:`;
256
+ for (const k of this.memoryStore.keys()) {
257
+ if (k.startsWith(prefix)) {
258
+ this.memoryStore.delete(k);
259
+ }
260
+ }
261
+ }
262
+ }
263
+ };
264
+ RedisRateLimiter = RedisRateLimiter_1 = __decorate([
265
+ Injectable(),
266
+ __param(0, Optional()),
267
+ __metadata("design:paramtypes", [Function, Object])
268
+ ], RedisRateLimiter);
269
+ export { RedisRateLimiter };
270
+ //# sourceMappingURL=redis-rate-limiter.js.map