@macss/modular-api 0.4.6 → 0.4.8
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/README.md +70 -8
- package/dist/core/logger/logger.d.ts +1 -0
- package/dist/core/logger/logger.js +1 -0
- package/dist/core/logger/logging_middleware.js +11 -0
- package/dist/core/modular_api.d.ts +8 -0
- package/dist/core/modular_api.js +99 -42
- package/dist/core/official_plugins.d.ts +35 -0
- package/dist/core/official_plugins.js +213 -0
- package/dist/core/plugin.d.ts +163 -0
- package/dist/core/plugin.js +304 -0
- package/dist/core/request_pipeline_audit.d.ts +15 -0
- package/dist/core/request_pipeline_audit.js +29 -0
- package/dist/core/unhandled_request_error_handler.d.ts +2 -0
- package/dist/core/unhandled_request_error_handler.js +17 -0
- package/dist/graphql/catalog/graphql_catalog_builder.d.ts +149 -0
- package/dist/graphql/catalog/graphql_catalog_builder.js +564 -0
- package/dist/graphql/metadata/graphql_metadata_parser.d.ts +53 -0
- package/dist/graphql/metadata/graphql_metadata_parser.js +373 -0
- package/dist/graphql/read/sql_read_contract.d.ts +155 -0
- package/dist/graphql/read/sql_read_contract.js +194 -0
- package/dist/graphql/read/sqlserver_read_compiler.d.ts +58 -0
- package/dist/graphql/read/sqlserver_read_compiler.js +279 -0
- package/dist/graphql/runtime/graphql_artifacts.d.ts +43 -0
- package/dist/graphql/runtime/graphql_artifacts.js +512 -0
- package/dist/graphql/runtime/graphql_runtime_options.d.ts +52 -0
- package/dist/graphql/runtime/graphql_runtime_options.js +60 -0
- package/dist/graphql/runtime/graphql_runtime_plugin.d.ts +18 -0
- package/dist/graphql/runtime/graphql_runtime_plugin.js +946 -0
- package/dist/graphql/schema/graphql_schema_sdl_generator.d.ts +17 -0
- package/dist/graphql/schema/graphql_schema_sdl_generator.js +221 -0
- package/dist/graphql/sqlserver/physical_model.d.ts +28 -0
- package/dist/graphql/sqlserver/physical_model.js +8 -0
- package/dist/graphql/sqlserver/sql_server_connection_settings.d.ts +15 -0
- package/dist/graphql/sqlserver/sql_server_connection_settings.js +28 -0
- package/dist/graphql/sqlserver/sql_server_metadata_reader.d.ts +39 -0
- package/dist/graphql/sqlserver/sql_server_metadata_reader.js +294 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +58 -1
- package/dist/openapi/swagger_docs.d.ts +4 -0
- package/dist/openapi/swagger_docs.js +6 -2
- package/package.json +8 -6
package/README.md
CHANGED
|
@@ -35,10 +35,10 @@ curl -X POST http://localhost:8080/api/greetings/hello \
|
|
|
35
35
|
{ "message": "Hello, World!" }
|
|
36
36
|
```
|
|
37
37
|
|
|
38
|
-
**Docs** → `http://localhost:8080/docs`
|
|
39
|
-
**Health** → `http://localhost:8080/health`
|
|
40
|
-
**OpenAPI JSON** → `http://localhost:8080/openapi.json` _(also /openapi.yaml)_
|
|
41
|
-
**Metrics** → `http://localhost:8080/metrics` _(opt-in)_
|
|
38
|
+
**Docs** → `http://localhost:8080/api/docs`
|
|
39
|
+
**Health** → `http://localhost:8080/api/health`
|
|
40
|
+
**OpenAPI JSON** → `http://localhost:8080/api/openapi.json` _(also /api/openapi.yaml)_
|
|
41
|
+
**Metrics** → `http://localhost:8080/api/metrics` _(opt-in)_
|
|
42
42
|
|
|
43
43
|
See `example/example.ts` for the full implementation including Input, Output, UseCase with `validate()`, and the builder.
|
|
44
44
|
|
|
@@ -53,22 +53,84 @@ See `example/example.ts` for the full implementation including Input, Output, Us
|
|
|
53
53
|
- `ModularApi` + `ModuleBuilder` — module registration and routing
|
|
54
54
|
- Constructor-based unit testing with fake dependency injection
|
|
55
55
|
- `cors()` middleware — built-in CORS support
|
|
56
|
-
-
|
|
57
|
-
-
|
|
58
|
-
-
|
|
59
|
-
-
|
|
56
|
+
- All public endpoints resolve under the configured `basePath`.
|
|
57
|
+
- Swagger UI at `/{basePath}/docs` — auto-generated from registered use cases
|
|
58
|
+
- OpenAPI spec at `/{basePath}/openapi.json` and `/{basePath}/openapi.yaml` — raw spec download
|
|
59
|
+
- Health check at `GET /{basePath}/health` — [IETF Health Check Response Format](doc/health_check_guide.md)
|
|
60
|
+
- Prometheus metrics at `GET /{basePath}/metrics` — [Prometheus exposition format](doc/metrics_guide.md)
|
|
60
61
|
- Structured JSON logging — Loki/Grafana compatible, [request-scoped with trace_id](doc/logger_guide.md)
|
|
61
62
|
- All endpoints default to `POST` (configurable per use case)
|
|
62
63
|
- Full TypeScript declarations (`.d.ts`) included
|
|
63
64
|
|
|
64
65
|
---
|
|
65
66
|
|
|
67
|
+
## Plugin host
|
|
68
|
+
|
|
69
|
+
The public plugin contract is available from the package exports and is already
|
|
70
|
+
used by the official health, metrics, OpenAPI, and docs plugins.
|
|
71
|
+
|
|
72
|
+
Current lifecycle behavior:
|
|
73
|
+
|
|
74
|
+
- `api.plugin(...)` registers a plugin instance without running setup yet
|
|
75
|
+
- `setup(host)` runs during `serve()` in dependency order
|
|
76
|
+
- `validate(host)` runs after registration freeze and can abort startup
|
|
77
|
+
- `shutdown()` runs in reverse setup order on normal shutdown and on partial
|
|
78
|
+
startup rollback
|
|
79
|
+
- plugin routes always resolve under the configured `basePath`
|
|
80
|
+
- all three public middleware slots are active with deterministic ordering
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
import {
|
|
84
|
+
ModularApi,
|
|
85
|
+
type Plugin,
|
|
86
|
+
type PluginHost,
|
|
87
|
+
type PluginManifest,
|
|
88
|
+
} from '@macss/modular-api';
|
|
89
|
+
|
|
90
|
+
class HelloPlugin implements Plugin {
|
|
91
|
+
readonly manifest: PluginManifest = {
|
|
92
|
+
id: 'acme.hello',
|
|
93
|
+
displayName: 'Hello Plugin',
|
|
94
|
+
version: '0.1.0',
|
|
95
|
+
hostApiVersion: '>=0.1.0 <0.2.0',
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
setup(host: PluginHost): void {
|
|
99
|
+
host.registerRoute({
|
|
100
|
+
id: 'hello-plugin',
|
|
101
|
+
method: 'GET',
|
|
102
|
+
path: '/hello-plugin',
|
|
103
|
+
visibility: 'custom',
|
|
104
|
+
handler: () => ({
|
|
105
|
+
status: 200,
|
|
106
|
+
body: { ok: true, basePath: host.metadata().basePath },
|
|
107
|
+
}),
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
validate() {
|
|
112
|
+
return [];
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const api = new ModularApi({ basePath: '/api' }).plugin(new HelloPlugin());
|
|
117
|
+
await api.serve({ port: 8080 });
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
---
|
|
121
|
+
|
|
66
122
|
## Installation
|
|
67
123
|
|
|
68
124
|
```bash
|
|
69
125
|
npm install @macss/modular-api
|
|
70
126
|
```
|
|
71
127
|
|
|
128
|
+
If you use `SqlServerMetadataReader` for SQL Server introspection, install `mssql` explicitly:
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
npm install @macss/modular-api mssql
|
|
132
|
+
```
|
|
133
|
+
|
|
72
134
|
---
|
|
73
135
|
|
|
74
136
|
## Error handling
|
|
@@ -68,6 +68,7 @@ export declare class RequestScopedLogger implements ModularLogger {
|
|
|
68
68
|
route: string;
|
|
69
69
|
statusCode: number;
|
|
70
70
|
durationMs: number;
|
|
71
|
+
extra?: Record<string, unknown>;
|
|
71
72
|
}): void;
|
|
72
73
|
/** Emits an "unhandled exception" log at `error` level. No stack trace. */
|
|
73
74
|
logUnhandledException(opts: {
|
|
@@ -9,6 +9,7 @@ exports.LOGGER_LOCALS_KEY = void 0;
|
|
|
9
9
|
exports.loggingMiddleware = loggingMiddleware;
|
|
10
10
|
const node_crypto_1 = require("node:crypto");
|
|
11
11
|
const logger_1 = require("./logger");
|
|
12
|
+
const request_pipeline_audit_1 = require("../request_pipeline_audit");
|
|
12
13
|
/** Key used in `res.locals` to propagate the logger to downstream handlers. */
|
|
13
14
|
exports.LOGGER_LOCALS_KEY = 'modularLogger';
|
|
14
15
|
/**
|
|
@@ -42,17 +43,27 @@ function loggingMiddleware(opts) {
|
|
|
42
43
|
logger.logRequest({ method, route });
|
|
43
44
|
// 4. Propagate logger via res.locals
|
|
44
45
|
res.locals[exports.LOGGER_LOCALS_KEY] = logger;
|
|
46
|
+
(0, request_pipeline_audit_1.ensureRequestPipelineAudit)(res);
|
|
45
47
|
// 5. Attach X-Request-ID to response
|
|
46
48
|
res.setHeader('X-Request-ID', traceId);
|
|
47
49
|
// 6. Capture timing and emit response log on finish
|
|
48
50
|
const startNs = process.hrtime.bigint();
|
|
49
51
|
res.on('finish', () => {
|
|
50
52
|
const durationMs = Number(process.hrtime.bigint() - startNs) / 1e6;
|
|
53
|
+
const shortCircuit = (0, request_pipeline_audit_1.readShortCircuitCandidate)(res);
|
|
51
54
|
logger.logResponse({
|
|
52
55
|
method,
|
|
53
56
|
route,
|
|
54
57
|
statusCode: res.statusCode,
|
|
55
58
|
durationMs,
|
|
59
|
+
extra: shortCircuit
|
|
60
|
+
? {
|
|
61
|
+
short_circuit: true,
|
|
62
|
+
short_circuit_plugin_id: shortCircuit.pluginId,
|
|
63
|
+
short_circuit_middleware_id: shortCircuit.middlewareId,
|
|
64
|
+
short_circuit_slot: shortCircuit.slot,
|
|
65
|
+
}
|
|
66
|
+
: undefined,
|
|
56
67
|
});
|
|
57
68
|
});
|
|
58
69
|
next();
|
|
@@ -3,6 +3,8 @@ import { ModuleBuilder } from './module_builder';
|
|
|
3
3
|
import type { HealthCheck } from './health/health_check';
|
|
4
4
|
import { MetricsRegistrar } from './metrics/metric_registry';
|
|
5
5
|
import { LogLevel } from './logger/logger';
|
|
6
|
+
import { type Plugin } from './plugin';
|
|
7
|
+
import type { GraphqlOptions } from '../graphql/runtime/graphql_runtime_options';
|
|
6
8
|
export interface ModularApiOptions {
|
|
7
9
|
/** Base path prefix for all module routes. Default: '/api' */
|
|
8
10
|
basePath?: string;
|
|
@@ -34,6 +36,8 @@ export interface ModularApiOptions {
|
|
|
34
36
|
url: string;
|
|
35
37
|
description?: string;
|
|
36
38
|
}>;
|
|
39
|
+
/** GraphQL runtime integration. Disabled by default. */
|
|
40
|
+
graphql?: GraphqlOptions;
|
|
37
41
|
}
|
|
38
42
|
/**
|
|
39
43
|
* Main entry point for modular_api.
|
|
@@ -61,8 +65,10 @@ export declare class ModularApi {
|
|
|
61
65
|
private readonly rootRouter;
|
|
62
66
|
private readonly basePath;
|
|
63
67
|
private readonly title;
|
|
68
|
+
private readonly version;
|
|
64
69
|
private readonly middlewares;
|
|
65
70
|
private readonly healthService;
|
|
71
|
+
private readonly plugins;
|
|
66
72
|
private readonly metricsEnabled;
|
|
67
73
|
private readonly metricsPath;
|
|
68
74
|
private readonly excludedMetricsRoutes;
|
|
@@ -73,6 +79,7 @@ export declare class ModularApi {
|
|
|
73
79
|
private readonly httpRequestDuration?;
|
|
74
80
|
private readonly logLevel;
|
|
75
81
|
private readonly servers?;
|
|
82
|
+
private readonly graphql?;
|
|
76
83
|
/** Public accessor for custom-metric registration. Undefined when metrics are disabled. */
|
|
77
84
|
get metrics(): MetricsRegistrar | undefined;
|
|
78
85
|
constructor(options?: ModularApiOptions);
|
|
@@ -109,6 +116,7 @@ export declare class ModularApi {
|
|
|
109
116
|
* ```
|
|
110
117
|
*/
|
|
111
118
|
use(middleware: RequestHandler): this;
|
|
119
|
+
plugin(plugin: Plugin): this;
|
|
112
120
|
/**
|
|
113
121
|
* Starts the Express server on the given port.
|
|
114
122
|
*
|
package/dist/core/modular_api.js
CHANGED
|
@@ -11,16 +11,14 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
11
11
|
exports.ModularApi = void 0;
|
|
12
12
|
const express_1 = __importDefault(require("express"));
|
|
13
13
|
const module_builder_1 = require("./module_builder");
|
|
14
|
-
const openapi_1 = require("../openapi/openapi");
|
|
15
|
-
const swagger_docs_1 = require("../openapi/swagger_docs");
|
|
16
14
|
const health_service_1 = require("./health/health_service");
|
|
17
|
-
const health_handler_1 = require("./health/health_handler");
|
|
18
15
|
const metric_registry_1 = require("./metrics/metric_registry");
|
|
19
|
-
const metrics_middleware_1 = require("./metrics/metrics_middleware");
|
|
20
16
|
const logging_middleware_1 = require("./logger/logging_middleware");
|
|
21
17
|
const logger_1 = require("./logger/logger");
|
|
22
18
|
const body_parser_error_handler_1 = require("./body_parser_error_handler");
|
|
23
|
-
const
|
|
19
|
+
const unhandled_request_error_handler_1 = require("./unhandled_request_error_handler");
|
|
20
|
+
const official_plugins_1 = require("./official_plugins");
|
|
21
|
+
const plugin_1 = require("./plugin");
|
|
24
22
|
/**
|
|
25
23
|
* Main entry point for modular_api.
|
|
26
24
|
*
|
|
@@ -47,8 +45,10 @@ class ModularApi {
|
|
|
47
45
|
rootRouter;
|
|
48
46
|
basePath;
|
|
49
47
|
title;
|
|
48
|
+
version;
|
|
50
49
|
middlewares = [];
|
|
51
50
|
healthService;
|
|
51
|
+
plugins = [];
|
|
52
52
|
// Metrics
|
|
53
53
|
metricsEnabled;
|
|
54
54
|
metricsPath;
|
|
@@ -62,6 +62,7 @@ class ModularApi {
|
|
|
62
62
|
logLevel;
|
|
63
63
|
// OpenAPI
|
|
64
64
|
servers;
|
|
65
|
+
graphql;
|
|
65
66
|
/** Public accessor for custom-metric registration. Undefined when metrics are disabled. */
|
|
66
67
|
get metrics() {
|
|
67
68
|
return this._metricsRegistrar;
|
|
@@ -69,8 +70,9 @@ class ModularApi {
|
|
|
69
70
|
constructor(options = {}) {
|
|
70
71
|
this.basePath = options.basePath ?? '/api';
|
|
71
72
|
this.title = options.title ?? 'Modular API';
|
|
73
|
+
this.version = options.version ?? 'x.y.z';
|
|
72
74
|
this.healthService = new health_service_1.HealthService({
|
|
73
|
-
version:
|
|
75
|
+
version: this.version,
|
|
74
76
|
releaseId: options.releaseId,
|
|
75
77
|
});
|
|
76
78
|
// Metrics setup
|
|
@@ -81,6 +83,7 @@ class ModularApi {
|
|
|
81
83
|
this.logLevel = options.logLevel ?? logger_1.LogLevel.info;
|
|
82
84
|
// OpenAPI servers
|
|
83
85
|
this.servers = options.servers;
|
|
86
|
+
this.graphql = options.graphql;
|
|
84
87
|
if (this.metricsEnabled) {
|
|
85
88
|
this.metricRegistry = new metric_registry_1.MetricRegistry();
|
|
86
89
|
this._metricsRegistrar = new metric_registry_1.MetricsRegistrar(this.metricRegistry);
|
|
@@ -146,6 +149,10 @@ class ModularApi {
|
|
|
146
149
|
this.middlewares.push(middleware);
|
|
147
150
|
return this;
|
|
148
151
|
}
|
|
152
|
+
plugin(plugin) {
|
|
153
|
+
this.plugins.push(plugin);
|
|
154
|
+
return this;
|
|
155
|
+
}
|
|
149
156
|
/**
|
|
150
157
|
* Starts the Express server on the given port.
|
|
151
158
|
*
|
|
@@ -155,11 +162,78 @@ class ModularApi {
|
|
|
155
162
|
*
|
|
156
163
|
* @returns The Node.js http.Server instance
|
|
157
164
|
*/
|
|
158
|
-
serve(options) {
|
|
165
|
+
async serve(options) {
|
|
159
166
|
const { port, host = '0.0.0.0' } = options;
|
|
160
|
-
|
|
167
|
+
const operationalPaths = (0, official_plugins_1.operationalRoutePaths)(this.basePath, this.metricsEnabled ? this.metricsPath : undefined);
|
|
168
|
+
const runtimePlugins = [
|
|
169
|
+
...this.plugins,
|
|
170
|
+
...(0, official_plugins_1.buildRuntimePlugins)({
|
|
171
|
+
basePath: this.basePath,
|
|
172
|
+
title: this.title,
|
|
173
|
+
version: this.version,
|
|
174
|
+
port,
|
|
175
|
+
servers: this.servers,
|
|
176
|
+
healthService: this.healthService,
|
|
177
|
+
graphql: this.graphql,
|
|
178
|
+
metrics: this.metricsEnabled &&
|
|
179
|
+
this.metricRegistry &&
|
|
180
|
+
this.httpRequestsTotal &&
|
|
181
|
+
this.httpRequestsInFlight &&
|
|
182
|
+
this.httpRequestDuration
|
|
183
|
+
? {
|
|
184
|
+
path: this.metricsPath,
|
|
185
|
+
registry: this.metricRegistry,
|
|
186
|
+
requestsTotal: this.httpRequestsTotal,
|
|
187
|
+
requestsInFlight: this.httpRequestsInFlight,
|
|
188
|
+
requestDuration: this.httpRequestDuration,
|
|
189
|
+
excludedRoutes: this.excludedMetricsRoutes,
|
|
190
|
+
}
|
|
191
|
+
: undefined,
|
|
192
|
+
}),
|
|
193
|
+
];
|
|
194
|
+
const seenPluginIds = new Set();
|
|
195
|
+
for (const plugin of runtimePlugins) {
|
|
196
|
+
if (seenPluginIds.has(plugin.manifest.id)) {
|
|
197
|
+
throw new plugin_1.PluginHostError('PLUGIN_ID_CONFLICT', `Duplicate plugin id: ${plugin.manifest.id}`, plugin.manifest.id, plugin.manifest.id);
|
|
198
|
+
}
|
|
199
|
+
seenPluginIds.add(plugin.manifest.id);
|
|
200
|
+
}
|
|
201
|
+
const orderedPlugins = (0, plugin_1.orderPlugins)(runtimePlugins);
|
|
202
|
+
const pluginHost = new plugin_1.RuntimePluginHost({
|
|
203
|
+
basePath: this.basePath,
|
|
204
|
+
title: this.title,
|
|
205
|
+
version: this.version,
|
|
206
|
+
});
|
|
207
|
+
try {
|
|
208
|
+
for (const plugin of orderedPlugins) {
|
|
209
|
+
pluginHost.beginPluginSetup(plugin.manifest.id);
|
|
210
|
+
try {
|
|
211
|
+
plugin.setup(pluginHost);
|
|
212
|
+
}
|
|
213
|
+
finally {
|
|
214
|
+
pluginHost.endPluginSetup();
|
|
215
|
+
}
|
|
216
|
+
if (plugin.shutdown) {
|
|
217
|
+
pluginHost.onShutdown(() => plugin.shutdown());
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
pluginHost.freeze();
|
|
221
|
+
const validationResults = (await Promise.all(orderedPlugins.map(async (plugin) => plugin.validate?.(pluginHost) ?? []))).flat();
|
|
222
|
+
pluginHost.assertValid(validationResults);
|
|
223
|
+
}
|
|
224
|
+
catch (error) {
|
|
225
|
+
await pluginHost.shutdown();
|
|
226
|
+
throw error;
|
|
227
|
+
}
|
|
228
|
+
return await new Promise((resolve) => {
|
|
161
229
|
// Logging middleware FIRST — trace_id + structured JSON logs.
|
|
162
|
-
const excludedLogRoutes = [
|
|
230
|
+
const excludedLogRoutes = [
|
|
231
|
+
operationalPaths.healthPath,
|
|
232
|
+
operationalPaths.docsPath,
|
|
233
|
+
operationalPaths.openApiJsonPath,
|
|
234
|
+
operationalPaths.openApiYamlPath,
|
|
235
|
+
...(operationalPaths.metricsPath ? [operationalPaths.metricsPath] : []),
|
|
236
|
+
];
|
|
163
237
|
this.app.use((0, logging_middleware_1.loggingMiddleware)({
|
|
164
238
|
logLevel: this.logLevel,
|
|
165
239
|
serviceName: this.title,
|
|
@@ -168,49 +242,32 @@ class ModularApi {
|
|
|
168
242
|
// Body parsing AFTER loggingMiddleware — SyntaxErrors now have trace_id.
|
|
169
243
|
this.app.use(express_1.default.json());
|
|
170
244
|
this.app.use(body_parser_error_handler_1.bodyParserErrorHandler);
|
|
171
|
-
|
|
172
|
-
// Created here so registeredPaths is populated from apiRegistry.
|
|
173
|
-
if (this.metricsEnabled &&
|
|
174
|
-
this.httpRequestsTotal &&
|
|
175
|
-
this.httpRequestsInFlight &&
|
|
176
|
-
this.httpRequestDuration) {
|
|
177
|
-
const registeredPaths = registry_1.apiRegistry.routes.map((r) => r.path);
|
|
178
|
-
this.app.use((0, metrics_middleware_1.metricsMiddleware)({
|
|
179
|
-
requestsTotal: this.httpRequestsTotal,
|
|
180
|
-
requestsInFlight: this.httpRequestsInFlight,
|
|
181
|
-
requestDuration: this.httpRequestDuration,
|
|
182
|
-
excludedRoutes: this.excludedMetricsRoutes,
|
|
183
|
-
registeredPaths,
|
|
184
|
-
}));
|
|
185
|
-
}
|
|
245
|
+
pluginHost.applyMiddlewares('preRouting', this.app);
|
|
186
246
|
// Register middlewares before routes
|
|
187
247
|
for (const mw of this.middlewares) {
|
|
188
248
|
this.app.use(mw);
|
|
189
249
|
}
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
}
|
|
194
|
-
// Health endpoint — IETF Health Check Response Format
|
|
195
|
-
this.app.get('/health', (0, health_handler_1.healthHandler)(this.healthService));
|
|
250
|
+
pluginHost.applyMiddlewares('preHandler', this.app);
|
|
251
|
+
pluginHost.applyMiddlewares('postHandler', this.app);
|
|
252
|
+
pluginHost.applyRoutes(this.rootRouter);
|
|
196
253
|
// Module use case routes.
|
|
197
254
|
this.app.use(this.rootRouter);
|
|
198
|
-
|
|
199
|
-
this.app.get('/docs', (0, swagger_docs_1.swaggerDocsHandler)({ title: this.title }));
|
|
200
|
-
// Raw spec endpoints
|
|
201
|
-
const spec = (0, openapi_1.buildOpenApiSpec)({ title: this.title, port, servers: this.servers });
|
|
202
|
-
this.app.get('/openapi.json', (0, openapi_1.openApiJsonHandler)(spec));
|
|
203
|
-
this.app.get('/openapi.yaml', (0, openapi_1.openApiYamlHandler)(spec));
|
|
255
|
+
this.app.use(unhandled_request_error_handler_1.unhandledRequestErrorHandler);
|
|
204
256
|
const server = this.app.listen(port, host, () => {
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
console.log(`
|
|
208
|
-
console.log(`
|
|
209
|
-
|
|
210
|
-
|
|
257
|
+
const address = server.address();
|
|
258
|
+
const resolvedPort = typeof address === 'object' && address ? address.port : port;
|
|
259
|
+
console.log(`Docs → http://localhost:${resolvedPort}${operationalPaths.docsPath}`);
|
|
260
|
+
console.log(`Health → http://localhost:${resolvedPort}${operationalPaths.healthPath}`);
|
|
261
|
+
console.log(`OpenAPI JSON → http://localhost:${resolvedPort}${operationalPaths.openApiJsonPath}`);
|
|
262
|
+
console.log(`OpenAPI YAML → http://localhost:${resolvedPort}${operationalPaths.openApiYamlPath}`);
|
|
263
|
+
if (operationalPaths.metricsPath) {
|
|
264
|
+
console.log(`Metrics → http://localhost:${resolvedPort}${operationalPaths.metricsPath}`);
|
|
211
265
|
}
|
|
212
266
|
resolve(server);
|
|
213
267
|
});
|
|
268
|
+
server.on('close', () => {
|
|
269
|
+
void pluginHost.shutdown();
|
|
270
|
+
});
|
|
214
271
|
});
|
|
215
272
|
}
|
|
216
273
|
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { GraphqlOptions } from '../graphql/runtime/graphql_runtime_options';
|
|
2
|
+
import type { HealthService } from './health/health_service';
|
|
3
|
+
import type { Counter, Gauge, Histogram } from './metrics/metric';
|
|
4
|
+
import type { MetricRegistry } from './metrics/metric_registry';
|
|
5
|
+
import type { Plugin } from './plugin';
|
|
6
|
+
export interface OperationalRoutePaths {
|
|
7
|
+
healthPath: string;
|
|
8
|
+
docsPath: string;
|
|
9
|
+
openApiJsonPath: string;
|
|
10
|
+
openApiYamlPath: string;
|
|
11
|
+
metricsPath?: string;
|
|
12
|
+
}
|
|
13
|
+
interface BuildRuntimePluginsOptions {
|
|
14
|
+
basePath: string;
|
|
15
|
+
title: string;
|
|
16
|
+
version: string;
|
|
17
|
+
port: number;
|
|
18
|
+
servers?: Array<{
|
|
19
|
+
url: string;
|
|
20
|
+
description?: string;
|
|
21
|
+
}>;
|
|
22
|
+
healthService: HealthService;
|
|
23
|
+
graphql?: GraphqlOptions;
|
|
24
|
+
metrics?: {
|
|
25
|
+
path: string;
|
|
26
|
+
registry: MetricRegistry;
|
|
27
|
+
requestsTotal: Counter;
|
|
28
|
+
requestsInFlight: Gauge;
|
|
29
|
+
requestDuration: Histogram;
|
|
30
|
+
excludedRoutes: string[];
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
export declare function operationalRoutePaths(basePath: string, metricsPath?: string): OperationalRoutePaths;
|
|
34
|
+
export declare function buildRuntimePlugins(options: BuildRuntimePluginsOptions): Plugin[];
|
|
35
|
+
export {};
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.operationalRoutePaths = operationalRoutePaths;
|
|
4
|
+
exports.buildRuntimePlugins = buildRuntimePlugins;
|
|
5
|
+
const openapi_1 = require("../openapi/openapi");
|
|
6
|
+
const swagger_docs_1 = require("../openapi/swagger_docs");
|
|
7
|
+
const graphql_runtime_plugin_1 = require("../graphql/runtime/graphql_runtime_plugin");
|
|
8
|
+
const metrics_middleware_1 = require("./metrics/metrics_middleware");
|
|
9
|
+
const registry_1 = require("./registry");
|
|
10
|
+
const OPENAPI_SPEC_CAPABILITY_ID = 'modular_api.openapi.spec';
|
|
11
|
+
const OFFICIAL_PLUGIN_HOST_RANGE = '>=0.1.0 <0.2.0';
|
|
12
|
+
function operationalRoutePaths(basePath, metricsPath) {
|
|
13
|
+
return {
|
|
14
|
+
healthPath: joinPath(basePath, '/health'),
|
|
15
|
+
docsPath: joinPath(basePath, '/docs'),
|
|
16
|
+
openApiJsonPath: joinPath(basePath, '/openapi.json'),
|
|
17
|
+
openApiYamlPath: joinPath(basePath, '/openapi.yaml'),
|
|
18
|
+
metricsPath: metricsPath ? joinPath(basePath, metricsPath) : undefined,
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
function buildRuntimePlugins(options) {
|
|
22
|
+
const plugins = [
|
|
23
|
+
new HealthRuntimePlugin(options.healthService),
|
|
24
|
+
new graphql_runtime_plugin_1.GraphqlRuntimePlugin(options.graphql, options.healthService),
|
|
25
|
+
];
|
|
26
|
+
if (options.metrics) {
|
|
27
|
+
plugins.push(new MetricsRuntimePlugin(options.basePath, options.metrics));
|
|
28
|
+
}
|
|
29
|
+
plugins.push(new OpenApiRuntimePlugin({
|
|
30
|
+
basePath: options.basePath,
|
|
31
|
+
title: options.title,
|
|
32
|
+
version: options.version,
|
|
33
|
+
port: options.port,
|
|
34
|
+
servers: options.servers,
|
|
35
|
+
}), new DocsRuntimePlugin());
|
|
36
|
+
return plugins;
|
|
37
|
+
}
|
|
38
|
+
class HealthRuntimePlugin {
|
|
39
|
+
healthService;
|
|
40
|
+
manifest = {
|
|
41
|
+
id: 'modular_api.health',
|
|
42
|
+
displayName: 'Health Plugin',
|
|
43
|
+
version: '0.1.0',
|
|
44
|
+
hostApiVersion: OFFICIAL_PLUGIN_HOST_RANGE,
|
|
45
|
+
};
|
|
46
|
+
constructor(healthService) {
|
|
47
|
+
this.healthService = healthService;
|
|
48
|
+
}
|
|
49
|
+
setup(host) {
|
|
50
|
+
host.registerRoute({
|
|
51
|
+
id: 'health.endpoint',
|
|
52
|
+
method: 'GET',
|
|
53
|
+
path: '/health',
|
|
54
|
+
visibility: 'operational',
|
|
55
|
+
handler: async () => {
|
|
56
|
+
const health = await this.healthService.evaluate();
|
|
57
|
+
return {
|
|
58
|
+
status: health.httpStatusCode,
|
|
59
|
+
contentType: 'application/health+json; charset=utf-8',
|
|
60
|
+
body: health.toJson(),
|
|
61
|
+
};
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
class MetricsRuntimePlugin {
|
|
67
|
+
basePath;
|
|
68
|
+
options;
|
|
69
|
+
manifest = {
|
|
70
|
+
id: 'modular_api.metrics',
|
|
71
|
+
displayName: 'Metrics Plugin',
|
|
72
|
+
version: '0.1.0',
|
|
73
|
+
hostApiVersion: OFFICIAL_PLUGIN_HOST_RANGE,
|
|
74
|
+
};
|
|
75
|
+
constructor(basePath, options) {
|
|
76
|
+
this.basePath = basePath;
|
|
77
|
+
this.options = options;
|
|
78
|
+
}
|
|
79
|
+
setup(host) {
|
|
80
|
+
if (!this.options) {
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
const paths = operationalRoutePaths(this.basePath, this.options.path);
|
|
84
|
+
const configuredExcluded = this.options.excludedRoutes.map((route) => joinPath(this.basePath, route));
|
|
85
|
+
const excludedRoutes = [...new Set([
|
|
86
|
+
...configuredExcluded,
|
|
87
|
+
paths.healthPath,
|
|
88
|
+
paths.docsPath,
|
|
89
|
+
paths.openApiJsonPath,
|
|
90
|
+
paths.openApiYamlPath,
|
|
91
|
+
...(paths.metricsPath ? [paths.metricsPath] : []),
|
|
92
|
+
])];
|
|
93
|
+
host.registerMiddleware({
|
|
94
|
+
id: 'metrics.middleware',
|
|
95
|
+
slot: 'preRouting',
|
|
96
|
+
order: 0,
|
|
97
|
+
handler: (0, metrics_middleware_1.metricsMiddleware)({
|
|
98
|
+
requestsTotal: this.options.requestsTotal,
|
|
99
|
+
requestsInFlight: this.options.requestsInFlight,
|
|
100
|
+
requestDuration: this.options.requestDuration,
|
|
101
|
+
excludedRoutes,
|
|
102
|
+
registeredPaths: registry_1.apiRegistry.routes.map((route) => route.path),
|
|
103
|
+
}),
|
|
104
|
+
});
|
|
105
|
+
host.registerRoute({
|
|
106
|
+
id: 'metrics.endpoint',
|
|
107
|
+
method: 'GET',
|
|
108
|
+
path: this.options.path,
|
|
109
|
+
visibility: 'operational',
|
|
110
|
+
handler: () => ({
|
|
111
|
+
status: 200,
|
|
112
|
+
contentType: 'text/plain; version=0.0.4; charset=utf-8',
|
|
113
|
+
body: this.options?.registry.serialize(),
|
|
114
|
+
}),
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
class OpenApiRuntimePlugin {
|
|
119
|
+
options;
|
|
120
|
+
manifest = {
|
|
121
|
+
id: 'modular_api.openapi',
|
|
122
|
+
displayName: 'OpenAPI Plugin',
|
|
123
|
+
version: '0.1.0',
|
|
124
|
+
hostApiVersion: OFFICIAL_PLUGIN_HOST_RANGE,
|
|
125
|
+
};
|
|
126
|
+
constructor(options) {
|
|
127
|
+
this.options = options;
|
|
128
|
+
}
|
|
129
|
+
setup(host) {
|
|
130
|
+
const spec = (0, openapi_1.buildOpenApiSpec)({
|
|
131
|
+
title: this.options.title,
|
|
132
|
+
port: this.options.port,
|
|
133
|
+
version: this.options.version,
|
|
134
|
+
servers: this.options.servers,
|
|
135
|
+
});
|
|
136
|
+
const yaml = (0, openapi_1.jsonToYaml)(spec);
|
|
137
|
+
const specUrl = operationalRoutePaths(this.options.basePath).openApiJsonPath;
|
|
138
|
+
host.exposeCapability({
|
|
139
|
+
id: OPENAPI_SPEC_CAPABILITY_ID,
|
|
140
|
+
version: '1.0.0',
|
|
141
|
+
value: { spec, yaml, specUrl },
|
|
142
|
+
});
|
|
143
|
+
host.registerRoute({
|
|
144
|
+
id: 'openapi.json.endpoint',
|
|
145
|
+
method: 'GET',
|
|
146
|
+
path: '/openapi.json',
|
|
147
|
+
visibility: 'operational',
|
|
148
|
+
handler: () => ({
|
|
149
|
+
status: 200,
|
|
150
|
+
contentType: 'application/json; charset=utf-8',
|
|
151
|
+
body: spec,
|
|
152
|
+
}),
|
|
153
|
+
});
|
|
154
|
+
host.registerRoute({
|
|
155
|
+
id: 'openapi.yaml.endpoint',
|
|
156
|
+
method: 'GET',
|
|
157
|
+
path: '/openapi.yaml',
|
|
158
|
+
visibility: 'operational',
|
|
159
|
+
handler: () => ({
|
|
160
|
+
status: 200,
|
|
161
|
+
contentType: 'application/x-yaml; charset=utf-8',
|
|
162
|
+
body: yaml,
|
|
163
|
+
}),
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
class DocsRuntimePlugin {
|
|
168
|
+
manifest = {
|
|
169
|
+
id: 'modular_api.docs',
|
|
170
|
+
displayName: 'Docs Plugin',
|
|
171
|
+
version: '0.1.0',
|
|
172
|
+
hostApiVersion: OFFICIAL_PLUGIN_HOST_RANGE,
|
|
173
|
+
};
|
|
174
|
+
setup(host) {
|
|
175
|
+
const specCapability = host.requireCapability(OPENAPI_SPEC_CAPABILITY_ID);
|
|
176
|
+
const html = (0, swagger_docs_1.buildSwaggerDocsHtml)({
|
|
177
|
+
title: host.metadata().title,
|
|
178
|
+
specUrl: specCapability.value.specUrl,
|
|
179
|
+
});
|
|
180
|
+
host.registerRoute({
|
|
181
|
+
id: 'docs.endpoint',
|
|
182
|
+
method: 'GET',
|
|
183
|
+
path: '/docs',
|
|
184
|
+
visibility: 'operational',
|
|
185
|
+
handler: () => ({
|
|
186
|
+
status: 200,
|
|
187
|
+
contentType: 'text/html; charset=utf-8',
|
|
188
|
+
body: html,
|
|
189
|
+
}),
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
function normalizeBasePath(basePath) {
|
|
194
|
+
if (!basePath || basePath === '/') {
|
|
195
|
+
return '/';
|
|
196
|
+
}
|
|
197
|
+
return `/${basePath.trim().replace(/^\/+|\/+$/g, '')}`;
|
|
198
|
+
}
|
|
199
|
+
function normalizeRelativePath(path) {
|
|
200
|
+
const trimmed = path.trim();
|
|
201
|
+
if (!trimmed) {
|
|
202
|
+
throw new Error('Plugin route path cannot be empty');
|
|
203
|
+
}
|
|
204
|
+
return `/${trimmed.replace(/^\/+|\/+$/g, '')}`;
|
|
205
|
+
}
|
|
206
|
+
function joinPath(basePath, relativePath) {
|
|
207
|
+
const normalizedBasePath = normalizeBasePath(basePath);
|
|
208
|
+
const normalizedRelativePath = normalizeRelativePath(relativePath);
|
|
209
|
+
if (normalizedBasePath === '/') {
|
|
210
|
+
return normalizedRelativePath;
|
|
211
|
+
}
|
|
212
|
+
return `${normalizedBasePath}${normalizedRelativePath}`.replace(/\/+/g, '/');
|
|
213
|
+
}
|