unnbound-events 2.0.14 → 2.0.16
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/lib/routing/endpoint.js +2 -0
- package/dist/lib/routing/middleware.js +6 -1
- package/package.json +18 -17
- package/LICENSE +0 -21
- package/dist/events/src/index.d.ts +0 -12
- package/dist/events/src/index.js +0 -24
- package/dist/events/src/lib/adapters/express.d.ts +0 -18
- package/dist/events/src/lib/adapters/express.js +0 -34
- package/dist/events/src/lib/adapters/sqs.d.ts +0 -36
- package/dist/events/src/lib/adapters/sqs.js +0 -42
- package/dist/events/src/lib/client.d.ts +0 -2
- package/dist/events/src/lib/client.js +0 -255
- package/dist/events/src/lib/types.d.ts +0 -60
- package/dist/events/src/lib/types.js +0 -2
- package/dist/lib/adapters/adapter.d.ts +0 -40
- package/dist/lib/adapters/adapter.js +0 -70
- package/dist/lib/adapters/express.d.ts +0 -17
- package/dist/lib/adapters/express.js +0 -39
- package/dist/lib/adapters/sqs.d.ts +0 -29
- package/dist/lib/adapters/sqs.js +0 -7
- package/dist/lib/client.d.ts +0 -41
- package/dist/lib/client.js +0 -153
- package/dist/lib/types.d.ts +0 -30
- package/dist/lib/types.js +0 -2
- package/dist/logger/src/axios.d.ts +0 -12
- package/dist/logger/src/axios.js +0 -85
- package/dist/logger/src/index.d.ts +0 -13
- package/dist/logger/src/index.js +0 -50
- package/dist/logger/src/logger.d.ts +0 -21
- package/dist/logger/src/logger.js +0 -46
- package/dist/logger/src/middleware.d.ts +0 -6
- package/dist/logger/src/middleware.js +0 -88
- package/dist/logger/src/span.d.ts +0 -22
- package/dist/logger/src/span.js +0 -48
- package/dist/logger/src/storage.d.ts +0 -6
- package/dist/logger/src/storage.js +0 -5
- package/dist/logger/src/trace.d.ts +0 -20
- package/dist/logger/src/trace.js +0 -28
- package/dist/logger/src/types.d.ts +0 -80
- package/dist/logger/src/types.js +0 -8
- package/dist/logger/src/utils.d.ts +0 -19
- package/dist/logger/src/utils.js +0 -51
|
@@ -21,6 +21,8 @@ exports.parseEndpointArguments = parseEndpointArguments;
|
|
|
21
21
|
const patchEndpoint = (handler) => {
|
|
22
22
|
return async (context) => {
|
|
23
23
|
const state = context.get('state');
|
|
24
|
+
// We have to recalculate the params because the handler path might contain url params
|
|
25
|
+
state.request.params = { ...state.request.params, ...context.req.param() };
|
|
24
26
|
const result = await (0, unnbound_logger_sdk_1.startSpan)('Event request', async () => {
|
|
25
27
|
const result = await handler(state);
|
|
26
28
|
return { status: result?.status ?? 204, headers: result?.headers, body: result?.body };
|
|
@@ -2,7 +2,12 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.buildMiddlewareArguments = exports.parseMiddlewareArguments = exports.patchMiddleware = void 0;
|
|
4
4
|
const patchMiddleware = (handler) => {
|
|
5
|
-
return (context, next) =>
|
|
5
|
+
return (context, next) => {
|
|
6
|
+
const state = context.get('state');
|
|
7
|
+
// We have to recalculate the params because middleware path might contain url params
|
|
8
|
+
state.request.params = { ...state.request.params, ...context.req.param() };
|
|
9
|
+
return handler(state, next);
|
|
10
|
+
};
|
|
6
11
|
};
|
|
7
12
|
exports.patchMiddleware = patchMiddleware;
|
|
8
13
|
const parseMiddlewareArguments = (...args) => {
|
package/package.json
CHANGED
|
@@ -1,9 +1,23 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "unnbound-events",
|
|
3
3
|
"description": "Unified events SDK to handle HTTP routes and queued messages with a single routing API.",
|
|
4
|
-
"version": "2.0.
|
|
4
|
+
"version": "2.0.16",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"build": "tsc",
|
|
9
|
+
"test": "jest",
|
|
10
|
+
"test:coverage": "jest --coverage",
|
|
11
|
+
"test:watch": "jest --watch",
|
|
12
|
+
"typecheck": "tsc -noEmit",
|
|
13
|
+
"lint": "eslint --cache --cache-location ./node_modules/.cache/eslint .",
|
|
14
|
+
"lint:fix": "pnpm lint --fix",
|
|
15
|
+
"format": "prettier --write .",
|
|
16
|
+
"format:check": "prettier --check .",
|
|
17
|
+
"prepublishOnly": "pnpm build",
|
|
18
|
+
"start:example": "npx --yes tsx --watch examples/node-server.ts",
|
|
19
|
+
"version:bump": "npm version patch"
|
|
20
|
+
},
|
|
7
21
|
"author": "Unnbound Team",
|
|
8
22
|
"license": "MIT",
|
|
9
23
|
"repository": {
|
|
@@ -20,7 +34,7 @@
|
|
|
20
34
|
"@hono/node-server": "^1.19.6",
|
|
21
35
|
"axios": "^1.12.2",
|
|
22
36
|
"hono": "^4.10.4",
|
|
23
|
-
"unnbound-logger-sdk": "
|
|
37
|
+
"unnbound-logger-sdk": "workspace:*"
|
|
24
38
|
},
|
|
25
39
|
"devDependencies": {
|
|
26
40
|
"@types/jest": "^29.5.12",
|
|
@@ -34,18 +48,5 @@
|
|
|
34
48
|
"engines": {
|
|
35
49
|
"node": ">=22"
|
|
36
50
|
},
|
|
37
|
-
"sideEffects": false
|
|
38
|
-
|
|
39
|
-
"build": "tsc",
|
|
40
|
-
"test": "jest",
|
|
41
|
-
"test:coverage": "jest --coverage",
|
|
42
|
-
"test:watch": "jest --watch",
|
|
43
|
-
"typecheck": "tsc -noEmit",
|
|
44
|
-
"lint": "eslint --cache --cache-location ./node_modules/.cache/eslint .",
|
|
45
|
-
"lint:fix": "pnpm lint --fix",
|
|
46
|
-
"format": "prettier --write .",
|
|
47
|
-
"format:check": "prettier --check .",
|
|
48
|
-
"start:example": "npx --yes tsx --watch examples/node-server.ts",
|
|
49
|
-
"version:bump": "npm version patch"
|
|
50
|
-
}
|
|
51
|
-
}
|
|
51
|
+
"sideEffects": false
|
|
52
|
+
}
|
package/LICENSE
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2025 Unnbound Team
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
export { createEventsClient } from './lib/client';
|
|
2
|
-
export type {
|
|
3
|
-
EventsClient,
|
|
4
|
-
EventRequest,
|
|
5
|
-
EventResponse,
|
|
6
|
-
RouteHandler,
|
|
7
|
-
RouteMatcher,
|
|
8
|
-
RegisteredRoute,
|
|
9
|
-
SqsBatchEvent,
|
|
10
|
-
} from './lib/types';
|
|
11
|
-
export { createExpressMiddleware } from './lib/adapters/express';
|
|
12
|
-
export { createSqsConsumer } from './lib/adapters/sqs';
|
package/dist/events/src/index.js
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
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', {
|
|
6
|
-
enumerable: true,
|
|
7
|
-
get: function () {
|
|
8
|
-
return client_1.createEventsClient;
|
|
9
|
-
},
|
|
10
|
-
});
|
|
11
|
-
var express_1 = require('./lib/adapters/express');
|
|
12
|
-
Object.defineProperty(exports, 'createExpressMiddleware', {
|
|
13
|
-
enumerable: true,
|
|
14
|
-
get: function () {
|
|
15
|
-
return express_1.createExpressMiddleware;
|
|
16
|
-
},
|
|
17
|
-
});
|
|
18
|
-
var sqs_1 = require('./lib/adapters/sqs');
|
|
19
|
-
Object.defineProperty(exports, 'createSqsConsumer', {
|
|
20
|
-
enumerable: true,
|
|
21
|
-
get: function () {
|
|
22
|
-
return sqs_1.createSqsConsumer;
|
|
23
|
-
},
|
|
24
|
-
});
|
|
@@ -1,18 +0,0 @@
|
|
|
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(
|
|
16
|
-
client: EventsClient
|
|
17
|
-
): (req: Request, res: Response) => Promise<void>;
|
|
18
|
-
export {};
|
|
@@ -1,34 +0,0 @@
|
|
|
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') headers[key] = value;
|
|
9
|
-
else if (Array.isArray(value)) headers[key] = value.join(',');
|
|
10
|
-
}
|
|
11
|
-
return {
|
|
12
|
-
method,
|
|
13
|
-
path: req.path,
|
|
14
|
-
headers,
|
|
15
|
-
query: req.query,
|
|
16
|
-
body: req.body,
|
|
17
|
-
metadata: { source: 'http' },
|
|
18
|
-
};
|
|
19
|
-
}
|
|
20
|
-
function applyResponse(res, response) {
|
|
21
|
-
res.status(response.status);
|
|
22
|
-
if (response.headers) {
|
|
23
|
-
for (const [k, v] of Object.entries(response.headers)) res.setHeader(k, v);
|
|
24
|
-
}
|
|
25
|
-
if (response.body !== undefined) return res.send(response.body);
|
|
26
|
-
return res.end();
|
|
27
|
-
}
|
|
28
|
-
function createExpressMiddleware(client) {
|
|
29
|
-
return async function eventsMiddleware(req, res) {
|
|
30
|
-
const eventReq = toEventRequest(req);
|
|
31
|
-
const eventRes = await client.handle(eventReq);
|
|
32
|
-
applyResponse(res, eventRes);
|
|
33
|
-
};
|
|
34
|
-
}
|
|
@@ -1,36 +0,0 @@
|
|
|
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
|
-
}>;
|
|
@@ -1,42 +0,0 @@
|
|
|
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(
|
|
9
|
-
event.Records.map(async (record) => {
|
|
10
|
-
try {
|
|
11
|
-
const envelope = JSON.parse(record.body);
|
|
12
|
-
const req = {
|
|
13
|
-
method: envelope.request.method,
|
|
14
|
-
path: envelope.request.path,
|
|
15
|
-
headers: envelope.request.headers,
|
|
16
|
-
query: envelope.request.query,
|
|
17
|
-
body: envelope.request.body,
|
|
18
|
-
metadata: {
|
|
19
|
-
source: 'sqs',
|
|
20
|
-
id: envelope.id,
|
|
21
|
-
workflow: envelope.workflow,
|
|
22
|
-
timestamp: envelope.timestamp,
|
|
23
|
-
version: envelope.version,
|
|
24
|
-
...envelope.metadata,
|
|
25
|
-
},
|
|
26
|
-
};
|
|
27
|
-
const res = await client.handle(req);
|
|
28
|
-
if (res.status >= 200 && res.status < 300) successes += 1;
|
|
29
|
-
else
|
|
30
|
-
failures.push({
|
|
31
|
-
messageId: record.messageId,
|
|
32
|
-
reason: `Handler returned status ${res.status}`,
|
|
33
|
-
});
|
|
34
|
-
} catch (error) {
|
|
35
|
-
const err = error instanceof Error ? error : new Error(String(error));
|
|
36
|
-
failures.push({ messageId: record.messageId, reason: err.message ?? 'Unknown error' });
|
|
37
|
-
}
|
|
38
|
-
})
|
|
39
|
-
);
|
|
40
|
-
return { successes, failures };
|
|
41
|
-
};
|
|
42
|
-
}
|
|
@@ -1,255 +0,0 @@
|
|
|
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
|
-
} catch {
|
|
9
|
-
return null;
|
|
10
|
-
}
|
|
11
|
-
})();
|
|
12
|
-
function matchPath(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);
|
|
20
|
-
}
|
|
21
|
-
function createEventsClient() {
|
|
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;
|
|
100
|
-
}
|
|
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();
|
|
143
|
-
});
|
|
144
|
-
});
|
|
145
|
-
},
|
|
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) => {
|
|
154
|
-
try {
|
|
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
|
-
});
|
|
177
|
-
}
|
|
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,
|
|
217
|
-
};
|
|
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();
|
|
251
|
-
},
|
|
252
|
-
});
|
|
253
|
-
},
|
|
254
|
-
};
|
|
255
|
-
}
|
|
@@ -1,60 +0,0 @@
|
|
|
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> = (
|
|
16
|
-
request: EventRequest<ReqBody>
|
|
17
|
-
) => Promise<EventResponse<ResBody>> | EventResponse<ResBody>;
|
|
18
|
-
export type RouteMatcher = string | RegExp | ((path: string) => boolean);
|
|
19
|
-
export interface RegisteredRoute {
|
|
20
|
-
method: HttpMethod;
|
|
21
|
-
matcher: RouteMatcher;
|
|
22
|
-
handler: RouteHandler<any, any>;
|
|
23
|
-
}
|
|
24
|
-
export type SqsRecord = {
|
|
25
|
-
messageId: string;
|
|
26
|
-
body: string;
|
|
27
|
-
};
|
|
28
|
-
export interface SqsBatchEvent {
|
|
29
|
-
Records: SqsRecord[];
|
|
30
|
-
}
|
|
31
|
-
export interface EventsClient {
|
|
32
|
-
on: (method: HttpMethod, matcher: RouteMatcher, handler: RouteHandler<any, any>) => void;
|
|
33
|
-
handle: (request: EventRequest<any>) => Promise<EventResponse<any>>;
|
|
34
|
-
get: (matcher: RouteMatcher, handler: RouteHandler<any, any>) => void;
|
|
35
|
-
post: (matcher: RouteMatcher, handler: RouteHandler<any, any>) => void;
|
|
36
|
-
put: (matcher: RouteMatcher, handler: RouteHandler<any, any>) => void;
|
|
37
|
-
patch: (matcher: RouteMatcher, handler: RouteHandler<any, any>) => void;
|
|
38
|
-
delete: (matcher: RouteMatcher, handler: RouteHandler<any, any>) => void;
|
|
39
|
-
options: (matcher: RouteMatcher, handler: RouteHandler<any, any>) => void;
|
|
40
|
-
head: (matcher: RouteMatcher, handler: RouteHandler<any, any>) => void;
|
|
41
|
-
http: (options?: { port?: number }) => Promise<{
|
|
42
|
-
close: () => Promise<void>;
|
|
43
|
-
}>;
|
|
44
|
-
sqs: () => (event: SqsBatchEvent) => Promise<{
|
|
45
|
-
successes: number;
|
|
46
|
-
failures: Array<{
|
|
47
|
-
messageId: string;
|
|
48
|
-
reason: string;
|
|
49
|
-
}>;
|
|
50
|
-
}>;
|
|
51
|
-
sqsListen: (options?: {
|
|
52
|
-
queueUrl?: string;
|
|
53
|
-
region?: string;
|
|
54
|
-
waitTimeSeconds?: number;
|
|
55
|
-
maxMessages?: number;
|
|
56
|
-
visibilityTimeoutSeconds?: number;
|
|
57
|
-
}) => Promise<{
|
|
58
|
-
stop: () => Promise<void>;
|
|
59
|
-
}>;
|
|
60
|
-
}
|
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
import { UnnboundLogger } from 'unnbound-logger-sdk';
|
|
2
|
-
import { EventHandlerResult, EventMetadata, EventSource, IncomingEvent, IncomingRequest } from '../types';
|
|
3
|
-
export type EventHandler = (event: IncomingEvent) => Promise<EventHandlerResult>;
|
|
4
|
-
export interface EventAdapterOptions {
|
|
5
|
-
logger?: UnnboundLogger;
|
|
6
|
-
source: EventSource;
|
|
7
|
-
handler: EventHandler;
|
|
8
|
-
}
|
|
9
|
-
export declare abstract class EventAdapter<E> {
|
|
10
|
-
protected readonly logger: UnnboundLogger;
|
|
11
|
-
protected readonly source: EventSource;
|
|
12
|
-
private readonly handler;
|
|
13
|
-
protected constructor(options: EventAdapterOptions);
|
|
14
|
-
protected abstract parseEvent(event: E): IncomingEvent;
|
|
15
|
-
abstract listen(): () => Promise<void>;
|
|
16
|
-
protected getMetadataFromRequest(request: IncomingRequest): EventMetadata;
|
|
17
|
-
protected normalizeHeaders(headers: Record<string, string | string[]>): Record<string, string>;
|
|
18
|
-
protected handle(event: IncomingEvent): Promise<EventHandlerResult>;
|
|
19
|
-
protected buildIncomingPayload(req: IncomingRequest, res?: EventHandlerResult): {
|
|
20
|
-
type: string;
|
|
21
|
-
source: EventSource;
|
|
22
|
-
http: {
|
|
23
|
-
url: string;
|
|
24
|
-
method: string;
|
|
25
|
-
query: Record<string, any>;
|
|
26
|
-
ip: string | undefined;
|
|
27
|
-
incoming: boolean;
|
|
28
|
-
request: {
|
|
29
|
-
headers: Record<string, string>;
|
|
30
|
-
body: any;
|
|
31
|
-
};
|
|
32
|
-
response: {
|
|
33
|
-
status: import("hono/utils/http-status").StatusCode;
|
|
34
|
-
headers: Record<string, string> | undefined;
|
|
35
|
-
body: any;
|
|
36
|
-
} | undefined;
|
|
37
|
-
};
|
|
38
|
-
};
|
|
39
|
-
protected handleError(error: unknown): EventHandlerResult;
|
|
40
|
-
}
|