@grest-ts/http 0.0.5 → 0.0.7

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,99 +1,99 @@
1
- import type http from "http";
2
- import {GGHttpCodec, GGHttpSchema} from "./GGHttpSchema";
3
- import {GGHttpRequest, GGHttpTransportMiddleware} from "./GGHttpSchema";
4
- import {GGContractApiDefinition, GGContractClass} from "@grest-ts/schema";
5
- import {GGContextKey} from "@grest-ts/context";
6
-
7
- /**
8
- * Create an HTTP API schema builder from a contract.
9
- *
10
- * @example
11
- * export const MyApiContract = defineApi("MyApi", () => ({
12
- * list: {
13
- * success: IsArray(IsItem),
14
- * errors: [NOT_AUTHORIZED, SERVER_ERROR]
15
- * },
16
- * create: {
17
- * input: IsCreateRequest,
18
- * success: IsItem,
19
- * errors: [NOT_AUTHORIZED, VALIDATION_ERROR, SERVER_ERROR]
20
- * }
21
- * }))
22
- *
23
- * export const MyApi = httpApi(MyApiContract)
24
- * .pathPrefix("api/items")
25
- * .use(AuthMiddleware)
26
- * .routes({
27
- * list: GGRpc.GET("list"),
28
- * create: GGRpc.POST("create")
29
- * })
30
- */
31
- export function httpSchema<TContract extends GGContractApiDefinition>(
32
- contract: GGContractClass<TContract>
33
- ): GGHttpSchemaBuilder<TContract> {
34
- return new GGHttpSchemaBuilder(contract)
35
- }
36
-
37
- class GGHttpSchemaBuilder<TContract extends GGContractApiDefinition, TContext = undefined> {
38
-
39
- private readonly _contract: GGContractClass<TContract>
40
- private _pathPrefix: string = ""
41
- private _middlewares: GGHttpTransportMiddleware[] = []
42
-
43
- constructor(contract: GGContractClass<TContract>) {
44
- this._contract = contract;
45
- }
46
-
47
- pathPrefix(prefix: string): this {
48
- this._pathPrefix = prefix
49
- return this
50
- }
51
-
52
- use<M extends GGHttpTransportMiddleware>(middleware: M): GGHttpSchemaBuilder<TContract, TContext | M> {
53
- this._middlewares.push(middleware)
54
- return this as unknown as GGHttpSchemaBuilder<TContract, TContext | M>
55
- }
56
-
57
- useHeader<Input>(contextKey: GGContextKey<Input>): GGHttpSchemaBuilder<TContract, TContext | Input> {
58
- const codec = contextKey.getCodec("http");
59
- if (!codec) {
60
- throw new Error(`Context key '${contextKey.name}' does not have an 'http-header' codec registered.`);
61
- }
62
-
63
- const middleware: GGHttpTransportMiddleware = {
64
- updateRequest(req: GGHttpRequest) {
65
- // Client-side: context -> headers
66
- const contextValue = contextKey.get();
67
- if (contextValue !== undefined) {
68
- const result = codec.decode(contextValue);
69
- if (result.success) {
70
- Object.assign(req.headers, result.value);
71
- }
72
- } else {
73
- // Clear any default headers by decoding an empty context
74
- const emptyResult = codec.decode({} as Input);
75
- if (emptyResult.success) {
76
- for (const key of Object.keys(emptyResult.value as object)) {
77
- delete req.headers[key];
78
- }
79
- }
80
- }
81
- },
82
- parseRequest(req: http.IncomingMessage) {
83
- // Server-side: headers -> context
84
- const headers = req.headers as Record<string, string>;
85
- const result = codec.encode(headers);
86
- if (result.success) {
87
- contextKey.set(result.value);
88
- }
89
- }
90
- };
91
-
92
- this._middlewares.push(middleware);
93
- return this as unknown as GGHttpSchemaBuilder<TContract, TContext | Input>;
94
- }
95
-
96
- routes(mapping: { [K in keyof TContract]: GGHttpCodec }): GGHttpSchema<TContract, TContext> {
97
- return new GGHttpSchema(this._pathPrefix, this._contract, mapping, this._middlewares)
98
- }
99
- }
1
+ import type http from "http";
2
+ import {GGHttpCodec, GGHttpSchema} from "./GGHttpSchema";
3
+ import {GGHttpRequest, GGHttpTransportMiddleware} from "./GGHttpSchema";
4
+ import {GGContractApiDefinition, GGContractClass} from "@grest-ts/schema";
5
+ import {GGContextKey} from "@grest-ts/context";
6
+
7
+ /**
8
+ * Create an HTTP API schema builder from a contract.
9
+ *
10
+ * @example
11
+ * export const MyApiContract = defineApi("MyApi", () => ({
12
+ * list: {
13
+ * success: IsArray(IsItem),
14
+ * errors: [NOT_AUTHORIZED, SERVER_ERROR]
15
+ * },
16
+ * create: {
17
+ * input: IsCreateRequest,
18
+ * success: IsItem,
19
+ * errors: [NOT_AUTHORIZED, VALIDATION_ERROR, SERVER_ERROR]
20
+ * }
21
+ * }))
22
+ *
23
+ * export const MyApi = httpApi(MyApiContract)
24
+ * .pathPrefix("api/items")
25
+ * .use(AuthMiddleware)
26
+ * .routes({
27
+ * list: GGRpc.GET("list"),
28
+ * create: GGRpc.POST("create")
29
+ * })
30
+ */
31
+ export function httpSchema<TContract extends GGContractApiDefinition>(
32
+ contract: GGContractClass<TContract>
33
+ ): GGHttpSchemaBuilder<TContract> {
34
+ return new GGHttpSchemaBuilder(contract)
35
+ }
36
+
37
+ class GGHttpSchemaBuilder<TContract extends GGContractApiDefinition, TContext = undefined> {
38
+
39
+ private readonly _contract: GGContractClass<TContract>
40
+ private _pathPrefix: string = ""
41
+ private _middlewares: GGHttpTransportMiddleware[] = []
42
+
43
+ constructor(contract: GGContractClass<TContract>) {
44
+ this._contract = contract;
45
+ }
46
+
47
+ pathPrefix(prefix: string): this {
48
+ this._pathPrefix = prefix
49
+ return this
50
+ }
51
+
52
+ use<M extends GGHttpTransportMiddleware>(middleware: M): GGHttpSchemaBuilder<TContract, TContext | M> {
53
+ this._middlewares.push(middleware)
54
+ return this as unknown as GGHttpSchemaBuilder<TContract, TContext | M>
55
+ }
56
+
57
+ useHeader<Input>(contextKey: GGContextKey<Input>): GGHttpSchemaBuilder<TContract, TContext | Input> {
58
+ const codec = contextKey.getCodec("http");
59
+ if (!codec) {
60
+ throw new Error(`Context key '${contextKey.name}' does not have an 'http-header' codec registered.`);
61
+ }
62
+
63
+ const middleware: GGHttpTransportMiddleware = {
64
+ updateRequest(req: GGHttpRequest) {
65
+ // Client-side: context -> headers
66
+ const contextValue = contextKey.get();
67
+ if (contextValue !== undefined) {
68
+ const result = codec.decode(contextValue);
69
+ if (result.success) {
70
+ Object.assign(req.headers, result.value);
71
+ }
72
+ } else {
73
+ // Clear any default headers by decoding an empty context
74
+ const emptyResult = codec.decode({} as Input);
75
+ if (emptyResult.success) {
76
+ for (const key of Object.keys(emptyResult.value as object)) {
77
+ delete req.headers[key];
78
+ }
79
+ }
80
+ }
81
+ },
82
+ parseRequest(req: http.IncomingMessage) {
83
+ // Server-side: headers -> context
84
+ const headers = req.headers as Record<string, string>;
85
+ const result = codec.encode(headers);
86
+ if (result.success) {
87
+ contextKey.set(result.value);
88
+ }
89
+ }
90
+ };
91
+
92
+ this._middlewares.push(middleware);
93
+ return this as unknown as GGHttpSchemaBuilder<TContract, TContext | Input>;
94
+ }
95
+
96
+ routes(mapping: { [K in keyof TContract]: GGHttpCodec }): GGHttpSchema<TContract, TContext> {
97
+ return new GGHttpSchema(this._pathPrefix, this._contract, mapping, this._middlewares)
98
+ }
99
+ }
@@ -1,27 +1,27 @@
1
- import {GGHttpSchema} from "../schema/GGHttpSchema";
2
- import {GGContractApiDefinition, GGContractImplementation} from "@grest-ts/schema";
3
- import {GGHttpServerMiddleware} from "./GGHttpSchema.startServer";
4
- import {GGHttpServer} from "./GGHttpServer";
5
-
6
- export class GGHttp<TContext = undefined> {
7
-
8
- private readonly httpServer: GGHttpServer
9
- private readonly middlewares: GGHttpServerMiddleware[] = [];
10
-
11
- constructor(httpServer: GGHttpServer) {
12
- this.httpServer = httpServer;
13
- }
14
-
15
- public use<M extends GGHttpServerMiddleware>(middleware: M): GGHttp<TContext | M> {
16
- this.middlewares.push(middleware);
17
- return this as any;
18
- }
19
-
20
- public http<TContract extends GGContractApiDefinition, TSchemaContext>(
21
- schema: GGHttpSchema<TContract, TSchemaContext>,
22
- implementation: GGContractImplementation<TContract>
23
- ): this {
24
- schema.register(implementation, {http: this.httpServer, middlewares: this.middlewares});
25
- return this as any;
26
- }
27
- }
1
+ import {GGHttpSchema} from "../schema/GGHttpSchema";
2
+ import {GGContractApiDefinition, GGContractImplementation} from "@grest-ts/schema";
3
+ import {GGHttpServerMiddleware} from "./GGHttpSchema.startServer";
4
+ import {GGHttpServer} from "./GGHttpServer";
5
+
6
+ export class GGHttp<TContext = undefined> {
7
+
8
+ private readonly httpServer: GGHttpServer
9
+ private readonly middlewares: GGHttpServerMiddleware[] = [];
10
+
11
+ constructor(httpServer: GGHttpServer) {
12
+ this.httpServer = httpServer;
13
+ }
14
+
15
+ public use<M extends GGHttpServerMiddleware>(middleware: M): GGHttp<TContext | M> {
16
+ this.middlewares.push(middleware);
17
+ return this as any;
18
+ }
19
+
20
+ public http<TContract extends GGContractApiDefinition, TSchemaContext>(
21
+ schema: GGHttpSchema<TContract, TSchemaContext>,
22
+ implementation: GGContractImplementation<TContract>
23
+ ): this {
24
+ schema.register(implementation, {http: this.httpServer, middlewares: this.middlewares});
25
+ return this as any;
26
+ }
27
+ }
@@ -1,31 +1,31 @@
1
- import {GGCounterKey, GGHistogramKey, GGMetrics} from "@grest-ts/metrics";
2
- import {EXISTS, FORBIDDEN, NOT_AUTHORIZED, NOT_FOUND, OK, ROUTE_NOT_FOUND, SERVER_ERROR, VALIDATION_ERROR} from "@grest-ts/schema";
3
-
4
- /**
5
- * Result type for HTTP operations.
6
- * Known types listed for documentation, but accepts any string for custom error types.
7
- */
8
- type ResultType =
9
- | typeof OK.TYPE
10
- | typeof VALIDATION_ERROR.TYPE
11
- | typeof NOT_AUTHORIZED.TYPE
12
- | typeof FORBIDDEN.TYPE
13
- | typeof NOT_FOUND.TYPE
14
- | typeof ROUTE_NOT_FOUND.TYPE
15
- | typeof EXISTS.TYPE
16
- | typeof SERVER_ERROR.TYPE
17
- | string;
18
-
19
- export const GGHttpMetrics = GGMetrics.define('/http/', () => ({
20
- requests: new GGCounterKey<{ api: string, method: string, path: string, result: ResultType }>('requests_total', {
21
- help: 'Total HTTP requests after contract validation',
22
- labelNames: ['api', 'method', 'path', 'result'],
23
- groupBy: {labels: ["api", "method"], template: "{api}.{method}"}
24
- }),
25
- requestDuration: new GGHistogramKey<{ api: string, method: string, path: string }>('request_duration_ms', {
26
- help: 'HTTP request duration in milliseconds',
27
- labelNames: ['api', 'method', 'path'],
28
- buckets: [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000],
29
- groupBy: {labels: ["api", "method"], template: "{api}.{method}"}
30
- }),
31
- }));
1
+ import {GGCounterKey, GGHistogramKey, GGMetrics} from "@grest-ts/metrics";
2
+ import {EXISTS, FORBIDDEN, NOT_AUTHORIZED, NOT_FOUND, OK, ROUTE_NOT_FOUND, SERVER_ERROR, VALIDATION_ERROR} from "@grest-ts/schema";
3
+
4
+ /**
5
+ * Result type for HTTP operations.
6
+ * Known types listed for documentation, but accepts any string for custom error types.
7
+ */
8
+ type ResultType =
9
+ | typeof OK.TYPE
10
+ | typeof VALIDATION_ERROR.TYPE
11
+ | typeof NOT_AUTHORIZED.TYPE
12
+ | typeof FORBIDDEN.TYPE
13
+ | typeof NOT_FOUND.TYPE
14
+ | typeof ROUTE_NOT_FOUND.TYPE
15
+ | typeof EXISTS.TYPE
16
+ | typeof SERVER_ERROR.TYPE
17
+ | string;
18
+
19
+ export const GGHttpMetrics = GGMetrics.define('/http/', () => ({
20
+ requests: new GGCounterKey<{ api: string, method: string, path: string, result: ResultType }>('requests_total', {
21
+ help: 'Total HTTP requests after contract validation',
22
+ labelNames: ['api', 'method', 'path', 'result'],
23
+ groupBy: {labels: ["api", "method"], template: "{api}.{method}"}
24
+ }),
25
+ requestDuration: new GGHistogramKey<{ api: string, method: string, path: string }>('request_duration_ms', {
26
+ help: 'HTTP request duration in milliseconds',
27
+ labelNames: ['api', 'method', 'path'],
28
+ buckets: [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000],
29
+ groupBy: {labels: ["api", "method"], template: "{api}.{method}"}
30
+ }),
31
+ }));
@@ -1,161 +1,161 @@
1
- /**
2
- * Server extension for HttpApiSchema - adds register method.
3
- * This file should only be imported in server (Node.js) context.
4
- */
5
-
6
- import http from "http";
7
- import {GGLocator} from "@grest-ts/locator";
8
- import {ClientHttpRouteToRpcTransformServerCodec, GGHttpCodec, GGHttpSchema} from "../schema/GGHttpSchema";
9
- import {ERROR, GGContractApiDefinition, GGContractImplementation, GGContractMethod, OK, SERVER_ERROR} from "@grest-ts/schema";
10
- import {HttpMethod} from "@grest-ts/common";
11
- import {GG_DISCOVERY} from "@grest-ts/discovery";
12
- import {GGContext, GGContextStore} from "@grest-ts/context";
13
- import {GG_TRACE} from "@grest-ts/trace";
14
- import {GG_HTTP_REQUEST} from "./GG_HTTP_REQUEST";
15
- import {GG_METRICS} from "@grest-ts/metrics";
16
- import {GGHttpMetrics} from "./GGHttpMetrics";
17
- import {GG_HTTP_SERVER} from "./GG_HTTP_SERVER";
18
- import {GGHttpServer} from "./GGHttpServer";
19
- import {GGLog} from "@grest-ts/logger";
20
-
21
- export interface GGHttpSchemaConfig {
22
- /**
23
- * The HTTP request handler to register with.
24
- */
25
- http?: GGHttpServer;
26
- /**
27
- * Additional middlewares to apply to all routes.
28
- */
29
- middlewares?: GGHttpServerMiddleware[];
30
- }
31
-
32
- export interface GGHttpServerMiddleware {
33
- process?(): Promise<void>
34
- }
35
-
36
- declare module "../schema/GGHttpSchema" {
37
- interface GGHttpSchema<TContract extends GGContractApiDefinition> {
38
- /**
39
- * Start server with direct implementation.
40
- * Uses parseRequest from use classes without transform.
41
- * For custom transforms, use createServer() instead.
42
- */
43
- register(implementation: GGContractImplementation<TContract>, config?: GGHttpSchemaConfig): void
44
- }
45
- }
46
-
47
- GGHttpSchema.prototype.register = function <TContract extends GGContractApiDefinition>(
48
- this: GGHttpSchema<TContract>,
49
- implementation: GGContractImplementation<TContract>,
50
- config?: GGHttpSchemaConfig
51
- ) {
52
- return setupRoutes(this, implementation, config)
53
- }
54
-
55
- function setupRoutes<TContract extends GGContractApiDefinition>(
56
- httpSchema: GGHttpSchema<TContract>,
57
- implementation: GGContractImplementation<TContract>,
58
- config?: GGHttpSchemaConfig
59
- ) {
60
- config ??= {};
61
- config.middlewares ??= [];
62
-
63
- if (!httpSchema.contract) throw new Error(`HttpApiSchema "${httpSchema.name}" has no contract.`);
64
-
65
- const server = config.http ?? GGLocator.getScope().get(GG_HTTP_SERVER);
66
- if (!server) throw new Error(`No HTTP server found. Make sure to register GGHttpServerAdapter in the scope or pass handler via config`)
67
-
68
- const pathPrefix = "/" + httpSchema.pathPrefix + "/"
69
- const apiMiddlewares = httpSchema.apiMiddlewares;
70
- const scope = GGLocator.getScope();
71
- const parentContext = GGContextStore.tryGetContext();
72
-
73
- server.onStart(() => {
74
- GG_DISCOVERY.tryGet()?.registerRoutes([{
75
- runtime: scope.serviceName,
76
- api: httpSchema.name,
77
- pathPrefix: pathPrefix,
78
- protocol: "http",
79
- port: server.port
80
- }]);
81
- })
82
-
83
- // Info: Contract instance is auto-registered in GGLocator via patched implement()
84
- // @TODO This is not really used and only for testkit so it would register implementation of the contract... Not cool
85
- httpSchema.contract.implement(implementation);
86
-
87
- for (const methodName in httpSchema.codec) {
88
- // Wire format.
89
- const codec: GGHttpCodec = httpSchema.codec[methodName]
90
- if (!codec) throw new Error(`Contract for "${httpSchema.name}.${methodName}" is missing wire format!`)
91
-
92
- // Implementation function
93
- const implFn = implementation[methodName]?.bind(implementation)
94
- if (!implFn) throw new Error(`Implementation for "${httpSchema.name}.${methodName}" is missing implementation method!`)
95
-
96
- // Input schema
97
- const contractFunctionSchema: GGContractMethod = httpSchema.contract.methods[methodName as keyof TContract]
98
- if (!contractFunctionSchema) throw new Error(`Contract for "${httpSchema.name}.${methodName}" is missing contract function schema!`)
99
-
100
- // build request mapping
101
- const requestParser: ClientHttpRouteToRpcTransformServerCodec = codec.createForServer({
102
- contract: contractFunctionSchema,
103
- apiMiddlewares: apiMiddlewares,
104
- serverMiddlewares: config.middlewares
105
- })
106
- server.registerRoute(codec.method, pathPrefix + codec.path, async (req: http.IncomingMessage, res: http.ServerResponse): Promise<void> => {
107
- scope.ensureEntered();
108
- return new GGContext("REQ", parentContext).run(async () => {
109
- GG_TRACE.init();
110
- GG_HTTP_REQUEST.set({port: server.port, method: req.method, path: req.url});
111
- const startTime = performance.now()
112
- let rpcResult: ERROR<string, unknown> | OK<unknown>
113
- try {
114
- const rpcInput = await requestParser.parseRequest(req)
115
- try {
116
- rpcResult = {success: true, type: "OK", data: await implFn(rpcInput)}
117
- // GGLog.debug(httpSchema, "Response", rpcResult) // This is very slow to log this (like 3x performance loss)
118
- } catch (error: unknown) {
119
- rpcResult = ERROR.fromUnknown(error);
120
- if (rpcResult instanceof SERVER_ERROR) {
121
- GGLog.error(httpSchema, rpcResult)
122
- } else {
123
- // GGLog.debug(httpSchema, "Response", rpcResult) // This is very slow to log this (like 3x performance loss)
124
- }
125
- }
126
- await requestParser.sendResponse(res, rpcResult) // can throw
127
- } catch (error: unknown) {
128
- rpcResult = ERROR.fromUnknown(error)
129
- await requestParser.sendResponse(res, rpcResult) // Does not throw
130
- GGLog.error(httpSchema, rpcResult)
131
- } finally {
132
- metrics(rpcResult?.type, httpSchema.name, codec.method, pathPrefix, codec.path, startTime)
133
- }
134
- });
135
- })
136
- }
137
- }
138
-
139
- function metrics(
140
- resultType: string,
141
- apiName: string,
142
- method: HttpMethod,
143
- pathPrefix: string,
144
- pathSuffix: string,
145
- startTime: number
146
- ) {
147
- if (GG_METRICS.has()) {
148
- const path = method + " " + pathPrefix + pathSuffix;
149
- GGHttpMetrics.requests.inc(1, {
150
- api: apiName,
151
- method: pathSuffix,
152
- path: path,
153
- result: resultType
154
- });
155
- GGHttpMetrics.requestDuration.observe(performance.now() - startTime, {
156
- api: apiName,
157
- method: pathSuffix,
158
- path: path
159
- });
160
- }
161
- }
1
+ /**
2
+ * Server extension for HttpApiSchema - adds register method.
3
+ * This file should only be imported in server (Node.js) context.
4
+ */
5
+
6
+ import http from "http";
7
+ import {GGLocator} from "@grest-ts/locator";
8
+ import {ClientHttpRouteToRpcTransformServerCodec, GGHttpCodec, GGHttpSchema} from "../schema/GGHttpSchema";
9
+ import {ERROR, GGContractApiDefinition, GGContractImplementation, GGContractMethod, OK, SERVER_ERROR} from "@grest-ts/schema";
10
+ import {HttpMethod} from "@grest-ts/common";
11
+ import {GG_DISCOVERY} from "@grest-ts/discovery";
12
+ import {GGContext, GGContextStore} from "@grest-ts/context";
13
+ import {GG_TRACE} from "@grest-ts/trace";
14
+ import {GG_HTTP_REQUEST} from "./GG_HTTP_REQUEST";
15
+ import {GG_METRICS} from "@grest-ts/metrics";
16
+ import {GGHttpMetrics} from "./GGHttpMetrics";
17
+ import {GG_HTTP_SERVER} from "./GG_HTTP_SERVER";
18
+ import {GGHttpServer} from "./GGHttpServer";
19
+ import {GGLog} from "@grest-ts/logger";
20
+
21
+ export interface GGHttpSchemaConfig {
22
+ /**
23
+ * The HTTP request handler to register with.
24
+ */
25
+ http?: GGHttpServer;
26
+ /**
27
+ * Additional middlewares to apply to all routes.
28
+ */
29
+ middlewares?: GGHttpServerMiddleware[];
30
+ }
31
+
32
+ export interface GGHttpServerMiddleware {
33
+ process?(): Promise<void>
34
+ }
35
+
36
+ declare module "../schema/GGHttpSchema" {
37
+ interface GGHttpSchema<TContract extends GGContractApiDefinition> {
38
+ /**
39
+ * Start server with direct implementation.
40
+ * Uses parseRequest from use classes without transform.
41
+ * For custom transforms, use createServer() instead.
42
+ */
43
+ register(implementation: GGContractImplementation<TContract>, config?: GGHttpSchemaConfig): void
44
+ }
45
+ }
46
+
47
+ GGHttpSchema.prototype.register = function <TContract extends GGContractApiDefinition>(
48
+ this: GGHttpSchema<TContract>,
49
+ implementation: GGContractImplementation<TContract>,
50
+ config?: GGHttpSchemaConfig
51
+ ) {
52
+ return setupRoutes(this, implementation, config)
53
+ }
54
+
55
+ function setupRoutes<TContract extends GGContractApiDefinition>(
56
+ httpSchema: GGHttpSchema<TContract>,
57
+ implementation: GGContractImplementation<TContract>,
58
+ config?: GGHttpSchemaConfig
59
+ ) {
60
+ config ??= {};
61
+ config.middlewares ??= [];
62
+
63
+ if (!httpSchema.contract) throw new Error(`HttpApiSchema "${httpSchema.name}" has no contract.`);
64
+
65
+ const server = config.http ?? GGLocator.getScope().get(GG_HTTP_SERVER);
66
+ if (!server) throw new Error(`No HTTP server found. Make sure to register GGHttpServerAdapter in the scope or pass handler via config`)
67
+
68
+ const pathPrefix = "/" + httpSchema.pathPrefix + "/"
69
+ const apiMiddlewares = httpSchema.apiMiddlewares;
70
+ const scope = GGLocator.getScope();
71
+ const parentContext = GGContextStore.tryGetContext();
72
+
73
+ server.onStart(() => {
74
+ GG_DISCOVERY.tryGet()?.registerRoutes([{
75
+ runtime: scope.serviceName,
76
+ api: httpSchema.name,
77
+ pathPrefix: pathPrefix,
78
+ protocol: "http",
79
+ port: server.port
80
+ }]);
81
+ })
82
+
83
+ // Info: Contract instance is auto-registered in GGLocator via patched implement()
84
+ // @TODO This is not really used and only for testkit so it would register implementation of the contract... Not cool
85
+ httpSchema.contract.implement(implementation);
86
+
87
+ for (const methodName in httpSchema.codec) {
88
+ // Wire format.
89
+ const codec: GGHttpCodec = httpSchema.codec[methodName]
90
+ if (!codec) throw new Error(`Contract for "${httpSchema.name}.${methodName}" is missing wire format!`)
91
+
92
+ // Implementation function
93
+ const implFn = implementation[methodName]?.bind(implementation)
94
+ if (!implFn) throw new Error(`Implementation for "${httpSchema.name}.${methodName}" is missing implementation method!`)
95
+
96
+ // Input schema
97
+ const contractFunctionSchema: GGContractMethod = httpSchema.contract.methods[methodName as keyof TContract]
98
+ if (!contractFunctionSchema) throw new Error(`Contract for "${httpSchema.name}.${methodName}" is missing contract function schema!`)
99
+
100
+ // build request mapping
101
+ const requestParser: ClientHttpRouteToRpcTransformServerCodec = codec.createForServer({
102
+ contract: contractFunctionSchema,
103
+ apiMiddlewares: apiMiddlewares,
104
+ serverMiddlewares: config.middlewares
105
+ })
106
+ server.registerRoute(codec.method, pathPrefix + codec.path, async (req: http.IncomingMessage, res: http.ServerResponse): Promise<void> => {
107
+ scope.ensureEntered();
108
+ return new GGContext("REQ", parentContext).run(async () => {
109
+ GG_TRACE.init();
110
+ GG_HTTP_REQUEST.set({port: server.port, method: req.method, path: req.url});
111
+ const startTime = performance.now()
112
+ let rpcResult: ERROR<string, unknown> | OK<unknown>
113
+ try {
114
+ const rpcInput = await requestParser.parseRequest(req)
115
+ try {
116
+ rpcResult = {success: true, type: "OK", data: await implFn(rpcInput)}
117
+ // GGLog.debug(httpSchema, "Response", rpcResult) // This is very slow to log this (like 3x performance loss)
118
+ } catch (error: unknown) {
119
+ rpcResult = ERROR.fromUnknown(error);
120
+ if (rpcResult instanceof SERVER_ERROR) {
121
+ GGLog.error(httpSchema, rpcResult)
122
+ } else {
123
+ // GGLog.debug(httpSchema, "Response", rpcResult) // This is very slow to log this (like 3x performance loss)
124
+ }
125
+ }
126
+ await requestParser.sendResponse(res, rpcResult) // can throw
127
+ } catch (error: unknown) {
128
+ rpcResult = ERROR.fromUnknown(error)
129
+ await requestParser.sendResponse(res, rpcResult) // Does not throw
130
+ GGLog.error(httpSchema, rpcResult)
131
+ } finally {
132
+ metrics(rpcResult?.type, httpSchema.name, codec.method, pathPrefix, codec.path, startTime)
133
+ }
134
+ });
135
+ })
136
+ }
137
+ }
138
+
139
+ function metrics(
140
+ resultType: string,
141
+ apiName: string,
142
+ method: HttpMethod,
143
+ pathPrefix: string,
144
+ pathSuffix: string,
145
+ startTime: number
146
+ ) {
147
+ if (GG_METRICS.has()) {
148
+ const path = method + " " + pathPrefix + pathSuffix;
149
+ GGHttpMetrics.requests.inc(1, {
150
+ api: apiName,
151
+ method: pathSuffix,
152
+ path: path,
153
+ result: resultType
154
+ });
155
+ GGHttpMetrics.requestDuration.observe(performance.now() - startTime, {
156
+ api: apiName,
157
+ method: pathSuffix,
158
+ path: path
159
+ });
160
+ }
161
+ }