unnbound-events 1.0.19 → 1.0.21

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.
@@ -1,312 +1,255 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
1
+ 'use strict';
2
+ Object.defineProperty(exports, '__esModule', { value: true });
3
3
  exports.createEventsClient = createEventsClient;
4
- const unnbound_logger_sdk_1 = require("unnbound-logger-sdk");
4
+ const unnbound_logger_sdk_1 = require('unnbound-logger-sdk');
5
5
  const http = (() => {
6
- try {
7
- return (require && require('http'));
8
- }
9
- catch {
10
- return null;
11
- }
6
+ try {
7
+ return require && require('http');
8
+ } catch {
9
+ return null;
10
+ }
12
11
  })();
13
12
  function matchPath(matcher, path) {
14
- if (typeof matcher === 'string') {
15
- return matcher === path;
16
- }
17
- if (matcher instanceof RegExp) {
18
- return matcher.test(path);
19
- }
20
- return matcher(path);
13
+ if (typeof matcher === 'string') {
14
+ return matcher === path;
15
+ }
16
+ if (matcher instanceof RegExp) {
17
+ return matcher.test(path);
18
+ }
19
+ return matcher(path);
21
20
  }
22
21
  function createEventsClient() {
23
- const routes = [];
24
- return {
25
- on(method, matcher, handler) {
26
- routes.push({ method, matcher, handler });
27
- },
28
- get(matcher, handler) {
29
- routes.push({ method: 'GET', matcher, handler });
30
- },
31
- post(matcher, handler) {
32
- routes.push({ method: 'POST', matcher, handler });
33
- },
34
- put(matcher, handler) {
35
- routes.push({ method: 'PUT', matcher, handler });
36
- },
37
- patch(matcher, handler) {
38
- routes.push({ method: 'PATCH', matcher, handler });
39
- },
40
- delete(matcher, handler) {
41
- routes.push({ method: 'DELETE', matcher, handler });
42
- },
43
- options(matcher, handler) {
44
- routes.push({ method: 'OPTIONS', matcher, handler });
45
- },
46
- head(matcher, handler) {
47
- routes.push({ method: 'HEAD', matcher, handler });
48
- },
49
- async handle(request) {
50
- const route = routes.find((r) => r.method === request.method && matchPath(r.matcher, request.path));
51
- if (!route) {
52
- unnbound_logger_sdk_1.logger.warn({ path: request.path, method: request.method }, 'No route match');
53
- return { status: 404, body: { message: 'Not Found' } };
22
+ const routes = [];
23
+ return {
24
+ on(method, matcher, handler) {
25
+ routes.push({ method, matcher, handler });
26
+ },
27
+ get(matcher, handler) {
28
+ routes.push({ method: 'GET', matcher, handler });
29
+ },
30
+ post(matcher, handler) {
31
+ routes.push({ method: 'POST', matcher, handler });
32
+ },
33
+ put(matcher, handler) {
34
+ routes.push({ method: 'PUT', matcher, handler });
35
+ },
36
+ patch(matcher, handler) {
37
+ routes.push({ method: 'PATCH', matcher, handler });
38
+ },
39
+ delete(matcher, handler) {
40
+ routes.push({ method: 'DELETE', matcher, handler });
41
+ },
42
+ options(matcher, handler) {
43
+ routes.push({ method: 'OPTIONS', matcher, handler });
44
+ },
45
+ head(matcher, handler) {
46
+ routes.push({ method: 'HEAD', matcher, handler });
47
+ },
48
+ async handle(request) {
49
+ const route = routes.find(
50
+ (r) => r.method === request.method && matchPath(r.matcher, request.path)
51
+ );
52
+ if (!route) {
53
+ unnbound_logger_sdk_1.logger.warn(
54
+ { path: request.path, method: request.method },
55
+ 'No route match'
56
+ );
57
+ return { status: 404, body: { message: 'Not Found' } };
58
+ }
59
+ try {
60
+ const response = await route.handler(request);
61
+ return response;
62
+ } catch (error) {
63
+ const err = error instanceof Error ? error : new Error(String(error));
64
+ unnbound_logger_sdk_1.logger.error({ err, path: request.path }, 'Handler error');
65
+ return { status: 500, body: { message: 'Internal Server Error' } };
66
+ }
67
+ },
68
+ async http(options) {
69
+ const port = options?.port ?? 3000;
70
+ const server = http.createServer((req, res) => {
71
+ const method = (req.method || 'GET').toUpperCase();
72
+ const url = new URL(req.url || '/', 'http://localhost');
73
+ const path = url.pathname;
74
+ const query = {};
75
+ url.searchParams.forEach((value, key) => {
76
+ query[key] = value;
77
+ });
78
+ const headers = {};
79
+ for (const [k, v] of Object.entries(req.headers)) {
80
+ if (typeof v === 'string') headers[k] = v;
81
+ else if (Array.isArray(v)) headers[k] = v.join(',');
82
+ }
83
+ let raw = '';
84
+ req.setEncoding('utf8');
85
+ req.on('data', (chunk) => {
86
+ raw += String(chunk);
87
+ });
88
+ req.on('end', async () => {
89
+ let body = undefined;
90
+ const contentType = headers['content-type'] || headers['Content-Type'];
91
+ if (raw) {
92
+ if (contentType && contentType.includes('application/json')) {
93
+ try {
94
+ body = JSON.parse(raw);
95
+ } catch {
96
+ body = raw;
97
+ }
98
+ } else {
99
+ body = raw;
54
100
  }
55
- try {
56
- const response = await route.handler(request);
57
- return response;
58
- }
59
- catch (error) {
60
- const err = error instanceof Error ? error : new Error(String(error));
61
- unnbound_logger_sdk_1.logger.error({ err, path: request.path }, 'Handler error');
62
- return { status: 500, body: { message: 'Internal Server Error' } };
63
- }
64
- },
65
- async http(options) {
66
- const port = options?.port ?? 3000;
67
- const server = http.createServer((req, res) => {
68
- const method = (req.method || 'GET').toUpperCase();
69
- const url = new URL(req.url || '/', 'http://localhost');
70
- const path = url.pathname;
71
- const query = {};
72
- url.searchParams.forEach((value, key) => {
73
- query[key] = value;
74
- });
75
- const headers = {};
76
- for (const [k, v] of Object.entries(req.headers)) {
77
- if (typeof v === 'string')
78
- headers[k] = v;
79
- else if (Array.isArray(v))
80
- headers[k] = v.join(',');
81
- }
82
- let raw = '';
83
- req.setEncoding('utf8');
84
- req.on('data', (chunk) => {
85
- raw += String(chunk);
86
- });
87
- req.on('end', async () => {
88
- let body = undefined;
89
- const contentType = headers['content-type'] || headers['Content-Type'];
90
- if (raw) {
91
- if (contentType && contentType.includes('application/json')) {
92
- try {
93
- body = JSON.parse(raw);
94
- }
95
- catch {
96
- body = raw;
97
- }
98
- }
99
- else {
100
- body = raw;
101
- }
102
- }
103
- const eventReq = {
104
- method,
105
- path,
106
- headers,
107
- query,
108
- body,
109
- metadata: { source: 'http' },
110
- };
111
- const eventRes = await this.handle(eventReq);
112
- res.statusCode = eventRes.status;
113
- if (eventRes.headers) {
114
- for (const [k, v] of Object.entries(eventRes.headers))
115
- res.setHeader(k, v);
116
- }
117
- if (eventRes.body !== undefined) {
118
- const bodyStr = typeof eventRes.body === 'string' ? eventRes.body : JSON.stringify(eventRes.body);
119
- res.end(bodyStr);
120
- }
121
- else {
122
- res.end();
123
- }
124
- });
101
+ }
102
+ const eventReq = {
103
+ method,
104
+ path,
105
+ headers,
106
+ query,
107
+ body,
108
+ metadata: { source: 'http' },
109
+ };
110
+ const eventRes = await this.handle(eventReq);
111
+ res.statusCode = eventRes.status;
112
+ if (eventRes.headers) {
113
+ for (const [k, v] of Object.entries(eventRes.headers)) res.setHeader(k, v);
114
+ }
115
+ if (eventRes.body !== undefined) {
116
+ const bodyStr =
117
+ typeof eventRes.body === 'string' ? eventRes.body : JSON.stringify(eventRes.body);
118
+ res.end(bodyStr);
119
+ } else {
120
+ res.end();
121
+ }
122
+ });
123
+ });
124
+ await new Promise((resolve) => server.listen(port, resolve));
125
+ unnbound_logger_sdk_1.logger.info({ port }, 'HTTP server started');
126
+ return {
127
+ close() {
128
+ return new Promise((resolve, reject) => {
129
+ server.close((err) => {
130
+ if (err instanceof Error) {
131
+ reject(err);
132
+ return;
133
+ }
134
+ if (typeof err === 'string') {
135
+ reject(new Error(err));
136
+ return;
137
+ }
138
+ if (err != null) {
139
+ reject(new Error('Server close failed'));
140
+ return;
141
+ }
142
+ resolve();
125
143
  });
126
- await new Promise((resolve) => server.listen(port, resolve));
127
- unnbound_logger_sdk_1.logger.info({ port }, 'HTTP server started');
128
- return {
129
- close() {
130
- return new Promise((resolve, reject) => {
131
- server.close((err) => {
132
- if (err instanceof Error) {
133
- reject(err);
134
- return;
135
- }
136
- if (typeof err === 'string') {
137
- reject(new Error(err));
138
- return;
139
- }
140
- if (err != null) {
141
- reject(new Error('Server close failed'));
142
- return;
143
- }
144
- resolve();
145
- });
146
- });
147
- },
148
- };
144
+ });
149
145
  },
150
- sqs() {
151
- return async (event) => {
152
- let successes = 0;
153
- const failures = [];
154
- await Promise.all(event.Records.map(async (record) => {
155
- try {
156
- const envelope = JSON.parse(record.body);
157
- const req = {
158
- method: envelope.request.method,
159
- path: envelope.request.path,
160
- headers: envelope.request.headers,
161
- query: envelope.request.query,
162
- body: envelope.request.body,
163
- metadata: { source: 'sqs', ...envelope.metadata },
164
- };
165
- const res = await this.handle(req);
166
- if (res.status >= 200 && res.status < 300)
167
- successes += 1;
168
- else
169
- failures.push({
170
- messageId: record.messageId,
171
- reason: `Handler returned status ${res.status}`,
172
- });
173
- }
174
- catch (error) {
175
- const err = error instanceof Error ? error : new Error(String(error));
176
- failures.push({
177
- messageId: record.messageId,
178
- reason: err.message ?? 'Unknown error',
179
- });
180
- }
181
- }));
182
- return { successes, failures };
183
- };
184
- },
185
- sqsListen(options) {
186
- const awsSqs = (() => {
187
- try {
188
- return require('@aws-sdk/client-sqs');
189
- }
190
- catch {
191
- return null;
192
- }
193
- })();
194
- if (!awsSqs) {
195
- throw new Error('@aws-sdk/client-sqs is required to use sqsListen');
196
- }
197
- const env = globalThis
198
- .process?.env ?? {};
199
- const queueUrl = options?.queueUrl || env.SQS_QUEUE_URL || env.QUEUE_URL;
200
- if (!queueUrl || queueUrl === undefined) {
201
- throw new Error('SQS queue URL not provided. Set SQS_QUEUE_URL env or pass options.queueUrl');
202
- }
203
- const region = options?.region || env.AWS_REGION || 'us-east-1';
204
- const endpoint = env.AWS_SQS_ENDPOINT || env.AWS_ENDPOINT_URL || undefined;
205
- const waitTimeSeconds = options?.waitTimeSeconds ?? 10;
206
- const maxMessages = options?.maxMessages ?? 10;
207
- const visibilityTimeout = options?.visibilityTimeoutSeconds;
208
- const sqs = new awsSqs.SQSClient({ region, endpoint });
209
- let stopped = false;
210
- const consume = this.sqs();
211
- async function loop() {
212
- while (!stopped) {
213
- try {
214
- const params = {
215
- QueueUrl: queueUrl,
216
- MaxNumberOfMessages: maxMessages,
217
- WaitTimeSeconds: waitTimeSeconds,
218
- ...(visibilityTimeout && { VisibilityTimeout: visibilityTimeout }),
219
- };
220
- const resp = (await sqs.send(new awsSqs.ReceiveMessageCommand(params)));
221
- const messages = (resp.Messages ?? []).map((m) => ({
222
- id: m.MessageId ?? '',
223
- body: String(m.Body ?? ''),
224
- receiptHandle: String(m.ReceiptHandle ?? ''),
225
- }));
226
- if (messages.length === 0)
227
- continue;
228
- const result = await consume({
229
- Records: messages.map((m) => ({ messageId: m.id, body: m.body })),
230
- });
231
- const failed = new Set(result.failures.map((f) => f.messageId));
232
- const toDelete = messages
233
- .filter((m) => !failed.has(m.id))
234
- .map((m) => ({ Id: m.id, ReceiptHandle: m.receiptHandle }));
235
- for (let i = 0; i < toDelete.length; i += 10) {
236
- const chunk = toDelete.slice(i, i + 10);
237
- if (chunk.length > 0) {
238
- await sqs.send(new awsSqs.DeleteMessageBatchCommand({ QueueUrl: queueUrl, Entries: chunk }));
239
- }
240
- }
241
- }
242
- catch (err) {
243
- unnbound_logger_sdk_1.logger.error({ err }, 'SQS listen loop error');
244
- }
245
- }
246
- }
247
- // Start async loop without awaiting
248
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
249
- loop();
250
- return Promise.resolve({
251
- stop() {
252
- stopped = true;
253
- return Promise.resolve();
254
- },
255
- });
256
- },
257
- async start(options) {
258
- // Default to starting both HTTP and SQS if no options provided
259
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
260
- const httpOptions = options?.http ?? { port: 3000 };
261
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
262
- const sqsOptions = options?.sqs ?? {};
263
- // Start HTTP server
264
- let httpServer;
146
+ };
147
+ },
148
+ sqs() {
149
+ return async (event) => {
150
+ let successes = 0;
151
+ const failures = [];
152
+ await Promise.all(
153
+ event.Records.map(async (record) => {
265
154
  try {
266
- httpServer = await this.http(httpOptions);
267
- }
268
- catch (error) {
269
- unnbound_logger_sdk_1.logger.warn({ error }, 'Failed to start HTTP server, continuing without it');
270
- }
271
- // Start SQS listener
272
- let sqsListener;
273
- try {
274
- sqsListener = await this.sqsListen(sqsOptions);
275
- }
276
- catch (error) {
277
- unnbound_logger_sdk_1.logger.warn({ error }, 'Failed to start SQS listener, continuing without it');
278
- }
279
- // If neither HTTP nor SQS started successfully, throw an error
280
- if (!httpServer && !sqsListener) {
281
- throw new Error('Failed to start any transport. Please check your configuration and try again.');
155
+ const envelope = JSON.parse(record.body);
156
+ const req = {
157
+ method: envelope.request.method,
158
+ path: envelope.request.path,
159
+ headers: envelope.request.headers,
160
+ query: envelope.request.query,
161
+ body: envelope.request.body,
162
+ metadata: { source: 'sqs', ...envelope.metadata },
163
+ };
164
+ const res = await this.handle(req);
165
+ if (res.status >= 200 && res.status < 300) successes += 1;
166
+ else
167
+ failures.push({
168
+ messageId: record.messageId,
169
+ reason: `Handler returned status ${res.status}`,
170
+ });
171
+ } catch (error) {
172
+ const err = error instanceof Error ? error : new Error(String(error));
173
+ failures.push({
174
+ messageId: record.messageId,
175
+ reason: err.message ?? 'Unknown error',
176
+ });
282
177
  }
283
- // Set up graceful shutdown
284
- const g = globalThis;
285
- const shutdown = async () => {
286
- unnbound_logger_sdk_1.logger.info('Received shutdown signal, closing servers...');
287
- const promises = [];
288
- if (httpServer)
289
- promises.push(httpServer.close());
290
- if (sqsListener)
291
- promises.push(sqsListener.stop());
292
- await Promise.all(promises);
293
- unnbound_logger_sdk_1.logger.info('All servers closed');
294
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
295
- g.process?.exit?.(0);
178
+ })
179
+ );
180
+ return { successes, failures };
181
+ };
182
+ },
183
+ sqsListen(options) {
184
+ const AWS = (() => {
185
+ try {
186
+ return require('aws-sdk');
187
+ } catch {
188
+ return null;
189
+ }
190
+ })();
191
+ if (!AWS) {
192
+ throw new Error('aws-sdk is required to use sqsListen');
193
+ }
194
+ const env = globalThis.process?.env ?? {};
195
+ const queueUrl = options?.queueUrl || env.SQS_QUEUE_URL || env.QUEUE_URL;
196
+ if (!queueUrl || queueUrl === undefined) {
197
+ throw new Error(
198
+ 'SQS queue URL not provided. Set SQS_QUEUE_URL env or pass options.queueUrl'
199
+ );
200
+ }
201
+ const region = options?.region || env.AWS_REGION || 'us-east-1';
202
+ const endpoint = env.AWS_SQS_ENDPOINT || env.AWS_ENDPOINT_URL || undefined;
203
+ const waitTimeSeconds = options?.waitTimeSeconds ?? 10;
204
+ const maxMessages = options?.maxMessages ?? 10;
205
+ const visibilityTimeout = options?.visibilityTimeoutSeconds;
206
+ const AWSLib = AWS;
207
+ const sqs = new AWSLib.SQS({ region, endpoint });
208
+ let stopped = false;
209
+ const consume = this.sqs();
210
+ async function loop() {
211
+ while (!stopped) {
212
+ try {
213
+ const params = {
214
+ QueueUrl: queueUrl,
215
+ MaxNumberOfMessages: maxMessages,
216
+ WaitTimeSeconds: waitTimeSeconds,
296
217
  };
297
- // Handle SIGINT and SIGTERM
298
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
299
- g.process?.on?.('SIGINT', shutdown);
300
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
301
- g.process?.on?.('SIGTERM', shutdown);
302
- // Log startup information
303
- const services = [];
304
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
305
- if (httpServer)
306
- services.push(`HTTP on port ${httpOptions?.port ?? 3000}`);
307
- if (sqsListener)
308
- services.push('SQS listener');
309
- unnbound_logger_sdk_1.logger.info({ services: services.join(' and ') }, 'Services started. Press Ctrl+C to stop.');
218
+ if (visibilityTimeout) params.VisibilityTimeout = visibilityTimeout;
219
+ const resp = await sqs.receiveMessage(params).promise();
220
+ const messages = (resp.Messages ?? []).map((m) => ({
221
+ id: m.MessageId ?? '',
222
+ body: String(m.Body ?? ''),
223
+ receiptHandle: String(m.ReceiptHandle ?? ''),
224
+ }));
225
+ if (messages.length === 0) continue;
226
+ const result = await consume({
227
+ Records: messages.map((m) => ({ messageId: m.id, body: m.body })),
228
+ });
229
+ const failed = new Set(result.failures.map((f) => f.messageId));
230
+ const toDelete = messages
231
+ .filter((m) => !failed.has(m.id))
232
+ .map((m) => ({ Id: m.id, ReceiptHandle: m.receiptHandle }));
233
+ for (let i = 0; i < toDelete.length; i += 10) {
234
+ const chunk = toDelete.slice(i, i + 10);
235
+ if (chunk.length > 0) {
236
+ await sqs.deleteMessageBatch({ QueueUrl: queueUrl, Entries: chunk }).promise();
237
+ }
238
+ }
239
+ } catch (err) {
240
+ unnbound_logger_sdk_1.logger.error({ err }, 'SQS listen loop error');
241
+ }
242
+ }
243
+ }
244
+ // Start async loop without awaiting
245
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
246
+ loop();
247
+ return Promise.resolve({
248
+ stop() {
249
+ stopped = true;
250
+ return Promise.resolve();
310
251
  },
311
- };
252
+ });
253
+ },
254
+ };
312
255
  }