Skip to content

Commit 2a0d8f8

Browse files
authored
Merge pull request #88 from Accenture/chore/quality-polish
Quality round: 12 Sonar rules, EventEmitter rationale, and engine-parity host polish
2 parents 51bfdc1 + a73332f commit 2a0d8f8

16 files changed

Lines changed: 234 additions & 80 deletions

‎CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@
22

33
## 0.1.0 (unreleased)
44

5+
- Host polish for engine parity: `GET /` serves the engines' minimal index page linking
6+
the actuator endpoints (embedded - no static file service by design); actuator JSON
7+
responses are pretty-printed (the engines' default-serializer presentation); unknown
8+
paths and non-GET methods answer the engines' error shape
9+
`{"status": 404, "message": "Resource not found", "type": "error"}`.
510
- Actuator endpoints `/info`, `/info/routes`, `/env`, `/health` and `/livenessprobe` -
611
the engines' operational surface, for Kubernetes probes and one-dashboard monitoring
712
of polyglot installations. Health check functions are normal registered functions

‎LICENSE‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,7 @@
187187
same "printed page" as the copyright notice for easier
188188
identification within third-party archives.
189189

190-
Copyright 2018 - 2025 Accenture.
190+
Copyright 2018-2026 Accenture.
191191

192192
Licensed under the Apache License, Version 2.0 (the "License");
193193
you may not use this file except in compliance with the License.

‎README.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,7 @@ Kubernetes probes and dashboards treat a Node.js app exactly like a Java or Rust
134134

135135
| Endpoint | Purpose |
136136
|----------|---------|
137+
| `GET /` | minimal index page linking the endpoints below |
137138
| `GET /info` | app identity, runtime, origin id, start time, uptime |
138139
| `GET /info/routes` | registered routes split by visibility, with instance counts |
139140
| `GET /env` | selected environment variables and configuration parameters |
@@ -156,6 +157,10 @@ preload('demo.health', { isPrivate: true }, async (headers, _body) => {
156157
});
157158
```
158159

160+
JSON responses are pretty-printed — the engines' default-serializer presentation — and
161+
unknown paths answer the engines' error shape
162+
(`{"status": 404, "message": "Resource not found", "type": "error"}`).
163+
159164
Kubernetes wiring: point `livenessProbe` at `/livenessprobe` and `readinessProbe` at
160165
`/health`.
161166

‎examples/demo-app.mjs‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,13 @@ import { AppException, annotateTrace, getLogger, preload } from '../dist/src/ind
1818
const log = getLogger('demo-app');
1919

2020
preload('hello.node', { instances: 10 }, async (headers, body) => {
21-
if (typeof body !== 'object' || body === null || !('text' in body)) {
21+
if (typeof body !== 'object' || body === null
22+
|| !('text' in body) || typeof body.text !== 'string') {
2223
throw new AppException(400, "missing 'text'");
2324
}
2425
annotateTrace('language', 'node.js');
25-
log.info(`Transforming text of length ${String(body.text).length}`);
26-
return { text: String(body.text).toUpperCase(), language: 'node.js' };
26+
log.info(`Transforming text of length ${body.text.length}`);
27+
return { text: body.text.toUpperCase(), language: 'node.js' };
2728
});
2829

2930
preload('hello.declarative', { instances: 10 }, async (headers, body) => {
@@ -32,7 +33,8 @@ preload('hello.declarative', { instances: 10 }, async (headers, body) => {
3233

3334
// Private helper - callable in-app only (the HTTP host answers 403 for it).
3435
preload('demo.suffix.helper', { instances: 10, isPrivate: true }, async (_headers, body) => {
35-
return { text: `${body?.text ?? ''}!`, language: 'node.js' };
36+
const text = typeof body?.text === 'string' ? body.text : '';
37+
return { text: `${text}!`, language: 'node.js' };
3638
});
3739

3840
// Local composition: a public function calls a private sibling through the bus.

‎src/actuator.ts‎

Lines changed: 74 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ import { randomUUID } from 'node:crypto';
4040
import * as http from 'node:http';
4141
import { DeliveryTimeout } from './bus.js';
4242
import { appConfig } from './config.js';
43-
import { isoUtc } from './envelope.js';
43+
import { asText, isoUtc } from './envelope.js';
4444
import { getLogger } from './log.js';
4545
import { FunctionRegistry } from './registry.js';
4646
import { VERSION } from './version.js';
@@ -51,6 +51,23 @@ const INFO_TIMEOUT_MS = 3000; // engine value for the advisory type=info lookup
5151
const HEALTH_TIMEOUT_MS = 10000; // engine value for the type=health probe
5252
const UNHEALTHY = "Unhealthy. Please check '/health' endpoint.";
5353

54+
// The engines' minimal landing page (platform-core public/index.html style);
55+
// the wrappers embed it - no static file service by design.
56+
const INDEX_HTML = `<!DOCTYPE html>
57+
<html>
58+
<body>
59+
60+
<h2>Welcome</h2>
61+
62+
<p><a href="/info">INFO endpoint</a></p>
63+
<p><a href="/info/routes">Service list</a></p>
64+
<p><a href="/env">Environment endpoint</a></p>
65+
<p><a href="/health">Health endpoint</a></p>
66+
<p><a href="/livenessprobe">Liveness probe</a></p>
67+
68+
</body>
69+
</html>`;
70+
5471
let origin: string | undefined;
5572

5673
/**
@@ -101,8 +118,8 @@ export function elapsedTime(milliseconds: number): string {
101118
/** A comma/space-separated string (engine syntax) or a YAML list. */
102119
function asList(value: unknown): string[] {
103120
const items = Array.isArray(value)
104-
? value.map((item) => String(item).trim())
105-
: String(value ?? '').split(/[,\s]+/);
121+
? value.map((item) => asText(item).trim())
122+
: asText(value ?? '').split(/[,\s]+/);
106123
return items.filter((item) => item.length > 0);
107124
}
108125

@@ -113,13 +130,27 @@ function isMessageShape(body: unknown): boolean {
113130
}
114131

115132
function sendText(res: http.ServerResponse, status: number, text: string): void {
116-
res.writeHead(status, { 'content-type': 'text/plain' });
133+
res.writeHead(status, { 'content-type': 'text/plain; charset=utf-8' });
117134
res.end(text);
118135
}
119136

120137
function sendJson(res: http.ServerResponse, status: number, body: unknown): void {
121-
const bytes = Buffer.from(JSON.stringify(body));
122-
res.writeHead(status, { 'content-type': 'application/json', 'content-length': bytes.length });
138+
// the engines' default serializer presentation: pretty-printed JSON
139+
const bytes = Buffer.from(JSON.stringify(body, null, 2));
140+
res.writeHead(status,
141+
{ 'content-type': 'application/json; charset=utf-8', 'content-length': bytes.length });
142+
res.end(bytes);
143+
}
144+
145+
/** The engines' host-level error shape (SimpleHttpUtility signature). */
146+
export function sendError(res: http.ServerResponse, status: number, message: string): void {
147+
sendJson(res, status, { status, message, type: 'error' });
148+
}
149+
150+
function sendHtml(res: http.ServerResponse, page: string): void {
151+
const bytes = Buffer.from(page);
152+
res.writeHead(200,
153+
{ 'content-type': 'text/html; charset=utf-8', 'content-length': bytes.length });
123154
res.end(bytes);
124155
}
125156

@@ -153,6 +184,9 @@ export class Actuator {
153184
/** Route a GET to its actuator endpoint; false when the path is not ours. */
154185
async handle(pathname: string, res: http.ServerResponse): Promise<boolean> {
155186
switch (pathname) {
187+
case '/':
188+
sendHtml(res, INDEX_HTML);
189+
return true;
156190
case '/info':
157191
sendJson(res, 200, this.info());
158192
return true;
@@ -240,40 +274,44 @@ export class Actuator {
240274
for (const route of services) {
241275
const entry: Record<string, unknown> = { route, required };
242276
dependency.push(entry);
243-
const service = this.registry.get(route);
244-
if (!service) {
277+
if (!await this.checkService(route, entry)) {
245278
allUp = false;
246-
entry.status_code = 404;
247-
entry.message = `Please check - Route ${route} not found`;
248-
continue;
249279
}
250-
const bus = this.registry.bus;
251-
// info is advisory - merge whatever the service reports about itself;
252-
// the health probe below decides the status
253-
try {
254-
const info = await bus.deliver(service, { type: 'info' }, null, INFO_TIMEOUT_MS);
255-
if (info.body !== null && typeof info.body === 'object' && !Array.isArray(info.body)) {
256-
Object.assign(entry, info.body);
257-
}
258-
} catch (e) {
259-
if (!(e instanceof DeliveryTimeout)) throw e;
280+
}
281+
return allUp;
282+
}
283+
284+
/** Probe one health-check function; false when it is missing or down. */
285+
private async checkService(route: string, entry: Record<string, unknown>): Promise<boolean> {
286+
const service = this.registry.get(route);
287+
if (!service) {
288+
entry.status_code = 404;
289+
entry.message = `Please check - Route ${route} not found`;
290+
return false;
291+
}
292+
const bus = this.registry.bus;
293+
// info is advisory - merge whatever the service reports about itself;
294+
// the health probe below decides the status
295+
try {
296+
const info = await bus.deliver(service, { type: 'info' }, null, INFO_TIMEOUT_MS);
297+
if (info.body !== null && typeof info.body === 'object' && !Array.isArray(info.body)) {
298+
Object.assign(entry, info.body);
260299
}
261-
try {
262-
const reply = await bus.deliver(service, { type: 'health' }, null, HEALTH_TIMEOUT_MS);
263-
entry.status_code = reply.getStatus();
264-
if (isMessageShape(reply.body)) {
265-
entry.message = reply.body;
266-
}
267-
if (reply.hasError()) {
268-
allUp = false;
269-
}
270-
} catch (e) {
271-
if (!(e instanceof DeliveryTimeout)) throw e;
272-
allUp = false;
273-
entry.status_code = 408;
274-
entry.message = `Please check - ${e.message}`;
300+
} catch (e) {
301+
if (!(e instanceof DeliveryTimeout)) throw e;
302+
}
303+
try {
304+
const reply = await bus.deliver(service, { type: 'health' }, null, HEALTH_TIMEOUT_MS);
305+
entry.status_code = reply.getStatus();
306+
if (isMessageShape(reply.body)) {
307+
entry.message = reply.body;
275308
}
309+
return !reply.hasError();
310+
} catch (e) {
311+
if (!(e instanceof DeliveryTimeout)) throw e;
312+
entry.status_code = 408;
313+
entry.message = `Please check - ${e.message}`;
314+
return false;
276315
}
277-
return allUp;
278316
}
279317
}

‎src/bus.ts‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,20 @@
1515
* deadline (the 408 envelope) instead of hoarding work.
1616
* - In-memory only; no orchestration, no flows, no persistence, no broadcast.
1717
*
18+
* Why a hand-built Mailbox instead of Node's EventEmitter: this contract is
19+
* an ANYCAST WORK QUEUE - each delivery goes to exactly one of N workers and
20+
* waits its FIFO turn while all are busy. EventEmitter is a broadcast
21+
* notifier - emit() invokes every listener synchronously and buffers
22+
* nothing - so a bounded-concurrency bus would still need this queue in
23+
* front of it (the emitter demoted to a wake-up bell), and once()-based
24+
* bridging re-registers a listener per iteration, can drop emissions
25+
* between iterations, and trips MaxListenersExceededWarning right at the
26+
* default instances=10. Bare promise waiters also hold no event-loop
27+
* handles, which is what makes the lifecycle contract exactly true (an idle
28+
* bus lets the process exit; only an in-flight RPC's deadline timer holds
29+
* it). The Mailbox is node's missing asyncio.Queue, keeping the python and
30+
* node twins structurally identical.
31+
*
1832
* The bus is internal: application code uses preload() and PostOffice, never
1933
* this module - the same way engine developers never touch the engine bus.
2034
*/
@@ -61,8 +75,8 @@ const CLOSED: unique symbol = Symbol('bus-closed');
6175

6276
/** Unbounded FIFO handing items to awaiting workers. */
6377
class Mailbox {
64-
private items: Array<Delivery | typeof CLOSED> = [];
65-
private waiters: Array<(item: Delivery | typeof CLOSED) => void> = [];
78+
private readonly items: Array<Delivery | typeof CLOSED> = [];
79+
private readonly waiters: Array<(item: Delivery | typeof CLOSED) => void> = [];
6680

6781
push(item: Delivery | typeof CLOSED): void {
6882
const waiter = this.waiters.shift();
@@ -84,7 +98,7 @@ class Mailbox {
8498

8599
/** Per-registry bus: one FIFO mailbox and N workers per registered route. */
86100
export class EventBus {
87-
private mailboxes = new Map<string, Mailbox>();
101+
private readonly mailboxes = new Map<string, Mailbox>();
88102

89103
private mailbox(service: ServiceDef): Mailbox {
90104
let mailbox = this.mailboxes.get(service.route);

‎src/cli.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ function parseArgs(argv: string[]): { app?: string; port?: number; host: string;
1515
};
1616
for (let i = 0; i < argv.length; i++) {
1717
const arg = argv[i];
18-
if (arg === '--port') result.port = parseInt(argv[++i], 10);
18+
if (arg === '--port') result.port = Number.parseInt(argv[++i], 10);
1919
else if (arg === '--host') result.host = argv[++i];
2020
else if (arg === '--config') result.config = argv[++i];
2121
else if (!arg.startsWith('-') && !result.app) result.app = arg;
@@ -61,9 +61,10 @@ async function main(): Promise<number> {
6161
return 0;
6262
}
6363

64-
main().then((code) => {
64+
try {
65+
const code = await main();
6566
if (code !== 0) process.exit(code);
66-
}).catch((e) => {
67+
} catch (e) {
6768
process.stderr.write(`${(e as Error).message}\n`);
6869
process.exit(1);
69-
});
70+
}

‎src/config.ts‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,12 @@
1616
*/
1717
import * as fs from 'node:fs';
1818
import YAML from 'yaml';
19+
import { asText } from './envelope.js';
1920

2021
const REF = /\$\{([^}]+)\}/g;
2122

23+
const WHOLE_REF = /^\$\{([^}]+)\}$/;
24+
2225
export const DEFAULT_CANDIDATES = [
2326
'resources/application.yml',
2427
'resources/application.yaml',
@@ -61,7 +64,7 @@ function parseProperties(text: string): Map<string, unknown> {
6164

6265
export class AppConfig {
6366
private store = new Map<string, unknown>();
64-
private overrides: Map<string, unknown>;
67+
private readonly overrides: Map<string, unknown>;
6568
readonly source: string;
6669

6770
constructor(path?: string, argv?: string[]) {
@@ -95,7 +98,7 @@ export class AppConfig {
9598

9699
/** Runtime override, checked first on every read (f:setConfig analog). */
97100
set(key: string, value: unknown): void {
98-
if (!key || !key.trim()) {
101+
if (!key?.trim()) {
99102
throw new Error('Config key must not be empty');
100103
}
101104
this.overrides.set(key, value);
@@ -112,22 +115,22 @@ export class AppConfig {
112115

113116
getProperty(key: string, defaultValue?: string): string | undefined {
114117
const value = this.get(key, defaultValue);
115-
return value === undefined || value === null ? undefined : String(value);
118+
return value === undefined || value === null ? undefined : asText(value);
116119
}
117120

118121
exists(key: string): boolean {
119122
return this.overrides.has(key) || this.store.has(key);
120123
}
121124

122125
private substitute(value: string, defaultValue: unknown): unknown {
123-
const whole = value.trim().match(/^\$\{([^}]+)\}$/);
126+
const whole = WHOLE_REF.exec(value.trim());
124127
if (whole) {
125128
const resolved = this.resolveRef(whole[1]);
126129
return resolved === undefined ? defaultValue : resolved;
127130
}
128131
return value.replace(REF, (_m, ref: string) => {
129132
const resolved = this.resolveRef(ref);
130-
return resolved === undefined || resolved === null ? '' : String(resolved);
133+
return resolved === undefined || resolved === null ? '' : asText(resolved);
131134
});
132135
}
133136

@@ -151,7 +154,7 @@ let instance: AppConfig | undefined;
151154

152155
/** The shared AppConfig singleton (created on first use). */
153156
export function appConfig(): AppConfig {
154-
if (!instance) instance = new AppConfig();
157+
instance ??= new AppConfig();
155158
return instance;
156159
}
157160

0 commit comments

Comments
 (0)