@bernierllc/message-queue 0.2.0

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.
@@ -0,0 +1,201 @@
1
+ "use strict";
2
+ /*
3
+ Copyright (c) 2025 Bernier LLC
4
+
5
+ This file is licensed to the client under a limited-use license.
6
+ The client may use and modify this code *only within the scope of the project it was delivered for*.
7
+ Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.generateId = generateId;
11
+ exports.validateMessage = validateMessage;
12
+ exports.validateConfig = validateConfig;
13
+ exports.validateFilter = validateFilter;
14
+ exports.validateMessageId = validateMessageId;
15
+ exports.validateQueueName = validateQueueName;
16
+ const types_1 = require("../types");
17
+ /**
18
+ * Generate a unique ID for messages
19
+ */
20
+ function generateId() {
21
+ return `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
22
+ }
23
+ /**
24
+ * Validate a message object
25
+ */
26
+ function validateMessage(message) {
27
+ if (!message.id || typeof message.id !== 'string') {
28
+ return {
29
+ isValid: false,
30
+ error: 'Message ID is required and must be a string'
31
+ };
32
+ }
33
+ if (message.content === undefined || message.content === null) {
34
+ return {
35
+ isValid: false,
36
+ error: 'Message content is required'
37
+ };
38
+ }
39
+ if (!Object.values(types_1.MessagePriority).includes(message.priority)) {
40
+ return {
41
+ isValid: false,
42
+ error: 'Invalid message priority'
43
+ };
44
+ }
45
+ if (!(message.timestamp instanceof Date) || isNaN(message.timestamp.getTime())) {
46
+ return {
47
+ isValid: false,
48
+ error: 'Message timestamp must be a valid Date'
49
+ };
50
+ }
51
+ if (message.expiresAt && (!(message.expiresAt instanceof Date) || isNaN(message.expiresAt.getTime()))) {
52
+ return {
53
+ isValid: false,
54
+ error: 'Message expiration must be a valid Date'
55
+ };
56
+ }
57
+ if (message.retryCount !== undefined && (typeof message.retryCount !== 'number' || message.retryCount < 0)) {
58
+ return {
59
+ isValid: false,
60
+ error: 'Retry count must be a non-negative number'
61
+ };
62
+ }
63
+ if (message.maxRetries !== undefined && (typeof message.maxRetries !== 'number' || message.maxRetries < 0)) {
64
+ return {
65
+ isValid: false,
66
+ error: 'Max retries must be a non-negative number'
67
+ };
68
+ }
69
+ if (message.metadata && typeof message.metadata !== 'object') {
70
+ return {
71
+ isValid: false,
72
+ error: 'Message metadata must be an object'
73
+ };
74
+ }
75
+ return { isValid: true };
76
+ }
77
+ /**
78
+ * Validate queue configuration
79
+ */
80
+ function validateConfig(config) {
81
+ if (!config.name || typeof config.name !== 'string') {
82
+ throw new Error('Queue name is required and must be a string');
83
+ }
84
+ if (config.maxSize !== undefined && (typeof config.maxSize !== 'number' || config.maxSize <= 0)) {
85
+ throw new Error('Max size must be a positive number');
86
+ }
87
+ if (config.defaultPriority !== undefined && !Object.values(types_1.MessagePriority).includes(config.defaultPriority)) {
88
+ throw new Error('Invalid default priority');
89
+ }
90
+ if (config.defaultTtl !== undefined && (typeof config.defaultTtl !== 'number' || config.defaultTtl <= 0)) {
91
+ throw new Error('Default TTL must be a positive number');
92
+ }
93
+ if (config.maxRetries !== undefined && (typeof config.maxRetries !== 'number' || config.maxRetries < 0)) {
94
+ throw new Error('Max retries must be a non-negative number');
95
+ }
96
+ if (config.retryDelay !== undefined && (typeof config.retryDelay !== 'number' || config.retryDelay < 0)) {
97
+ throw new Error('Retry delay must be a non-negative number');
98
+ }
99
+ if (config.retryMaxDelay !== undefined && (typeof config.retryMaxDelay !== 'number' || config.retryMaxDelay < 0)) {
100
+ throw new Error('Retry max delay must be a non-negative number');
101
+ }
102
+ if (config.retryMaxDelay !== undefined && config.retryDelay !== undefined && config.retryMaxDelay < config.retryDelay) {
103
+ throw new Error('Retry max delay must be greater than or equal to retry delay');
104
+ }
105
+ return {
106
+ name: config.name,
107
+ maxSize: config.maxSize,
108
+ defaultPriority: config.defaultPriority || types_1.MessagePriority.NORMAL,
109
+ defaultTtl: config.defaultTtl,
110
+ enableRetries: config.enableRetries || false,
111
+ maxRetries: config.maxRetries || 0,
112
+ retryDelay: config.retryDelay || 1000,
113
+ retryMaxDelay: config.retryMaxDelay || (config.retryDelay || 1000) * 10,
114
+ retryJitter: config.retryJitter !== false // Default to true
115
+ };
116
+ }
117
+ /**
118
+ * Validate message filter
119
+ */
120
+ function validateFilter(filter) {
121
+ if (filter.priority !== undefined && !Object.values(types_1.MessagePriority).includes(filter.priority)) {
122
+ return {
123
+ isValid: false,
124
+ error: 'Invalid priority filter'
125
+ };
126
+ }
127
+ if (filter.fromTimestamp && (!(filter.fromTimestamp instanceof Date) || isNaN(filter.fromTimestamp.getTime()))) {
128
+ return {
129
+ isValid: false,
130
+ error: 'From timestamp must be a valid Date'
131
+ };
132
+ }
133
+ if (filter.toTimestamp && (!(filter.toTimestamp instanceof Date) || isNaN(filter.toTimestamp.getTime()))) {
134
+ return {
135
+ isValid: false,
136
+ error: 'To timestamp must be a valid Date'
137
+ };
138
+ }
139
+ if (filter.limit !== undefined && (typeof filter.limit !== 'number' || filter.limit <= 0)) {
140
+ return {
141
+ isValid: false,
142
+ error: 'Limit must be a positive number'
143
+ };
144
+ }
145
+ if (filter.offset !== undefined && (typeof filter.offset !== 'number' || filter.offset < 0)) {
146
+ return {
147
+ isValid: false,
148
+ error: 'Offset must be a non-negative number'
149
+ };
150
+ }
151
+ if (filter.metadata && typeof filter.metadata !== 'object') {
152
+ return {
153
+ isValid: false,
154
+ error: 'Metadata filter must be an object'
155
+ };
156
+ }
157
+ return { isValid: true };
158
+ }
159
+ /**
160
+ * Validate message ID format
161
+ */
162
+ function validateMessageId(messageId) {
163
+ if (!messageId || typeof messageId !== 'string') {
164
+ return {
165
+ isValid: false,
166
+ error: 'Message ID is required and must be a string'
167
+ };
168
+ }
169
+ if (messageId.length < 10) {
170
+ return {
171
+ isValid: false,
172
+ error: 'Message ID must be at least 10 characters long'
173
+ };
174
+ }
175
+ return { isValid: true };
176
+ }
177
+ /**
178
+ * Validate queue name
179
+ */
180
+ function validateQueueName(name) {
181
+ if (!name || typeof name !== 'string') {
182
+ return {
183
+ isValid: false,
184
+ error: 'Queue name is required and must be a string'
185
+ };
186
+ }
187
+ if (name.length < 1 || name.length > 100) {
188
+ return {
189
+ isValid: false,
190
+ error: 'Queue name must be between 1 and 100 characters'
191
+ };
192
+ }
193
+ if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
194
+ return {
195
+ isValid: false,
196
+ error: 'Queue name can only contain letters, numbers, underscores, and hyphens'
197
+ };
198
+ }
199
+ return { isValid: true };
200
+ }
201
+ //# sourceMappingURL=validation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validation.js","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":";AAAA;;;;;;EAME;;AAYF,gCAEC;AAKD,0CA0DC;AAKD,wCA4CC;AAKD,wCA4CC;AAKD,8CAgBC;AAKD,8CAuBC;AA9ND,oCAAiE;AAOjE;;GAEG;AACH,SAAgB,UAAU;IACxB,OAAO,OAAO,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC;AACxE,CAAC;AAED;;GAEG;AACH,SAAgB,eAAe,CAAC,OAAgB;IAC9C,IAAI,CAAC,OAAO,CAAC,EAAE,IAAI,OAAO,OAAO,CAAC,EAAE,KAAK,QAAQ,EAAE,CAAC;QAClD,OAAO;YACL,OAAO,EAAE,KAAK;YACd,KAAK,EAAE,6CAA6C;SACrD,CAAC;IACJ,CAAC;IAED,IAAI,OAAO,CAAC,OAAO,KAAK,SAAS,IAAI,OAAO,CAAC,OAAO,KAAK,IAAI,EAAE,CAAC;QAC9D,OAAO;YACL,OAAO,EAAE,KAAK;YACd,KAAK,EAAE,6BAA6B;SACrC,CAAC;IACJ,CAAC;IAED,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,uBAAe,CAAC,CAAC,QAAQ,CAA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EG;AACH,SAAgB,iBAAiB,CAAC,SAAiB;IACjD,IAAI,CAAC,SAAS,IAAI,OAAO,SAAS,KAAK,QAAQ,EAAE,CAAC;QAChD,OAAO;YACL,OAAO,EAAE,KAAK;YACd,KAAK,EAAE,6CAA6C;SACrD,CAAC;IACJ,CAAC;IAED,IAAI,SAAS,CAAC,MAAM,GAAG,EAAE,EAAE,CAAC;QAC1B,OAAO;YACL,OAAO,EAAE,KAAK;YACd,KAAK,EAAE,gDAAgD;SACxD,CAAC;IACJ,CAAC;IAED,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;AAC3B,CAAC;AAED;;GAEG;AACH,SAAgB,iBAAiB,CAAC,IAAY;IAC5C,IAAI,CAAC,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;QACtC,OAAO;YACL,OAAO,EAAE,KAAK;YACd,KAAK,EAAE,6CAA6C;SACrD,CAAC;IACJ,CAAC;IAED,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,MAAM,GAAG,GAAG,EAAE,CAAC;QACzC,OAAO;YACL,OAAO,EAAE,KAAK;YACd,KAAK,EAAE,iDAAiD;SACzD,CAAC;IACJ,CAAC;IAED,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QACnC,OAAO;YACL,OAAO,EAAE,KAAK;YACd,KAAK,EAAE,wEAAwE;SAChF,CAAC;IACJ,CAAC;IAED,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;AAC3B,CAAC"}
@@ -0,0 +1,197 @@
1
+ /*
2
+ Copyright (c) 2025 Bernier LLC
3
+
4
+ This file is licensed to the client under a limited-use license.
5
+ The client may use and modify this code *only within the scope of the project it was delivered for*.
6
+ Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
7
+ */
8
+
9
+ import { MessageQueue, MessagePriority, QueueEvent } from '../src/index';
10
+
11
+ // Example 1: Basic Queue Usage
12
+ async function basicQueueExample() {
13
+ console.log('=== Basic Queue Example ===');
14
+
15
+ // Create a simple queue
16
+ const queue = new MessageQueue({
17
+ name: 'basic-queue',
18
+ maxSize: 100,
19
+ enableRetries: true,
20
+ maxRetries: 3
21
+ });
22
+
23
+ // Add messages with different priorities
24
+ queue.addMessage('Low priority task', MessagePriority.LOW);
25
+ queue.addMessage('High priority task', MessagePriority.HIGH);
26
+ queue.addMessage('Normal priority task', MessagePriority.NORMAL);
27
+
28
+ console.log(`Queue size: ${queue.size}`);
29
+ console.log(`Is empty: ${queue.isEmpty}`);
30
+ console.log(`Is full: ${queue.isFull}`);
31
+
32
+ // Process messages
33
+ const processor = async (message: any) => {
34
+ console.log(`Processing: ${message.content} (Priority: ${message.priority})`);
35
+ // Simulate some work
36
+ await new Promise(resolve => setTimeout(resolve, 100));
37
+ return true; // Success
38
+ };
39
+
40
+ // Process all messages
41
+ while (!queue.isEmpty) {
42
+ await queue.processMessage(processor);
43
+ }
44
+
45
+ console.log('All messages processed!');
46
+ console.log(`Final stats:`, queue.getStats());
47
+ }
48
+
49
+ // Example 2: Queue with Events
50
+ async function eventDrivenQueueExample() {
51
+ console.log('\n=== Event-Driven Queue Example ===');
52
+
53
+ const queue = new MessageQueue({
54
+ name: 'event-queue',
55
+ maxSize: 50
56
+ });
57
+
58
+ // Set up event handlers
59
+ queue.onEvent((event: QueueEvent) => {
60
+ console.log(`Event: ${event.type} - ${event.messageId || 'N/A'}`);
61
+ });
62
+
63
+ // Add messages
64
+ queue.addMessage('Event message 1');
65
+ queue.addMessage('Event message 2');
66
+
67
+ // Process messages
68
+ const processor = async (message: any) => {
69
+ console.log(`Processing: ${message.content}`);
70
+ return true;
71
+ };
72
+
73
+ await queue.processMessage(processor);
74
+ await queue.processMessage(processor);
75
+ }
76
+
77
+ // Example 3: Queue with Filtering
78
+ async function filteringExample() {
79
+ console.log('\n=== Filtering Example ===');
80
+
81
+ const queue = new MessageQueue({
82
+ name: 'filter-queue'
83
+ });
84
+
85
+ // Add messages with metadata
86
+ queue.addMessage('User notification', MessagePriority.HIGH, { type: 'notification', userId: '123' });
87
+ queue.addMessage('System log', MessagePriority.LOW, { type: 'log', system: 'auth' });
88
+ queue.addMessage('User notification', MessagePriority.NORMAL, { type: 'notification', userId: '456' });
89
+
90
+ // Filter messages by metadata
91
+ const notifications = queue.getMessages({ metadata: { type: 'notification' } });
92
+ console.log(`Found ${notifications.length} notification messages`);
93
+
94
+ // Filter by priority
95
+ const highPriority = queue.getMessages({ priority: MessagePriority.HIGH });
96
+ console.log(`Found ${highPriority.length} high priority messages`);
97
+
98
+ // Filter with pagination
99
+ const paginated = queue.getMessages({ limit: 2, offset: 0 });
100
+ console.log(`First 2 messages:`, paginated.map(m => m.content));
101
+ }
102
+
103
+ // Example 4: Queue with Retries
104
+ async function retryExample() {
105
+ console.log('\n=== Retry Example ===');
106
+
107
+ const queue = new MessageQueue({
108
+ name: 'retry-queue',
109
+ enableRetries: true,
110
+ maxRetries: 2,
111
+ retryDelay: 500
112
+ });
113
+
114
+ queue.addMessage('Failing message');
115
+
116
+ let attemptCount = 0;
117
+ const failingProcessor = async (message: any) => {
118
+ attemptCount++;
119
+ console.log(`Attempt ${attemptCount} to process: ${message.content}`);
120
+
121
+ if (attemptCount < 3) {
122
+ return false; // Fail first two attempts
123
+ }
124
+ return true; // Succeed on third attempt
125
+ };
126
+
127
+ await queue.processMessage(failingProcessor);
128
+
129
+ // Wait for retries to complete
130
+ await new Promise(resolve => setTimeout(resolve, 1500));
131
+
132
+ console.log(`Final attempt count: ${attemptCount}`);
133
+ console.log(`Queue stats:`, queue.getStats());
134
+ }
135
+
136
+ // Example 5: Queue Management
137
+ async function queueManagementExample() {
138
+ console.log('\n=== Queue Management Example ===');
139
+
140
+ const queue = new MessageQueue({
141
+ name: 'management-queue',
142
+ maxSize: 5
143
+ });
144
+
145
+ // Add some messages
146
+ for (let i = 1; i <= 3; i++) {
147
+ queue.addMessage(`Message ${i}`);
148
+ }
149
+
150
+ console.log('Queue info:', queue.getInfo());
151
+
152
+ // Pause the queue
153
+ queue.pause();
154
+ console.log('Queue paused:', queue.getInfo().isActive);
155
+
156
+ // Try to add message while paused
157
+ const result = queue.addMessage('Should fail');
158
+ console.log('Add result:', result.success, result.error);
159
+
160
+ // Resume the queue
161
+ queue.resume();
162
+ console.log('Queue resumed:', queue.getInfo().isActive);
163
+
164
+ // Clear the queue
165
+ queue.clear();
166
+ console.log('Queue cleared, size:', queue.size);
167
+ }
168
+
169
+ // Run all examples
170
+ async function runExamples() {
171
+ try {
172
+ await basicQueueExample();
173
+ await eventDrivenQueueExample();
174
+ await filteringExample();
175
+ await retryExample();
176
+ await queueManagementExample();
177
+
178
+ console.log('\n=== All Examples Completed ===');
179
+ } catch (error) {
180
+ console.error('Example error:', error);
181
+ }
182
+ }
183
+
184
+ // Export for use in other files
185
+ export {
186
+ basicQueueExample,
187
+ eventDrivenQueueExample,
188
+ filteringExample,
189
+ retryExample,
190
+ queueManagementExample,
191
+ runExamples
192
+ };
193
+
194
+ // Run if this file is executed directly
195
+ if (require.main === module) {
196
+ runExamples();
197
+ }
@@ -0,0 +1,18 @@
1
+ module.exports = {
2
+ preset: 'ts-jest',
3
+ testEnvironment: 'node',
4
+ roots: ['<rootDir>/src', '<rootDir>/tests'],
5
+ testMatch: ['**/__tests__/**/*.ts', '**/?(*.)+(spec|test).ts'],
6
+ transform: {
7
+ '^.+\\.ts$': 'ts-jest',
8
+ },
9
+ collectCoverageFrom: [
10
+ 'src/**/*.ts',
11
+ '!src/**/*.d.ts',
12
+ '!src/index.ts',
13
+ ],
14
+ coverageDirectory: 'coverage',
15
+ coverageReporters: ['text', 'lcov', 'html'],
16
+ moduleFileExtensions: ['ts', 'js', 'json'],
17
+ setupFilesAfterEnv: ['<rootDir>/tests/setup.ts'],
18
+ };
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@bernierllc/message-queue",
3
+ "version": "0.2.0",
4
+ "private": false,
5
+ "description": "Atomic message queuing utilities for message ordering and persistence",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "scripts": {
9
+ "build": "tsc",
10
+ "test": "jest",
11
+ "test:watch": "jest --watch",
12
+ "test:coverage": "jest --coverage",
13
+ "lint": "eslint src --ext .ts",
14
+ "lint:fix": "eslint src --ext .ts --fix",
15
+ "clean": "rm -rf dist",
16
+ "prebuild": "npm run clean"
17
+ },
18
+ "keywords": [
19
+ "message-queue",
20
+ "queue",
21
+ "messaging",
22
+ "ordering",
23
+ "persistence",
24
+ "bernierllc"
25
+ ],
26
+ "author": "Bernier LLC",
27
+ "license": "ISC",
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "https://github.com/bernier-llc/tools"
31
+ },
32
+ "bugs": {
33
+ "url": "https://github.com/bernier-llc/tools/issues"
34
+ },
35
+ "homepage": "https://github.com/bernier-llc/tools#readme",
36
+ "dependencies": {
37
+ "@bernierllc/retry-policy": "^0.1.0"
38
+ },
39
+ "devDependencies": {
40
+ "@types/jest": "^29.5.0",
41
+ "@types/node": "^20.0.0",
42
+ "@typescript-eslint/eslint-plugin": "^6.0.0",
43
+ "@typescript-eslint/parser": "^6.0.0",
44
+ "eslint": "^8.0.0",
45
+ "jest": "^29.5.0",
46
+ "ts-jest": "^29.1.0",
47
+ "typescript": "^5.0.0"
48
+ },
49
+ "engines": {
50
+ "node": ">=18.0.0"
51
+ },
52
+ "packageType": "core"
53
+ }