Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
54b35e5
chore: refresh LICENSE copyright years (2018-2026)
acn-ericlaw Aug 24, 2026
50485d0
chore: pin tsconfig types to ['node'] for deterministic editor resolu…
acn-ericlaw Aug 24, 2026
26bb182
chore: mark construction-only fields readonly (Sonar S2933)
acn-ericlaw Aug 24, 2026
d35fc29
chore: prefer Number.parseInt over the global (Sonar S7773)
acn-ericlaw Aug 24, 2026
72e2aef
chore: config.ts Sonar batch - readonly, optional chain, ??=, exec, n…
acn-ericlaw Aug 24, 2026
0c22cde
chore: fromMap under the cognitive-complexity bar (Sonar S3776) + hon…
acn-ericlaw Aug 24, 2026
1554cb1
chore: log call-site probe carries an Error message (S7722); linear-t…
acn-ericlaw Aug 24, 2026
8f927a7
chore: Handler returns honest 'unknown' (Sonar S6571) - the union was…
acn-ericlaw Aug 24, 2026
6a72ff8
chore: split composite test assertions (Sonar S9073) - failures name …
acn-ericlaw Aug 24, 2026
f95ea43
chore: demo validates text is a string (Sonar S6551 x2) - no default …
acn-ericlaw Aug 24, 2026
f1849f2
chore: Sonar batch 2 - complexity, top-level await, shared asText, li…
acn-ericlaw Aug 24, 2026
f2bc7d6
chore: asText narrows positively (Sonar S6551, final) - typeof negati…
acn-ericlaw Aug 24, 2026
40876ed
docs: bus.ts header records why the Mailbox is hand-built, not EventE…
acn-ericlaw Aug 24, 2026
956c706
feat: engine-parity host polish - index page, pretty JSON, engine err…
acn-ericlaw Aug 24, 2026
a73332f
chore: node content types carry charset=utf-8, matching the python twin
acn-ericlaw Aug 24, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@

## 0.1.0 (unreleased)

