unnbound-events 1.0.0 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +4 -0
- package/dist/index.js +9 -0
- package/dist/lib/adapters/express.d.ts +16 -0
- package/dist/lib/adapters/express.js +38 -0
- package/dist/lib/adapters/sqs.d.ts +36 -0
- package/dist/lib/adapters/sqs.js +42 -0
- package/dist/lib/client.d.ts +2 -0
- package/dist/lib/client.js +312 -0
- package/dist/lib/types.d.ts +73 -0
- package/dist/lib/types.js +2 -0
- package/dist/logger/src/axios.d.ts +4 -2
- package/dist/logger/src/axios.js +11 -6
- package/dist/logger/src/middleware.d.ts +9 -2
- package/dist/logger/src/middleware.js +12 -8
- package/dist/logger/src/types.d.ts +2 -1
- package/package.json +2 -2
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { createEventsClient } from './lib/client';
|
|
2
|
+
export type { EventsClient, EventRequest, EventResponse, RouteHandler, RouteMatcher, RegisteredRoute, SqsBatchEvent, StartOptions, } from './lib/types';
|
|
3
|
+
export { createExpressMiddleware } from './lib/adapters/express';
|
|
4
|
+
export { createSqsConsumer } from './lib/adapters/sqs';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createSqsConsumer = exports.createExpressMiddleware = exports.createEventsClient = void 0;
|
|
4
|
+
var client_1 = require("./lib/client");
|
|
5
|
+
Object.defineProperty(exports, "createEventsClient", { enumerable: true, get: function () { return client_1.createEventsClient; } });
|
|
6
|
+
var express_1 = require("./lib/adapters/express");
|
|
7
|
+
Object.defineProperty(exports, "createExpressMiddleware", { enumerable: true, get: function () { return express_1.createExpressMiddleware; } });
|
|
8
|
+
var sqs_1 = require("./lib/adapters/sqs");
|
|
9
|
+
Object.defineProperty(exports, "createSqsConsumer", { enumerable: true, get: function () { return sqs_1.createSqsConsumer; } });
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
type Request = {
|
|
2
|
+
method: string;
|
|
3
|
+
path: string;
|
|
4
|
+
headers: Record<string, string | string[] | undefined>;
|
|
5
|
+
query: Record<string, unknown>;
|
|
6
|
+
body: unknown;
|
|
7
|
+
};
|
|
8
|
+
type Response = {
|
|
9
|
+
status: (code: number) => Response;
|
|
10
|
+
setHeader: (name: string, value: string) => void;
|
|
11
|
+
send: (body: unknown) => void;
|
|
12
|
+
end: () => void;
|
|
13
|
+
};
|
|
14
|
+
import type { EventsClient } from '../types';
|
|
15
|
+
export declare function createExpressMiddleware(client: EventsClient): (req: Request, res: Response) => Promise<void>;
|
|
16
|
+
export {};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createExpressMiddleware = createExpressMiddleware;
|
|
4
|
+
function toEventRequest(req) {
|
|
5
|
+
const method = req.method.toUpperCase();
|
|
6
|
+
const headers = {};
|
|
7
|
+
for (const [key, value] of Object.entries(req.headers)) {
|
|
8
|
+
if (typeof value === 'string')
|
|
9
|
+
headers[key] = value;
|
|
10
|
+
else if (Array.isArray(value))
|
|
11
|
+
headers[key] = value.join(',');
|
|
12
|
+
}
|
|
13
|
+
return {
|
|
14
|
+
method,
|
|
15
|
+
path: req.path,
|
|
16
|
+
headers,
|
|
17
|
+
query: req.query,
|
|
18
|
+
body: req.body,
|
|
19
|
+
metadata: { source: 'http' },
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
function applyResponse(res, response) {
|
|
23
|
+
res.status(response.status);
|
|
24
|
+
if (response.headers) {
|
|
25
|
+
for (const [k, v] of Object.entries(response.headers))
|
|
26
|
+
res.setHeader(k, v);
|
|
27
|
+
}
|
|
28
|
+
if (response.body !== undefined)
|
|
29
|
+
return res.send(response.body);
|
|
30
|
+
return res.end();
|
|
31
|
+
}
|
|
32
|
+
function createExpressMiddleware(client) {
|
|
33
|
+
return async function eventsMiddleware(req, res) {
|
|
34
|
+
const eventReq = toEventRequest(req);
|
|
35
|
+
const eventRes = await client.handle(eventReq);
|
|
36
|
+
applyResponse(res, eventRes);
|
|
37
|
+
};
|
|
38
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { EventsClient, HttpMethod } from '../types';
|
|
2
|
+
export interface QueueEnvelope {
|
|
3
|
+
id: string;
|
|
4
|
+
timestamp: number;
|
|
5
|
+
version: string;
|
|
6
|
+
workflow: string;
|
|
7
|
+
priority: number;
|
|
8
|
+
payload: {
|
|
9
|
+
type: string;
|
|
10
|
+
size: number;
|
|
11
|
+
compressed: boolean;
|
|
12
|
+
};
|
|
13
|
+
request: {
|
|
14
|
+
method: HttpMethod;
|
|
15
|
+
path: string;
|
|
16
|
+
headers: Record<string, string>;
|
|
17
|
+
query: Record<string, unknown>;
|
|
18
|
+
body: unknown;
|
|
19
|
+
};
|
|
20
|
+
metadata?: Record<string, unknown>;
|
|
21
|
+
addons?: Record<string, unknown>;
|
|
22
|
+
}
|
|
23
|
+
export type SqsRecord = {
|
|
24
|
+
messageId: string;
|
|
25
|
+
body: string;
|
|
26
|
+
};
|
|
27
|
+
export interface SqsBatchEvent {
|
|
28
|
+
Records: SqsRecord[];
|
|
29
|
+
}
|
|
30
|
+
export declare function createSqsConsumer(client: EventsClient): (event: SqsBatchEvent) => Promise<{
|
|
31
|
+
successes: number;
|
|
32
|
+
failures: Array<{
|
|
33
|
+
messageId: string;
|
|
34
|
+
reason: string;
|
|
35
|
+
}>;
|
|
36
|
+
}>;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createSqsConsumer = createSqsConsumer;
|
|
4
|
+
function createSqsConsumer(client) {
|
|
5
|
+
return async function consume(event) {
|
|
6
|
+
let successes = 0;
|
|
7
|
+
const failures = [];
|
|
8
|
+
await Promise.all(event.Records.map(async (record) => {
|
|
9
|
+
try {
|
|
10
|
+
const envelope = JSON.parse(record.body);
|
|
11
|
+
const req = {
|
|
12
|
+
method: envelope.request.method,
|
|
13
|
+
path: envelope.request.path,
|
|
14
|
+
headers: envelope.request.headers,
|
|
15
|
+
query: envelope.request.query,
|
|
16
|
+
body: envelope.request.body,
|
|
17
|
+
metadata: {
|
|
18
|
+
source: 'sqs',
|
|
19
|
+
id: envelope.id,
|
|
20
|
+
workflow: envelope.workflow,
|
|
21
|
+
timestamp: envelope.timestamp,
|
|
22
|
+
version: envelope.version,
|
|
23
|
+
...envelope.metadata,
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
const res = await client.handle(req);
|
|
27
|
+
if (res.status >= 200 && res.status < 300)
|
|
28
|
+
successes += 1;
|
|
29
|
+
else
|
|
30
|
+
failures.push({
|
|
31
|
+
messageId: record.messageId,
|
|
32
|
+
reason: `Handler returned status ${res.status}`,
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
37
|
+
failures.push({ messageId: record.messageId, reason: err.message ?? 'Unknown error' });
|
|
38
|
+
}
|
|
39
|
+
}));
|
|
40
|
+
return { successes, failures };
|
|
41
|
+
};
|
|
42
|
+
}
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createEventsClient = createEventsClient;
|
|
4
|
+
const unnbound_logger_sdk_1 = require("unnbound-logger-sdk");
|
|
5
|
+
const http = (() => {
|
|
6
|
+
try {
|
|
7
|
+
return (require && require('http'));
|
|
8
|
+
}
|
|
9
|
+
catch {
|
|
10
|
+
return null;
|
|
11
|
+
}
|
|
12
|
+
})();
|
|
13
|
+
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);
|
|
21
|
+
}
|
|
22
|
+
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' } };
|
|
54
|
+
}
|
|
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
|
+
});
|
|
125
|
+
});
|
|
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
|
+
};
|
|
149
|
+
},
|
|
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;
|
|
265
|
+
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.');
|
|
282
|
+
}
|
|
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);
|
|
296
|
+
};
|
|
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.');
|
|
310
|
+
},
|
|
311
|
+
};
|
|
312
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD';
|
|
2
|
+
export interface EventRequest<Body = unknown, Query = Record<string, unknown>> {
|
|
3
|
+
method: HttpMethod;
|
|
4
|
+
path: string;
|
|
5
|
+
headers: Record<string, string>;
|
|
6
|
+
query: Query;
|
|
7
|
+
body: Body;
|
|
8
|
+
metadata?: Record<string, unknown>;
|
|
9
|
+
}
|
|
10
|
+
export interface EventResponse<Body = unknown> {
|
|
11
|
+
status: number;
|
|
12
|
+
headers?: Record<string, string>;
|
|
13
|
+
body?: Body;
|
|
14
|
+
}
|
|
15
|
+
export type RouteHandler<ReqBody = unknown, ResBody = unknown> = (request: EventRequest<ReqBody>) => Promise<EventResponse<ResBody>> | EventResponse<ResBody>;
|
|
16
|
+
export type RouteMatcher = string | RegExp | ((path: string) => boolean);
|
|
17
|
+
export interface RegisteredRoute {
|
|
18
|
+
method: HttpMethod;
|
|
19
|
+
matcher: RouteMatcher;
|
|
20
|
+
handler: RouteHandler<any, any>;
|
|
21
|
+
}
|
|
22
|
+
export type SqsRecord = {
|
|
23
|
+
messageId: string;
|
|
24
|
+
body: string;
|
|
25
|
+
};
|
|
26
|
+
export interface SqsBatchEvent {
|
|
27
|
+
Records: SqsRecord[];
|
|
28
|
+
}
|
|
29
|
+
export interface StartOptions {
|
|
30
|
+
http?: {
|
|
31
|
+
port?: number;
|
|
32
|
+
};
|
|
33
|
+
sqs?: {
|
|
34
|
+
queueUrl?: string;
|
|
35
|
+
region?: string;
|
|
36
|
+
waitTimeSeconds?: number;
|
|
37
|
+
maxMessages?: number;
|
|
38
|
+
visibilityTimeoutSeconds?: number;
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
export interface EventsClient {
|
|
42
|
+
on: (method: HttpMethod, matcher: RouteMatcher, handler: RouteHandler<any, any>) => void;
|
|
43
|
+
handle: (request: EventRequest<any>) => Promise<EventResponse<any>>;
|
|
44
|
+
get: (matcher: RouteMatcher, handler: RouteHandler<any, any>) => void;
|
|
45
|
+
post: (matcher: RouteMatcher, handler: RouteHandler<any, any>) => void;
|
|
46
|
+
put: (matcher: RouteMatcher, handler: RouteHandler<any, any>) => void;
|
|
47
|
+
patch: (matcher: RouteMatcher, handler: RouteHandler<any, any>) => void;
|
|
48
|
+
delete: (matcher: RouteMatcher, handler: RouteHandler<any, any>) => void;
|
|
49
|
+
options: (matcher: RouteMatcher, handler: RouteHandler<any, any>) => void;
|
|
50
|
+
head: (matcher: RouteMatcher, handler: RouteHandler<any, any>) => void;
|
|
51
|
+
http: (options?: {
|
|
52
|
+
port?: number;
|
|
53
|
+
}) => Promise<{
|
|
54
|
+
close: () => Promise<void>;
|
|
55
|
+
}>;
|
|
56
|
+
sqs: () => (event: SqsBatchEvent) => Promise<{
|
|
57
|
+
successes: number;
|
|
58
|
+
failures: Array<{
|
|
59
|
+
messageId: string;
|
|
60
|
+
reason: string;
|
|
61
|
+
}>;
|
|
62
|
+
}>;
|
|
63
|
+
sqsListen: (options?: {
|
|
64
|
+
queueUrl?: string;
|
|
65
|
+
region?: string;
|
|
66
|
+
waitTimeSeconds?: number;
|
|
67
|
+
maxMessages?: number;
|
|
68
|
+
visibilityTimeoutSeconds?: number;
|
|
69
|
+
}) => Promise<{
|
|
70
|
+
stop: () => Promise<void>;
|
|
71
|
+
}>;
|
|
72
|
+
start: (options?: StartOptions) => Promise<void>;
|
|
73
|
+
}
|
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
import { Axios } from 'axios';
|
|
1
|
+
import { Axios, type AxiosRequestConfig, type AxiosResponse } from 'axios';
|
|
2
2
|
import { HttpOptions } from './types';
|
|
3
|
+
type GetPayload = (config: AxiosRequestConfig, res?: AxiosResponse) => object;
|
|
3
4
|
/**
|
|
4
5
|
* Wraps an axios instance to add tracing and span tracking
|
|
5
6
|
* @param axios - The axios instance to wrap
|
|
6
7
|
* @param options - Configuration options for HTTP tracing
|
|
7
8
|
* @returns The wrapped axios instance with span tracking
|
|
8
9
|
*/
|
|
9
|
-
export declare const traceAxios: (client: Axios, { ignoreTraceRoutes, traceHeaderKey, }?: HttpOptions) => Axios;
|
|
10
|
+
export declare const traceAxios: (client: Axios, { ignoreTraceRoutes, traceHeaderKey, getPayload, }?: HttpOptions<GetPayload>) => Axios;
|
|
11
|
+
export {};
|
package/dist/logger/src/axios.js
CHANGED
|
@@ -25,15 +25,17 @@ const buildOutgoingHttpPayload = (config, res) => ({
|
|
|
25
25
|
: undefined,
|
|
26
26
|
},
|
|
27
27
|
});
|
|
28
|
+
const getNoopPayload = () => ({});
|
|
28
29
|
/**
|
|
29
30
|
* Wraps an axios instance to add tracing and span tracking
|
|
30
31
|
* @param axios - The axios instance to wrap
|
|
31
32
|
* @param options - Configuration options for HTTP tracing
|
|
32
33
|
* @returns The wrapped axios instance with span tracking
|
|
33
34
|
*/
|
|
34
|
-
const traceAxios = (client, { ignoreTraceRoutes = types_1.defaultIgnoreTraceRoutes, traceHeaderKey = types_1.defaultTraceHeaderKey, } = {
|
|
35
|
+
const traceAxios = (client, { ignoreTraceRoutes = types_1.defaultIgnoreTraceRoutes, traceHeaderKey = types_1.defaultTraceHeaderKey, getPayload = getNoopPayload, } = {
|
|
35
36
|
ignoreTraceRoutes: types_1.defaultIgnoreTraceRoutes,
|
|
36
37
|
traceHeaderKey: types_1.defaultTraceHeaderKey,
|
|
38
|
+
getPayload: getNoopPayload,
|
|
37
39
|
}) => {
|
|
38
40
|
const createSpanWrappedRequest = (originalMethod, method) => {
|
|
39
41
|
const { headers: defaultHeaders, ...partialDefaultConfig } = client.defaults;
|
|
@@ -50,11 +52,14 @@ const traceAxios = (client, { ignoreTraceRoutes = types_1.defaultIgnoreTraceRout
|
|
|
50
52
|
config = { ...config, headers: { ...config.headers, [traceHeaderKey]: traceId } };
|
|
51
53
|
// Execute the request within a span
|
|
52
54
|
return (0, span_1.startSpan)(`Outgoing HTTP request`, () => originalMethod(config), (options) => {
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
55
|
+
const response = options
|
|
56
|
+
? options.error
|
|
57
|
+
? (0, axios_1.isAxiosError)(options.error)
|
|
58
|
+
? options.error.response
|
|
59
|
+
: undefined
|
|
60
|
+
: options.result
|
|
61
|
+
: undefined;
|
|
62
|
+
return { ...buildOutgoingHttpPayload(config, response), ...getPayload(config, response) };
|
|
58
63
|
});
|
|
59
64
|
};
|
|
60
65
|
};
|
|
@@ -1,3 +1,10 @@
|
|
|
1
|
-
import { RequestHandler } from 'express';
|
|
1
|
+
import { Request, RequestHandler } from 'express';
|
|
2
2
|
import { HttpOptions } from './types';
|
|
3
|
-
|
|
3
|
+
interface Response {
|
|
4
|
+
status: number;
|
|
5
|
+
headers?: Record<string, string | undefined>;
|
|
6
|
+
body?: unknown;
|
|
7
|
+
}
|
|
8
|
+
type GetPayload = (config: Request, res?: Response) => object;
|
|
9
|
+
export declare const traceMiddleware: ({ ignoreTraceRoutes, traceHeaderKey, getPayload, }?: HttpOptions<GetPayload>) => RequestHandler;
|
|
10
|
+
export {};
|
|
@@ -19,7 +19,7 @@ const getFullUrl = (req) => {
|
|
|
19
19
|
const host = req.get('host') || req.get('x-forwarded-host') || 'localhost';
|
|
20
20
|
return `${protocol}://${host}${url}`;
|
|
21
21
|
};
|
|
22
|
-
const buildIncomingHttpPayload = (req, res
|
|
22
|
+
const buildIncomingHttpPayload = (req, res) => ({
|
|
23
23
|
type: 'http',
|
|
24
24
|
http: {
|
|
25
25
|
url: getFullUrl(req),
|
|
@@ -32,16 +32,18 @@ const buildIncomingHttpPayload = (req, res, body) => ({
|
|
|
32
32
|
},
|
|
33
33
|
response: res
|
|
34
34
|
? {
|
|
35
|
-
headers: res
|
|
36
|
-
status: res.
|
|
37
|
-
body: (0, utils_1.safeJsonParse)(body),
|
|
35
|
+
headers: res.headers,
|
|
36
|
+
status: res.status,
|
|
37
|
+
body: (0, utils_1.safeJsonParse)(res.body),
|
|
38
38
|
}
|
|
39
39
|
: undefined,
|
|
40
40
|
},
|
|
41
41
|
});
|
|
42
|
-
const
|
|
42
|
+
const getNoopPayload = () => ({});
|
|
43
|
+
const traceMiddleware = ({ ignoreTraceRoutes = types_1.defaultIgnoreTraceRoutes, traceHeaderKey = types_1.defaultTraceHeaderKey, getPayload = getNoopPayload, } = {
|
|
43
44
|
ignoreTraceRoutes: types_1.defaultIgnoreTraceRoutes,
|
|
44
45
|
traceHeaderKey: types_1.defaultTraceHeaderKey,
|
|
46
|
+
getPayload: getNoopPayload,
|
|
45
47
|
}) => async (req, res, next) => {
|
|
46
48
|
if ((0, utils_1.shouldIgnorePath)(req.path, ignoreTraceRoutes))
|
|
47
49
|
return next();
|
|
@@ -60,12 +62,14 @@ const traceMiddleware = ({ ignoreTraceRoutes = types_1.defaultIgnoreTraceRoutes,
|
|
|
60
62
|
return next();
|
|
61
63
|
});
|
|
62
64
|
}, (o) => {
|
|
63
|
-
|
|
65
|
+
const response = o
|
|
64
66
|
? {
|
|
65
|
-
|
|
67
|
+
status: res.statusCode,
|
|
66
68
|
headers: res.getHeaders(),
|
|
69
|
+
body: res.locals.body,
|
|
67
70
|
}
|
|
68
|
-
: undefined
|
|
71
|
+
: undefined;
|
|
72
|
+
return { ...buildIncomingHttpPayload(req, response), ...getPayload(req, response) };
|
|
69
73
|
});
|
|
70
74
|
}, { traceId });
|
|
71
75
|
};
|
|
@@ -53,9 +53,10 @@ export interface SftpPayload {
|
|
|
53
53
|
content?: string;
|
|
54
54
|
exists?: string | false;
|
|
55
55
|
}
|
|
56
|
-
export interface HttpOptions {
|
|
56
|
+
export interface HttpOptions<G extends Function> {
|
|
57
57
|
ignoreTraceRoutes?: string[];
|
|
58
58
|
traceHeaderKey?: string;
|
|
59
|
+
getPayload?: G;
|
|
59
60
|
}
|
|
60
61
|
export declare const defaultIgnoreTraceRoutes: string[];
|
|
61
62
|
export declare const defaultTraceHeaderKey = "x-unnbound-trace-id";
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "unnbound-events",
|
|
3
3
|
"description": "Unified events SDK to handle HTTP routes and SQS messages with a single routing API.",
|
|
4
|
-
"version": "1.0.
|
|
4
|
+
"version": "1.0.2",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
7
7
|
"scripts": {
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
"dependencies": {
|
|
33
33
|
"express": "^4.0.0 || ^5.0.0",
|
|
34
34
|
"@aws-sdk/client-sqs": "^3.0.0",
|
|
35
|
-
"unnbound-logger-sdk": "
|
|
35
|
+
"unnbound-logger-sdk": "^3.0.9"
|
|
36
36
|
},
|
|
37
37
|
"peerDependencies": {
|
|
38
38
|
"express": "^4.0.0 || ^5.0.0"
|