@nmtjs/http-transport 0.0.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.
- package/LICENSE.md +7 -0
- package/README.md +1 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -0
- package/dist/lib/providers.js +2 -0
- package/dist/lib/providers.js.map +1 -0
- package/dist/lib/server.js +140 -0
- package/dist/lib/server.js.map +1 -0
- package/dist/lib/transport.js +11 -0
- package/dist/lib/transport.js.map +1 -0
- package/dist/lib/types.js +1 -0
- package/dist/lib/types.js.map +1 -0
- package/dist/lib/utils.js +33 -0
- package/dist/lib/utils.js.map +1 -0
- package/index.ts +5 -0
- package/lib/providers.ts +5 -0
- package/lib/server.ts +215 -0
- package/lib/transport.ts +16 -0
- package/lib/types.ts +17 -0
- package/lib/utils.ts +58 -0
- package/package.json +37 -0
- package/tsconfig.json +3 -0
package/LICENSE.md
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
Copyright (c) 2024 Denis Ilchyshyn
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
4
|
+
|
|
5
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
6
|
+
|
|
7
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
## HTTP transport for [Neemata](https://github.com/neematajs/neemata)
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../index.ts"],"sourcesContent":["export * from './lib/server.ts'\nexport * from './lib/transport.ts'\nexport * from './lib/types.ts'\nexport * from './lib/utils.ts'\nexport * from './lib/providers.ts'\n"],"names":[],"mappings":"AAAA,cAAc,kBAAiB;AAC/B,cAAc,qBAAoB;AAClC,cAAc,iBAAgB;AAC9B,cAAc,iBAAgB;AAC9B,cAAc,qBAAoB"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../lib/providers.ts"],"sourcesContent":["import { providers } from '@nmtjs/application'\nimport type { HttpConnectionData } from './types.ts'\n\nexport const connectionData =\n providers.connectionData.$withType<HttpConnectionData>()\n"],"names":["providers","connectionData","$withType"],"mappings":"AAAA,SAASA,SAAS,QAAQ,qBAAoB;AAG9C,OAAO,MAAMC,iBACXD,UAAUC,cAAc,CAACC,SAAS,GAAsB"}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { ApiError, Scope, providers } from '@nmtjs/application';
|
|
2
|
+
import { TransportType } from '@nmtjs/common';
|
|
3
|
+
import { App, SSLApp } from 'uWebSockets.js';
|
|
4
|
+
import { connectionData } from "./providers.js";
|
|
5
|
+
import { InternalError, getFormat, getRequestData } from "./utils.js";
|
|
6
|
+
export class HttpTransportServer {
|
|
7
|
+
application;
|
|
8
|
+
options;
|
|
9
|
+
server;
|
|
10
|
+
transportType;
|
|
11
|
+
constructor(application, options){
|
|
12
|
+
this.application = application;
|
|
13
|
+
this.options = options;
|
|
14
|
+
this.transportType = TransportType.HTTP;
|
|
15
|
+
this.server = this.options.tls ? SSLApp(options.tls) : App();
|
|
16
|
+
this.server.get('/healthy', (res)=>{
|
|
17
|
+
res.cork(()=>{
|
|
18
|
+
res.writeHeader('Access-Control-Allow-Origin', '*');
|
|
19
|
+
res.writeHeader('Access-Control-Allow-Headers', 'Content-Type');
|
|
20
|
+
res.writeHeader('Access-Control-Allow-Methods', 'GET');
|
|
21
|
+
res.writeHeader('Content-Type', 'text/plain');
|
|
22
|
+
res.end('OK');
|
|
23
|
+
});
|
|
24
|
+
}).post('/api/:service/:procudure', async (res, req)=>{
|
|
25
|
+
const ac = new AbortController();
|
|
26
|
+
res.onAborted(()=>ac.abort());
|
|
27
|
+
const tryEnd = (cb)=>{
|
|
28
|
+
if (!ac.signal.aborted) res.cork(cb);
|
|
29
|
+
};
|
|
30
|
+
try {
|
|
31
|
+
const requestData = getRequestData(req);
|
|
32
|
+
const serviceName = req.getParameter(0);
|
|
33
|
+
const procedureName = req.getParameter(1);
|
|
34
|
+
const service = this.application.registry.services.get(serviceName);
|
|
35
|
+
if (!service) throw new Error(`Service ${serviceName} not found`);
|
|
36
|
+
if (this.transportType in service.contract.transports === false) throw new Error(`Service ${serviceName} not supported`);
|
|
37
|
+
const format = getFormat(requestData, this.application.format);
|
|
38
|
+
const body = await this.getBody(res);
|
|
39
|
+
const container = this.application.container.createScope(Scope.Call);
|
|
40
|
+
const payload = body.byteLength ? format.decoder.decode(body) : null;
|
|
41
|
+
const connection = this.application.connections.add({
|
|
42
|
+
services: [
|
|
43
|
+
serviceName
|
|
44
|
+
],
|
|
45
|
+
type: this.transportType,
|
|
46
|
+
subscriptions: new Map()
|
|
47
|
+
});
|
|
48
|
+
container.provide(connectionData, {
|
|
49
|
+
query: requestData.query,
|
|
50
|
+
headers: requestData.headers,
|
|
51
|
+
proxiedRemoteAddress: Buffer.from(res.getProxiedRemoteAddressAsText()).toString(),
|
|
52
|
+
remoteAddress: Buffer.from(res.getRemoteAddressAsText()).toString()
|
|
53
|
+
});
|
|
54
|
+
container.provide(providers.connection, connection);
|
|
55
|
+
container.provide(providers.signal, ac.signal);
|
|
56
|
+
const { procedure } = this.api.find(serviceName, procedureName, this.transportType);
|
|
57
|
+
try {
|
|
58
|
+
const response = await this.handleRPC({
|
|
59
|
+
connection,
|
|
60
|
+
service,
|
|
61
|
+
procedure,
|
|
62
|
+
container,
|
|
63
|
+
signal: ac.signal,
|
|
64
|
+
payload
|
|
65
|
+
});
|
|
66
|
+
tryEnd(()=>res.writeStatus('200 OK').writeHeader('Content-Type', format.encoder.contentType).end(format.encoder.encode({
|
|
67
|
+
error: null,
|
|
68
|
+
result: response
|
|
69
|
+
})));
|
|
70
|
+
} catch (error) {
|
|
71
|
+
if (error instanceof ApiError) {
|
|
72
|
+
tryEnd(()=>res.writeStatus('200 OK').end(format.encoder.encode({
|
|
73
|
+
error,
|
|
74
|
+
result: null
|
|
75
|
+
})));
|
|
76
|
+
} else {
|
|
77
|
+
tryEnd(()=>res.writeStatus('200 OK').end(format.encoder.encode({
|
|
78
|
+
error: InternalError(),
|
|
79
|
+
result: null
|
|
80
|
+
})));
|
|
81
|
+
}
|
|
82
|
+
this.logError(error);
|
|
83
|
+
} finally{
|
|
84
|
+
this.application.connections.remove(connection);
|
|
85
|
+
this.handleContainerDisposal(container);
|
|
86
|
+
}
|
|
87
|
+
} catch (error) {
|
|
88
|
+
this.logError(error);
|
|
89
|
+
tryEnd(()=>res.writeStatus('500 Internal Server Error').endWithoutBody());
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
async start() {
|
|
94
|
+
return new Promise((resolve, reject)=>{
|
|
95
|
+
const hostname = this.options.hostname ?? '127.0.0.1';
|
|
96
|
+
this.server.listen(hostname, this.options.port, (socket)=>{
|
|
97
|
+
if (socket) {
|
|
98
|
+
this.logger.info('Server started on %s:%s', hostname, this.options.port);
|
|
99
|
+
resolve();
|
|
100
|
+
} else {
|
|
101
|
+
reject(new Error('Failed to start server'));
|
|
102
|
+
}
|
|
103
|
+
});
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
async stop() {
|
|
107
|
+
this.server.close();
|
|
108
|
+
}
|
|
109
|
+
get api() {
|
|
110
|
+
return this.application.api;
|
|
111
|
+
}
|
|
112
|
+
get logger() {
|
|
113
|
+
return this.application.logger;
|
|
114
|
+
}
|
|
115
|
+
async logError(cause, message = 'Unknown error while processing request') {
|
|
116
|
+
this.logger.error(new Error(message, {
|
|
117
|
+
cause
|
|
118
|
+
}));
|
|
119
|
+
}
|
|
120
|
+
handleContainerDisposal(container) {
|
|
121
|
+
container.dispose();
|
|
122
|
+
}
|
|
123
|
+
async handleRPC(options) {
|
|
124
|
+
return await this.api.call({
|
|
125
|
+
...options,
|
|
126
|
+
transport: this.transportType
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
async getBody(res) {
|
|
130
|
+
return new Promise((resolve)=>{
|
|
131
|
+
const chunks = [];
|
|
132
|
+
res.onData((chunk, isLast)=>{
|
|
133
|
+
chunks.push(Buffer.from(chunk));
|
|
134
|
+
if (isLast) {
|
|
135
|
+
resolve(Buffer.concat(chunks));
|
|
136
|
+
}
|
|
137
|
+
});
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../lib/server.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\nimport { once } from 'node:events'\nimport {\n type AnyProcedure,\n ApiError,\n type ApplicationContext,\n type Connection,\n type Container,\n Scope,\n ServerDownStream,\n ServerUpStream,\n type Service,\n SubscriptionResponse,\n onAbort,\n providers,\n} from '@nmtjs/application'\nimport {\n type ApiBlobMetadata,\n type EncodeRpcContext,\n MessageType,\n TransportType,\n decodeNumber,\n encodeNumber,\n} from '@nmtjs/common'\nimport {\n App,\n type HttpResponse,\n SSLApp,\n type TemplatedApp,\n} from 'uWebSockets.js'\nimport { connectionData } from './providers.ts'\nimport type { HttpTransportOptions } from './types.ts'\nimport { InternalError, getFormat, getRequestData } from './utils.ts'\n\nexport class HttpTransportServer {\n protected server!: TemplatedApp\n protected readonly transportType = TransportType.HTTP\n\n constructor(\n protected readonly application: ApplicationContext,\n protected readonly options: HttpTransportOptions,\n ) {\n this.server = this.options.tls ? SSLApp(options.tls!) : App()\n\n this.server\n .get('/healthy', (res) => {\n res.cork(() => {\n // cors\n res.writeHeader('Access-Control-Allow-Origin', '*')\n res.writeHeader('Access-Control-Allow-Headers', 'Content-Type')\n res.writeHeader('Access-Control-Allow-Methods', 'GET')\n res.writeHeader('Content-Type', 'text/plain')\n res.end('OK')\n })\n })\n .post('/api/:service/:procudure', async (res, req) => {\n const ac = new AbortController()\n res.onAborted(() => ac.abort())\n const tryEnd = (cb) => {\n if (!ac.signal.aborted) res.cork(cb)\n }\n\n try {\n const requestData = getRequestData(req)\n\n const serviceName = req.getParameter(0)!\n const procedureName = req.getParameter(1)!\n\n const service = this.application.registry.services.get(serviceName)\n\n if (!service) throw new Error(`Service ${serviceName} not found`)\n if (this.transportType in service.contract.transports === false)\n throw new Error(`Service ${serviceName} not supported`)\n\n const format = getFormat(requestData, this.application.format)\n const body = await this.getBody(res)\n const container = this.application.container.createScope(Scope.Call)\n const payload = body.byteLength ? format.decoder.decode(body) : null\n const connection = this.application.connections.add({\n services: [serviceName],\n type: this.transportType,\n subscriptions: new Map(),\n })\n\n container.provide(connectionData, {\n query: requestData.query,\n headers: requestData.headers,\n proxiedRemoteAddress: Buffer.from(\n res.getProxiedRemoteAddressAsText(),\n ).toString(),\n remoteAddress: Buffer.from(res.getRemoteAddressAsText()).toString(),\n })\n container.provide(providers.connection, connection)\n container.provide(providers.signal, ac.signal)\n\n const { procedure } = this.api.find(\n serviceName,\n procedureName,\n this.transportType,\n )\n\n try {\n const response = await this.handleRPC({\n connection,\n service,\n procedure,\n container,\n signal: ac.signal,\n payload,\n })\n\n tryEnd(() =>\n res\n .writeStatus('200 OK')\n .writeHeader('Content-Type', format.encoder.contentType)\n .end(format.encoder.encode({ error: null, result: response })),\n )\n } catch (error: any) {\n if (error instanceof ApiError) {\n tryEnd(() =>\n res\n .writeStatus('200 OK')\n .end(format.encoder.encode({ error, result: null })),\n )\n } else {\n tryEnd(() =>\n res.writeStatus('200 OK').end(\n format.encoder.encode({\n error: InternalError(),\n result: null,\n }),\n ),\n )\n }\n this.logError(error)\n } finally {\n this.application.connections.remove(connection)\n this.handleContainerDisposal(container)\n }\n } catch (error: any) {\n this.logError(error)\n tryEnd(() =>\n res.writeStatus('500 Internal Server Error').endWithoutBody(),\n )\n }\n })\n }\n\n async start() {\n return new Promise<void>((resolve, reject) => {\n const hostname = this.options.hostname ?? '127.0.0.1'\n this.server.listen(hostname, this.options.port!, (socket) => {\n if (socket) {\n this.logger.info(\n 'Server started on %s:%s',\n hostname,\n this.options.port!,\n )\n resolve()\n } else {\n reject(new Error('Failed to start server'))\n }\n })\n })\n }\n\n async stop() {\n this.server.close()\n }\n\n protected get api() {\n return this.application.api\n }\n\n protected get logger() {\n return this.application.logger\n }\n\n protected async logError(\n cause: Error,\n message = 'Unknown error while processing request',\n ) {\n this.logger.error(new Error(message, { cause }))\n }\n\n protected handleContainerDisposal(container: Container) {\n container.dispose()\n }\n\n protected async handleRPC(options: {\n connection: Connection\n service: Service\n procedure: AnyProcedure\n container: Container\n signal: AbortSignal\n payload: any\n }) {\n return await this.api.call({\n ...options,\n transport: this.transportType,\n })\n }\n\n protected async getBody(res: HttpResponse) {\n return new Promise<Buffer>((resolve) => {\n const chunks: Buffer[] = []\n res.onData((chunk, isLast) => {\n chunks.push(Buffer.from(chunk))\n if (isLast) {\n resolve(Buffer.concat(chunks))\n }\n })\n })\n }\n}\n"],"names":["ApiError","Scope","providers","TransportType","App","SSLApp","connectionData","InternalError","getFormat","getRequestData","HttpTransportServer","server","transportType","constructor","application","options","HTTP","tls","get","res","cork","writeHeader","end","post","req","ac","AbortController","onAborted","abort","tryEnd","cb","signal","aborted","requestData","serviceName","getParameter","procedureName","service","registry","services","Error","contract","transports","format","body","getBody","container","createScope","Call","payload","byteLength","decoder","decode","connection","connections","add","type","subscriptions","Map","provide","query","headers","proxiedRemoteAddress","Buffer","from","getProxiedRemoteAddressAsText","toString","remoteAddress","getRemoteAddressAsText","procedure","api","find","response","handleRPC","writeStatus","encoder","contentType","encode","error","result","logError","remove","handleContainerDisposal","endWithoutBody","start","Promise","resolve","reject","hostname","listen","port","socket","logger","info","stop","close","cause","message","dispose","call","transport","chunks","onData","chunk","isLast","push","concat"],"mappings":"AAEA,SAEEA,QAAQ,EAIRC,KAAK,EAMLC,SAAS,QACJ,qBAAoB;AAC3B,SAIEC,aAAa,QAGR,gBAAe;AACtB,SACEC,GAAG,EAEHC,MAAM,QAED,iBAAgB;AACvB,SAASC,cAAc,QAAQ,iBAAgB;AAE/C,SAASC,aAAa,EAAEC,SAAS,EAAEC,cAAc,QAAQ,aAAY;AAErE,OAAO,MAAMC;;;IACDC,OAAqB;IACZC,cAAkC;IAErDC,YACE,AAAmBC,WAA+B,EAClD,AAAmBC,OAA6B,CAChD;aAFmBD,cAAAA;aACAC,UAAAA;aAJFH,gBAAgBT,cAAca,IAAI;QAMnD,IAAI,CAACL,MAAM,GAAG,IAAI,CAACI,OAAO,CAACE,GAAG,GAAGZ,OAAOU,QAAQE,GAAG,IAAKb;QAExD,IAAI,CAACO,MAAM,CACRO,GAAG,CAAC,YAAY,CAACC;YAChBA,IAAIC,IAAI,CAAC;gBAEPD,IAAIE,WAAW,CAAC,+BAA+B;gBAC/CF,IAAIE,WAAW,CAAC,gCAAgC;gBAChDF,IAAIE,WAAW,CAAC,gCAAgC;gBAChDF,IAAIE,WAAW,CAAC,gBAAgB;gBAChCF,IAAIG,GAAG,CAAC;YACV;QACF,GACCC,IAAI,CAAC,4BAA4B,OAAOJ,KAAKK;YAC5C,MAAMC,KAAK,IAAIC;YACfP,IAAIQ,SAAS,CAAC,IAAMF,GAAGG,KAAK;YAC5B,MAAMC,SAAS,CAACC;gBACd,IAAI,CAACL,GAAGM,MAAM,CAACC,OAAO,EAAEb,IAAIC,IAAI,CAACU;YACnC;YAEA,IAAI;gBACF,MAAMG,cAAcxB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AU,IAAI,CAACzE,OAAO,CAAC2E,IAAI,EAAG,CAACC;gBAChD,IAAIA,QAAQ;oBACV,IAAI,CAACC,MAAM,CAACC,IAAI,CACd,2BACAL,UACA,IAAI,CAACzE,OAAO,CAAC2E,IAAI;oBAEnBJ;gBACF,OAAO;oBACLC,OAAO,IAAI/C,MAAM;gBACnB;YACF;QACF;IACF;IAEA,MAAMsD,OAAO;QACX,IAAI,CAACnF,MAAM,CAACoF,KAAK;IACnB;IAEA,IAAczB,MAAM;QAClB,OAAO,IAAI,CAACxD,WAAW,CAACwD,GAAG;IAC7B;IAEA,IAAcsB,SAAS;QACrB,OAAO,IAAI,CAAC9E,WAAW,CAAC8E,MAAM;IAChC;IAEA,MAAgBZ,SACdgB,KAAY,EACZC,UAAU,wCAAwC,EAClD;QACA,IAAI,CAACL,MAAM,CAACd,KAAK,CAAC,IAAItC,MAAMyD,SAAS;YAAED;QAAM;IAC/C;IAEUd,wBAAwBpC,SAAoB,EAAE;QACtDA,UAAUoD,OAAO;IACnB;IAEA,MAAgBzB,UAAU1D,OAOzB,EAAE;QACD,OAAO,MAAM,IAAI,CAACuD,GAAG,CAAC6B,IAAI,CAAC;YACzB,GAAGpF,OAAO;YACVqF,WAAW,IAAI,CAACxF,aAAa;QAC/B;IACF;IAEA,MAAgBiC,QAAQ1B,GAAiB,EAAE;QACzC,OAAO,IAAIkE,QAAgB,CAACC;YAC1B,MAAMe,SAAmB,EAAE;YAC3BlF,IAAImF,MAAM,CAAC,CAACC,OAAOC;gBACjBH,OAAOI,IAAI,CAAC1C,OAAOC,IAAI,CAACuC;gBACxB,IAAIC,QAAQ;oBACVlB,QAAQvB,OAAO2C,MAAM,CAACL;gBACxB;YACF;QACF;IACF;AACF"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { Hook, createPlugin } from '@nmtjs/application';
|
|
2
|
+
import { HttpTransportServer } from "./server.js";
|
|
3
|
+
export const HttpTransport = createPlugin('HttpTransport', (app, options)=>{
|
|
4
|
+
const server = new HttpTransportServer(app, options);
|
|
5
|
+
app.hooks.add(Hook.OnStartup, async ()=>{
|
|
6
|
+
await server.start();
|
|
7
|
+
});
|
|
8
|
+
app.hooks.add(Hook.OnShutdown, async ()=>{
|
|
9
|
+
await server.stop();
|
|
10
|
+
});
|
|
11
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../lib/transport.ts"],"sourcesContent":["import { Hook, createPlugin } from '@nmtjs/application'\nimport { HttpTransportServer } from './server.ts'\nimport type { HttpTransportOptions } from './types.ts'\n\nexport const HttpTransport = createPlugin<HttpTransportOptions>(\n 'HttpTransport',\n (app, options) => {\n const server = new HttpTransportServer(app, options)\n app.hooks.add(Hook.OnStartup, async () => {\n await server.start()\n })\n app.hooks.add(Hook.OnShutdown, async () => {\n await server.stop()\n })\n },\n)\n"],"names":["Hook","createPlugin","HttpTransportServer","HttpTransport","app","options","server","hooks","add","OnStartup","start","OnShutdown","stop"],"mappings":"AAAA,SAASA,IAAI,EAAEC,YAAY,QAAQ,qBAAoB;AACvD,SAASC,mBAAmB,QAAQ,cAAa;AAGjD,OAAO,MAAMC,gBAAgBF,aAC3B,iBACA,CAACG,KAAKC;IACJ,MAAMC,SAAS,IAAIJ,oBAAoBE,KAAKC;IAC5CD,IAAIG,KAAK,CAACC,GAAG,CAACR,KAAKS,SAAS,EAAE;QAC5B,MAAMH,OAAOI,KAAK;IACpB;IACAN,IAAIG,KAAK,CAACC,GAAG,CAACR,KAAKW,UAAU,EAAE;QAC7B,MAAML,OAAOM,IAAI;IACnB;AACF,GACD"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../lib/types.ts"],"sourcesContent":["import type { AppOptions } from 'uWebSockets.js'\n\nexport type HttpTransportOptions = {\n port?: number\n hostname?: string\n unix?: string\n tls?: AppOptions\n maxPayloadLength?: number\n maxStreamChunkLength?: number\n}\n\nexport type HttpConnectionData = {\n headers: Map<string, string>\n query: URLSearchParams\n remoteAddress: string\n proxiedRemoteAddress: string\n}\n"],"names":[],"mappings":"AAWA,WAKC"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { ApiError } from '@nmtjs/application';
|
|
2
|
+
import { ErrorCode } from '@nmtjs/common';
|
|
3
|
+
export const getFormat = ({ headers, query }, format)=>{
|
|
4
|
+
const contentType = headers.get('content-type') || query.get('content-type');
|
|
5
|
+
const acceptType = headers.get('accept') || query.get('accept');
|
|
6
|
+
const encoder = contentType ? format.supportsEncoder(contentType) : undefined;
|
|
7
|
+
if (!encoder) throw new Error('Unsupported content-type');
|
|
8
|
+
const decoder = acceptType ? format.supportsDecoder(acceptType) : undefined;
|
|
9
|
+
if (!decoder) throw new Error('Unsupported accept');
|
|
10
|
+
return {
|
|
11
|
+
encoder,
|
|
12
|
+
decoder
|
|
13
|
+
};
|
|
14
|
+
};
|
|
15
|
+
export const getRequestData = (req)=>{
|
|
16
|
+
const url = req.getUrl();
|
|
17
|
+
const method = req.getMethod();
|
|
18
|
+
const headers = new Map();
|
|
19
|
+
req.forEach((key, value)=>headers.set(key, value));
|
|
20
|
+
const query = new URLSearchParams(req.getQuery());
|
|
21
|
+
const origin = headers.has('origin') ? new URL(url, headers.get('origin')) : null;
|
|
22
|
+
return {
|
|
23
|
+
url,
|
|
24
|
+
origin,
|
|
25
|
+
method,
|
|
26
|
+
headers,
|
|
27
|
+
query
|
|
28
|
+
};
|
|
29
|
+
};
|
|
30
|
+
export const InternalError = (message = 'Internal Server Error')=>new ApiError(ErrorCode.InternalServerError, message);
|
|
31
|
+
export const NotFoundError = (message = 'Not Found')=>new ApiError(ErrorCode.NotFound, message);
|
|
32
|
+
export const ForbiddenError = (message = 'Forbidden')=>new ApiError(ErrorCode.Forbidden, message);
|
|
33
|
+
export const RequestTimeoutError = (message = 'Request Timeout')=>new ApiError(ErrorCode.RequestTimeout, message);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../lib/utils.ts"],"sourcesContent":["import { ApiError, type Format } from '@nmtjs/application'\nimport { ErrorCode } from '@nmtjs/common'\nimport type { HttpRequest } from 'uWebSockets.js'\n\nexport const getFormat = ({ headers, query }: RequestData, format: Format) => {\n const contentType = headers.get('content-type') || query.get('content-type')\n const acceptType = headers.get('accept') || query.get('accept')\n\n const encoder = contentType ? format.supportsEncoder(contentType) : undefined\n if (!encoder) throw new Error('Unsupported content-type')\n\n const decoder = acceptType ? format.supportsDecoder(acceptType) : undefined\n if (!decoder) throw new Error('Unsupported accept')\n\n return {\n encoder,\n decoder,\n }\n}\n\nexport type RequestData = {\n url: string\n origin: URL | null\n method: string\n headers: Map<string, string>\n query: URLSearchParams\n}\n\nexport const getRequestData = (req: HttpRequest): RequestData => {\n const url = req.getUrl()\n const method = req.getMethod()\n const headers = new Map()\n req.forEach((key, value) => headers.set(key, value))\n const query = new URLSearchParams(req.getQuery())\n const origin = headers.has('origin')\n ? new URL(url, headers.get('origin'))\n : null\n\n return {\n url,\n origin,\n method,\n headers,\n query,\n }\n}\n\nexport const InternalError = (message = 'Internal Server Error') =>\n new ApiError(ErrorCode.InternalServerError, message)\n\nexport const NotFoundError = (message = 'Not Found') =>\n new ApiError(ErrorCode.NotFound, message)\n\nexport const ForbiddenError = (message = 'Forbidden') =>\n new ApiError(ErrorCode.Forbidden, message)\n\nexport const RequestTimeoutError = (message = 'Request Timeout') =>\n new ApiError(ErrorCode.RequestTimeout, message)\n"],"names":["ApiError","ErrorCode","getFormat","headers","query","format","contentType","get","acceptType","encoder","supportsEncoder","undefined","Error","decoder","supportsDecoder","getRequestData","req","url","getUrl","method","getMethod","Map","forEach","key","value","set","URLSearchParams","getQuery","origin","has","URL","InternalError","message","InternalServerError","NotFoundError","NotFound","ForbiddenError","Forbidden","RequestTimeoutError","RequestTimeout"],"mappings":"AAAA,SAASA,QAAQ,QAAqB,qBAAoB;AAC1D,SAASC,SAAS,QAAQ,gBAAe;AAG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AAc,EAAEP,SAAQ"}
|
package/index.ts
ADDED
package/lib/providers.ts
ADDED
package/lib/server.ts
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import { once } from 'node:events'
|
|
3
|
+
import {
|
|
4
|
+
type AnyProcedure,
|
|
5
|
+
ApiError,
|
|
6
|
+
type ApplicationContext,
|
|
7
|
+
type Connection,
|
|
8
|
+
type Container,
|
|
9
|
+
Scope,
|
|
10
|
+
ServerDownStream,
|
|
11
|
+
ServerUpStream,
|
|
12
|
+
type Service,
|
|
13
|
+
SubscriptionResponse,
|
|
14
|
+
onAbort,
|
|
15
|
+
providers,
|
|
16
|
+
} from '@nmtjs/application'
|
|
17
|
+
import {
|
|
18
|
+
type ApiBlobMetadata,
|
|
19
|
+
type EncodeRpcContext,
|
|
20
|
+
MessageType,
|
|
21
|
+
TransportType,
|
|
22
|
+
decodeNumber,
|
|
23
|
+
encodeNumber,
|
|
24
|
+
} from '@nmtjs/common'
|
|
25
|
+
import {
|
|
26
|
+
App,
|
|
27
|
+
type HttpResponse,
|
|
28
|
+
SSLApp,
|
|
29
|
+
type TemplatedApp,
|
|
30
|
+
} from 'uWebSockets.js'
|
|
31
|
+
import { connectionData } from './providers.ts'
|
|
32
|
+
import type { HttpTransportOptions } from './types.ts'
|
|
33
|
+
import { InternalError, getFormat, getRequestData } from './utils.ts'
|
|
34
|
+
|
|
35
|
+
export class HttpTransportServer {
|
|
36
|
+
protected server!: TemplatedApp
|
|
37
|
+
protected readonly transportType = TransportType.HTTP
|
|
38
|
+
|
|
39
|
+
constructor(
|
|
40
|
+
protected readonly application: ApplicationContext,
|
|
41
|
+
protected readonly options: HttpTransportOptions,
|
|
42
|
+
) {
|
|
43
|
+
this.server = this.options.tls ? SSLApp(options.tls!) : App()
|
|
44
|
+
|
|
45
|
+
this.server
|
|
46
|
+
.get('/healthy', (res) => {
|
|
47
|
+
res.cork(() => {
|
|
48
|
+
// cors
|
|
49
|
+
res.writeHeader('Access-Control-Allow-Origin', '*')
|
|
50
|
+
res.writeHeader('Access-Control-Allow-Headers', 'Content-Type')
|
|
51
|
+
res.writeHeader('Access-Control-Allow-Methods', 'GET')
|
|
52
|
+
res.writeHeader('Content-Type', 'text/plain')
|
|
53
|
+
res.end('OK')
|
|
54
|
+
})
|
|
55
|
+
})
|
|
56
|
+
.post('/api/:service/:procudure', async (res, req) => {
|
|
57
|
+
const ac = new AbortController()
|
|
58
|
+
res.onAborted(() => ac.abort())
|
|
59
|
+
const tryEnd = (cb) => {
|
|
60
|
+
if (!ac.signal.aborted) res.cork(cb)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
try {
|
|
64
|
+
const requestData = getRequestData(req)
|
|
65
|
+
|
|
66
|
+
const serviceName = req.getParameter(0)!
|
|
67
|
+
const procedureName = req.getParameter(1)!
|
|
68
|
+
|
|
69
|
+
const service = this.application.registry.services.get(serviceName)
|
|
70
|
+
|
|
71
|
+
if (!service) throw new Error(`Service ${serviceName} not found`)
|
|
72
|
+
if (this.transportType in service.contract.transports === false)
|
|
73
|
+
throw new Error(`Service ${serviceName} not supported`)
|
|
74
|
+
|
|
75
|
+
const format = getFormat(requestData, this.application.format)
|
|
76
|
+
const body = await this.getBody(res)
|
|
77
|
+
const container = this.application.container.createScope(Scope.Call)
|
|
78
|
+
const payload = body.byteLength ? format.decoder.decode(body) : null
|
|
79
|
+
const connection = this.application.connections.add({
|
|
80
|
+
services: [serviceName],
|
|
81
|
+
type: this.transportType,
|
|
82
|
+
subscriptions: new Map(),
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
container.provide(connectionData, {
|
|
86
|
+
query: requestData.query,
|
|
87
|
+
headers: requestData.headers,
|
|
88
|
+
proxiedRemoteAddress: Buffer.from(
|
|
89
|
+
res.getProxiedRemoteAddressAsText(),
|
|
90
|
+
).toString(),
|
|
91
|
+
remoteAddress: Buffer.from(res.getRemoteAddressAsText()).toString(),
|
|
92
|
+
})
|
|
93
|
+
container.provide(providers.connection, connection)
|
|
94
|
+
container.provide(providers.signal, ac.signal)
|
|
95
|
+
|
|
96
|
+
const { procedure } = this.api.find(
|
|
97
|
+
serviceName,
|
|
98
|
+
procedureName,
|
|
99
|
+
this.transportType,
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
try {
|
|
103
|
+
const response = await this.handleRPC({
|
|
104
|
+
connection,
|
|
105
|
+
service,
|
|
106
|
+
procedure,
|
|
107
|
+
container,
|
|
108
|
+
signal: ac.signal,
|
|
109
|
+
payload,
|
|
110
|
+
})
|
|
111
|
+
|
|
112
|
+
tryEnd(() =>
|
|
113
|
+
res
|
|
114
|
+
.writeStatus('200 OK')
|
|
115
|
+
.writeHeader('Content-Type', format.encoder.contentType)
|
|
116
|
+
.end(format.encoder.encode({ error: null, result: response })),
|
|
117
|
+
)
|
|
118
|
+
} catch (error: any) {
|
|
119
|
+
if (error instanceof ApiError) {
|
|
120
|
+
tryEnd(() =>
|
|
121
|
+
res
|
|
122
|
+
.writeStatus('200 OK')
|
|
123
|
+
.end(format.encoder.encode({ error, result: null })),
|
|
124
|
+
)
|
|
125
|
+
} else {
|
|
126
|
+
tryEnd(() =>
|
|
127
|
+
res.writeStatus('200 OK').end(
|
|
128
|
+
format.encoder.encode({
|
|
129
|
+
error: InternalError(),
|
|
130
|
+
result: null,
|
|
131
|
+
}),
|
|
132
|
+
),
|
|
133
|
+
)
|
|
134
|
+
}
|
|
135
|
+
this.logError(error)
|
|
136
|
+
} finally {
|
|
137
|
+
this.application.connections.remove(connection)
|
|
138
|
+
this.handleContainerDisposal(container)
|
|
139
|
+
}
|
|
140
|
+
} catch (error: any) {
|
|
141
|
+
this.logError(error)
|
|
142
|
+
tryEnd(() =>
|
|
143
|
+
res.writeStatus('500 Internal Server Error').endWithoutBody(),
|
|
144
|
+
)
|
|
145
|
+
}
|
|
146
|
+
})
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async start() {
|
|
150
|
+
return new Promise<void>((resolve, reject) => {
|
|
151
|
+
const hostname = this.options.hostname ?? '127.0.0.1'
|
|
152
|
+
this.server.listen(hostname, this.options.port!, (socket) => {
|
|
153
|
+
if (socket) {
|
|
154
|
+
this.logger.info(
|
|
155
|
+
'Server started on %s:%s',
|
|
156
|
+
hostname,
|
|
157
|
+
this.options.port!,
|
|
158
|
+
)
|
|
159
|
+
resolve()
|
|
160
|
+
} else {
|
|
161
|
+
reject(new Error('Failed to start server'))
|
|
162
|
+
}
|
|
163
|
+
})
|
|
164
|
+
})
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async stop() {
|
|
168
|
+
this.server.close()
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
protected get api() {
|
|
172
|
+
return this.application.api
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
protected get logger() {
|
|
176
|
+
return this.application.logger
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
protected async logError(
|
|
180
|
+
cause: Error,
|
|
181
|
+
message = 'Unknown error while processing request',
|
|
182
|
+
) {
|
|
183
|
+
this.logger.error(new Error(message, { cause }))
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
protected handleContainerDisposal(container: Container) {
|
|
187
|
+
container.dispose()
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
protected async handleRPC(options: {
|
|
191
|
+
connection: Connection
|
|
192
|
+
service: Service
|
|
193
|
+
procedure: AnyProcedure
|
|
194
|
+
container: Container
|
|
195
|
+
signal: AbortSignal
|
|
196
|
+
payload: any
|
|
197
|
+
}) {
|
|
198
|
+
return await this.api.call({
|
|
199
|
+
...options,
|
|
200
|
+
transport: this.transportType,
|
|
201
|
+
})
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
protected async getBody(res: HttpResponse) {
|
|
205
|
+
return new Promise<Buffer>((resolve) => {
|
|
206
|
+
const chunks: Buffer[] = []
|
|
207
|
+
res.onData((chunk, isLast) => {
|
|
208
|
+
chunks.push(Buffer.from(chunk))
|
|
209
|
+
if (isLast) {
|
|
210
|
+
resolve(Buffer.concat(chunks))
|
|
211
|
+
}
|
|
212
|
+
})
|
|
213
|
+
})
|
|
214
|
+
}
|
|
215
|
+
}
|
package/lib/transport.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { Hook, createPlugin } from '@nmtjs/application'
|
|
2
|
+
import { HttpTransportServer } from './server.ts'
|
|
3
|
+
import type { HttpTransportOptions } from './types.ts'
|
|
4
|
+
|
|
5
|
+
export const HttpTransport = createPlugin<HttpTransportOptions>(
|
|
6
|
+
'HttpTransport',
|
|
7
|
+
(app, options) => {
|
|
8
|
+
const server = new HttpTransportServer(app, options)
|
|
9
|
+
app.hooks.add(Hook.OnStartup, async () => {
|
|
10
|
+
await server.start()
|
|
11
|
+
})
|
|
12
|
+
app.hooks.add(Hook.OnShutdown, async () => {
|
|
13
|
+
await server.stop()
|
|
14
|
+
})
|
|
15
|
+
},
|
|
16
|
+
)
|
package/lib/types.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { AppOptions } from 'uWebSockets.js'
|
|
2
|
+
|
|
3
|
+
export type HttpTransportOptions = {
|
|
4
|
+
port?: number
|
|
5
|
+
hostname?: string
|
|
6
|
+
unix?: string
|
|
7
|
+
tls?: AppOptions
|
|
8
|
+
maxPayloadLength?: number
|
|
9
|
+
maxStreamChunkLength?: number
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export type HttpConnectionData = {
|
|
13
|
+
headers: Map<string, string>
|
|
14
|
+
query: URLSearchParams
|
|
15
|
+
remoteAddress: string
|
|
16
|
+
proxiedRemoteAddress: string
|
|
17
|
+
}
|
package/lib/utils.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { ApiError, type Format } from '@nmtjs/application'
|
|
2
|
+
import { ErrorCode } from '@nmtjs/common'
|
|
3
|
+
import type { HttpRequest } from 'uWebSockets.js'
|
|
4
|
+
|
|
5
|
+
export const getFormat = ({ headers, query }: RequestData, format: Format) => {
|
|
6
|
+
const contentType = headers.get('content-type') || query.get('content-type')
|
|
7
|
+
const acceptType = headers.get('accept') || query.get('accept')
|
|
8
|
+
|
|
9
|
+
const encoder = contentType ? format.supportsEncoder(contentType) : undefined
|
|
10
|
+
if (!encoder) throw new Error('Unsupported content-type')
|
|
11
|
+
|
|
12
|
+
const decoder = acceptType ? format.supportsDecoder(acceptType) : undefined
|
|
13
|
+
if (!decoder) throw new Error('Unsupported accept')
|
|
14
|
+
|
|
15
|
+
return {
|
|
16
|
+
encoder,
|
|
17
|
+
decoder,
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export type RequestData = {
|
|
22
|
+
url: string
|
|
23
|
+
origin: URL | null
|
|
24
|
+
method: string
|
|
25
|
+
headers: Map<string, string>
|
|
26
|
+
query: URLSearchParams
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const getRequestData = (req: HttpRequest): RequestData => {
|
|
30
|
+
const url = req.getUrl()
|
|
31
|
+
const method = req.getMethod()
|
|
32
|
+
const headers = new Map()
|
|
33
|
+
req.forEach((key, value) => headers.set(key, value))
|
|
34
|
+
const query = new URLSearchParams(req.getQuery())
|
|
35
|
+
const origin = headers.has('origin')
|
|
36
|
+
? new URL(url, headers.get('origin'))
|
|
37
|
+
: null
|
|
38
|
+
|
|
39
|
+
return {
|
|
40
|
+
url,
|
|
41
|
+
origin,
|
|
42
|
+
method,
|
|
43
|
+
headers,
|
|
44
|
+
query,
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export const InternalError = (message = 'Internal Server Error') =>
|
|
49
|
+
new ApiError(ErrorCode.InternalServerError, message)
|
|
50
|
+
|
|
51
|
+
export const NotFoundError = (message = 'Not Found') =>
|
|
52
|
+
new ApiError(ErrorCode.NotFound, message)
|
|
53
|
+
|
|
54
|
+
export const ForbiddenError = (message = 'Forbidden') =>
|
|
55
|
+
new ApiError(ErrorCode.Forbidden, message)
|
|
56
|
+
|
|
57
|
+
export const RequestTimeoutError = (message = 'Request Timeout') =>
|
|
58
|
+
new ApiError(ErrorCode.RequestTimeout, message)
|
package/package.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@nmtjs/http-transport",
|
|
3
|
+
"type": "module",
|
|
4
|
+
"exports": {
|
|
5
|
+
".": {
|
|
6
|
+
"default": "./dist/index.js",
|
|
7
|
+
"types": "./index.ts"
|
|
8
|
+
}
|
|
9
|
+
},
|
|
10
|
+
"dependencies": {
|
|
11
|
+
"uWebSockets.js": "github:uNetworking/uWebSockets.js#v20.47.0"
|
|
12
|
+
},
|
|
13
|
+
"peerDependencies": {
|
|
14
|
+
"@nmtjs/application": "^0.0.1",
|
|
15
|
+
"@nmtjs/common": "^0.0.1"
|
|
16
|
+
},
|
|
17
|
+
"devDependencies": {
|
|
18
|
+
"@nmtjs/application": "^0.0.1",
|
|
19
|
+
"@nmtjs/common": "^0.0.1"
|
|
20
|
+
},
|
|
21
|
+
"engines": {
|
|
22
|
+
"node": ">=18.9.0"
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"index.ts",
|
|
26
|
+
"lib",
|
|
27
|
+
"dist",
|
|
28
|
+
"tsconfig.json",
|
|
29
|
+
"LICENSE.md",
|
|
30
|
+
"README.md"
|
|
31
|
+
],
|
|
32
|
+
"version": "0.0.1",
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "neemata-build ./index.ts './lib/**/*.ts'",
|
|
35
|
+
"type-check": "tsc --noEmit"
|
|
36
|
+
}
|
|
37
|
+
}
|
package/tsconfig.json
ADDED