- Host polish for engine parity: `GET /` serves the engines' minimal index page linking
the actuator endpoints (embedded - no static file service by design); actuator JSON
responses are pretty-printed (the engines' default-serializer presentation); unknown
paths and non-GET methods answer the engines' error shape
`{"status": 404, "message": "Resource not found", "type": "error"}`.
- Actuator endpoints `/info`, `/info/routes`, `/env`, `/health` and `/livenessprobe` -
the engines' operational surface, for Kubernetes probes and one-dashboard monitoring
of polyglot installations. Health check functions are normal registered functions
Expand Down
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@
same "printed page" as the copyright notice for easier
identification within third-party archives.

Copyright 2018 - 2025 Accenture.
Copyright 2018-2026 Accenture.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ Kubernetes probes and dashboards treat a Node.js app exactly like a Java or Rust

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

JSON responses are pretty-printed — the engines' default-serializer presentation — and
unknown paths answer the engines' error shape
(`{"status": 404, "message": "Resource not found", "type": "error"}`).

Kubernetes wiring: point `livenessProbe` at `/livenessprobe` and `readinessProbe` at
`/health`.

Expand Down
10 changes: 6 additions & 4 deletions examples/demo-app.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,13 @@ import { AppException, annotateTrace, getLogger, preload } from '../dist/src/ind
const log = getLogger('demo-app');

preload('hello.node', { instances: 10 }, async (headers, body) => {
if (typeof body !== 'object' || body === null || !('text' in body)) {
if (typeof body !== 'object' || body === null
|| !('text' in body) || typeof body.text !== 'string') {
throw new AppException(400, "missing 'text'");
}
annotateTrace('language', 'node.js');
log.info(`Transforming text of length ${String(body.text).length}`);
return { text: String(body.text).toUpperCase(), language: 'node.js' };
log.info(`Transforming text of length ${body.text.length}`);
return { text: body.text.toUpperCase(), language: 'node.js' };
});

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

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

// Local composition: a public function calls a private sibling through the bus.
Expand Down
110 changes: 74 additions & 36 deletions src/actuator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ import { randomUUID } from 'node:crypto';
import * as http from 'node:http';
import { DeliveryTimeout } from './bus.js';
import { appConfig } from './config.js';
import { isoUtc } from './envelope.js';
import { asText, isoUtc } from './envelope.js';
import { getLogger } from './log.js';
import { FunctionRegistry } from './registry.js';
import { VERSION } from './version.js';
Expand All @@ -51,6 +51,23 @@ const INFO_TIMEOUT_MS = 3000; // engine value for the advisory type=info lookup
const HEALTH_TIMEOUT_MS = 10000; // engine value for the type=health probe
const UNHEALTHY = "Unhealthy. Please check '/health' endpoint.";

// The engines' minimal landing page (platform-core public/index.html style);
// the wrappers embed it - no static file service by design.
const INDEX_HTML = `<!DOCTYPE html>
<html>
<body>
<h2>Welcome</h2>
<p><a href="/info">INFO endpoint</a></p>
<p><a href="/info/routes">Service list</a></p>
<p><a href="/env">Environment endpoint</a></p>
<p><a href="/health">Health endpoint</a></p>
<p><a href="/livenessprobe">Liveness probe</a></p>
</body>
</html>`;

let origin: string | undefined;

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

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

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

function sendJson(res: http.ServerResponse, status: number, body: unknown): void {
const bytes = Buffer.from(JSON.stringify(body));
res.writeHead(status, { 'content-type': 'application/json', 'content-length': bytes.length });
// the engines' default serializer presentation: pretty-printed JSON
const bytes = Buffer.from(JSON.stringify(body, null, 2));
res.writeHead(status,
{ 'content-type': 'application/json; charset=utf-8', 'content-length': bytes.length });
res.end(bytes);
}

/** The engines' host-level error shape (SimpleHttpUtility signature). */
export function sendError(res: http.ServerResponse, status: number, message: string): void {
sendJson(res, status, { status, message, type: 'error' });
}

function sendHtml(res: http.ServerResponse, page: string): void {
const bytes = Buffer.from(page);
res.writeHead(200,
{ 'content-type': 'text/html; charset=utf-8', 'content-length': bytes.length });
res.end(bytes);
}

Expand Down Expand Up @@ -153,6 +184,9 @@ export class Actuator {
/** Route a GET to its actuator endpoint; false when the path is not ours. */
async handle(pathname: string, res: http.ServerResponse): Promise<boolean> {
switch (pathname) {
case '/':
sendHtml(res, INDEX_HTML);
return true;
case '/info':
sendJson(res, 200, this.info());
return true;
Expand Down Expand Up @@ -240,40 +274,44 @@ export class Actuator {
for (const route of services) {
const entry: Record<string, unknown> = { route, required };
dependency.push(entry);
const service = this.registry.get(route);
if (!service) {
if (!await this.checkService(route, entry)) {
allUp = false;
entry.status_code = 404;
entry.message = `Please check - Route ${route} not found`;
continue;
}
const bus = this.registry.bus;
// info is advisory - merge whatever the service reports about itself;
// the health probe below decides the status
try {
const info = await bus.deliver(service, { type: 'info' }, null, INFO_TIMEOUT_MS);
if (info.body !== null && typeof info.body === 'object' && !Array.isArray(info.body)) {
Object.assign(entry, info.body);
}
} catch (e) {
if (!(e instanceof DeliveryTimeout)) throw e;
}
return allUp;
}

/** Probe one health-check function; false when it is missing or down. */
private async checkService(route: string, entry: Record<string, unknown>): Promise<boolean> {
const service = this.registry.get(route);
if (!service) {
entry.status_code = 404;
entry.message = `Please check - Route ${route} not found`;
return false;
}
const bus = this.registry.bus;
// info is advisory - merge whatever the service reports about itself;
// the health probe below decides the status
try {
const info = await bus.deliver(service, { type: 'info' }, null, INFO_TIMEOUT_MS);
if (info.body !== null && typeof info.body === 'object' && !Array.isArray(info.body)) {
Object.assign(entry, info.body);
}
try {
const reply = await bus.deliver(service, { type: 'health' }, null, HEALTH_TIMEOUT_MS);
entry.status_code = reply.getStatus();
if (isMessageShape(reply.body)) {
entry.message = reply.body;
}
if (reply.hasError()) {
allUp = false;
}
} catch (e) {
if (!(e instanceof DeliveryTimeout)) throw e;
allUp = false;
entry.status_code = 408;
entry.message = `Please check - ${e.message}`;
} catch (e) {
if (!(e instanceof DeliveryTimeout)) throw e;
}
try {
const reply = await bus.deliver(service, { type: 'health' }, null, HEALTH_TIMEOUT_MS);
entry.status_code = reply.getStatus();
if (isMessageShape(reply.body)) {
entry.message = reply.body;
}
return !reply.hasError();
} catch (e) {
if (!(e instanceof DeliveryTimeout)) throw e;
entry.status_code = 408;
entry.message = `Please check - ${e.message}`;
return false;
}
return allUp;
}
}
20 changes: 17 additions & 3 deletions src/bus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,20 @@
* deadline (the 408 envelope) instead of hoarding work.
* - In-memory only; no orchestration, no flows, no persistence, no broadcast.
*
* Why a hand-built Mailbox instead of Node's EventEmitter: this contract is
* an ANYCAST WORK QUEUE - each delivery goes to exactly one of N workers and
* waits its FIFO turn while all are busy. EventEmitter is a broadcast
* notifier - emit() invokes every listener synchronously and buffers
* nothing - so a bounded-concurrency bus would still need this queue in
* front of it (the emitter demoted to a wake-up bell), and once()-based
* bridging re-registers a listener per iteration, can drop emissions
* between iterations, and trips MaxListenersExceededWarning right at the
* default instances=10. Bare promise waiters also hold no event-loop
* handles, which is what makes the lifecycle contract exactly true (an idle
* bus lets the process exit; only an in-flight RPC's deadline timer holds
* it). The Mailbox is node's missing asyncio.Queue, keeping the python and
* node twins structurally identical.
*
* The bus is internal: application code uses preload() and PostOffice, never
* this module - the same way engine developers never touch the engine bus.
*/
Expand Down Expand Up @@ -61,8 +75,8 @@ const CLOSED: unique symbol = Symbol('bus-closed');

/** Unbounded FIFO handing items to awaiting workers. */
class Mailbox {
private items: Array<Delivery | typeof CLOSED> = [];
private waiters: Array<(item: Delivery | typeof CLOSED) => void> = [];
private readonly items: Array<Delivery | typeof CLOSED> = [];
private readonly waiters: Array<(item: Delivery | typeof CLOSED) => void> = [];

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

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

private mailbox(service: ServiceDef): Mailbox {
let mailbox = this.mailboxes.get(service.route);
Expand Down
9 changes: 5 additions & 4 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ function parseArgs(argv: string[]): { app?: string; port?: number; host: string;
};
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === '--port') result.port = parseInt(argv[++i], 10);
if (arg === '--port') result.port = Number.parseInt(argv[++i], 10);
else if (arg === '--host') result.host = argv[++i];
else if (arg === '--config') result.config = argv[++i];
else if (!arg.startsWith('-') && !result.app) result.app = arg;
Expand Down Expand Up @@ -61,9 +61,10 @@ async function main(): Promise<number> {
return 0;
}

main().then((code) => {
try {
const code = await main();
if (code !== 0) process.exit(code);
}).catch((e) => {
} catch (e) {
process.stderr.write(`${(e as Error).message}\n`);
process.exit(1);
});
}
15 changes: 9 additions & 6 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,12 @@
*/
import * as fs from 'node:fs';
import YAML from 'yaml';
import { asText } from './envelope.js';

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

const WHOLE_REF = /^\$\{([^}]+)\}$/;

export const DEFAULT_CANDIDATES = [
'resources/application.yml',
'resources/application.yaml',
Expand Down Expand Up @@ -61,7 +64,7 @@ function parseProperties(text: string): Map<string, unknown> {

export class AppConfig {
private store = new Map<string, unknown>();
private overrides: Map<string, unknown>;
private readonly overrides: Map<string, unknown>;
readonly source: string;

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

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

getProperty(key: string, defaultValue?: string): string | undefined {
const value = this.get(key, defaultValue);
return value === undefined || value === null ? undefined : String(value);
return value === undefined || value === null ? undefined : asText(value);
}

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

private substitute(value: string, defaultValue: unknown): unknown {
const whole = value.trim().match(/^\$\{([^}]+)\}$/);
const whole = WHOLE_REF.exec(value.trim());
if (whole) {
const resolved = this.resolveRef(whole[1]);
return resolved === undefined ? defaultValue : resolved;
}
return value.replace(REF, (_m, ref: string) => {
const resolved = this.resolveRef(ref);
return resolved === undefined || resolved === null ? '' : String(resolved);
return resolved === undefined || resolved === null ? '' : asText(resolved);
});
}

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

/** The shared AppConfig singleton (created on first use). */
export function appConfig(): AppConfig {
if (!instance) instance = new AppConfig();
instance ??= new AppConfig();
return instance;
}

Expand Down
Loading
Loading