tina4-nodejs 3.13.157 → 3.13.159
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/CLAUDE.md +4 -3
- package/package.json +3 -3
- package/packages/cli/dist/bin.js +1384 -639
- package/packages/cli/src/commands/generate.ts +72 -23
- package/packages/core/dist/index.js +1393 -639
- package/packages/core/public/bundled-component-provenance.json +2 -2
- package/packages/core/public/js/frond.js +26 -7
- package/packages/core/public/js/frond.min.js +1 -1
- package/packages/core/src/index.ts +18 -0
- package/packages/core/src/middleware.ts +10 -4
- package/packages/core/src/queue.ts +42 -32
- package/packages/core/src/queueBackends/kafkaBackend.ts +687 -544
- package/packages/core/src/server.ts +41 -4
- package/packages/core/src/tcp.ts +484 -0
- package/packages/frond/dist/index.js +118 -4
- package/packages/frond/src/engine.ts +87 -8
- package/packages/frond/src/index.ts +1 -1
- package/packages/orm/dist/index.js +1386 -641
- package/packages/orm/src/migration.ts +34 -0
- package/packages/orm/src/queryBuilder.ts +38 -0
- package/types/core/src/index.d.ts +2 -0
- package/types/core/src/queue.d.ts +1 -1
- package/types/core/src/queueBackends/kafkaBackend.d.ts +48 -54
- package/types/core/src/tcp.d.ts +165 -0
- package/types/frond/src/engine.d.ts +9 -0
- package/types/frond/src/index.d.ts +1 -1
- package/types/orm/src/migration.d.ts +0 -24
- package/types/orm/src/queryBuilder.d.ts +28 -0
|
@@ -48,11 +48,12 @@ import { generateNonce, runWithCspNonce, currentCspNonce } from "./csp.js";
|
|
|
48
48
|
import { createHealthRoutes } from "./health.js";
|
|
49
49
|
import { rateLimiter } from "./rateLimiter.js";
|
|
50
50
|
import { Log } from "./logger.js";
|
|
51
|
-
import { DevAdmin, RequestInspector, WsTracker, devRequestDenial, devHostAllowed, devToolbarAllowed } from "./devAdmin.js";
|
|
51
|
+
import { DevAdmin, RequestInspector, WsTracker, devRequestDenial, devHostAllowed, devPeerAllowed, devToolbarAllowed } from "./devAdmin.js";
|
|
52
52
|
import { CLOSE_GOING_AWAY, devReloadWs, serveWebSocketRoute, wsRouteManager } from "./websocket.js";
|
|
53
53
|
import { feedbackEnabled, injectFeedbackWidget } from "./feedback.js";
|
|
54
54
|
import { I18n } from "./i18n.js";
|
|
55
55
|
import { stopAllBackgroundTasks } from "./background.js";
|
|
56
|
+
import { startAllTcpServices, stopAcceptingAllTcpServices, drainAllTcpServices } from "./tcp.js";
|
|
56
57
|
import { TINA4_VERSION } from "./version.js";
|
|
57
58
|
|
|
58
59
|
const __filename = fileURLToPath(import.meta.url);
|
|
@@ -1129,6 +1130,25 @@ async function invokeRouteHandler(
|
|
|
1129
1130
|
* other shape - a handler that already wrote, no template, null/undefined, a
|
|
1130
1131
|
* string, a Buffer - is left exactly as it was.
|
|
1131
1132
|
*/
|
|
1133
|
+
/**
|
|
1134
|
+
* Coerce a handler's RETURN value into a response (#289).
|
|
1135
|
+
*
|
|
1136
|
+
* Node's idiom is `res.json()` / `res.send()`, but a handler that `return`s a
|
|
1137
|
+
* dict / array / string without writing used to answer an empty 200 with no
|
|
1138
|
+
* error and no log line — the value was dropped. This mirrors the Python, PHP
|
|
1139
|
+
* and Ruby masters, which coerce a bare return: a non-null, non-undefined
|
|
1140
|
+
* return is run through the auto-detecting `response()` callable (`res` itself),
|
|
1141
|
+
* so `return { open: 3 }` serialises to JSON. It is skipped when the handler
|
|
1142
|
+
* already sent (a template render, `res.json()`, a stream) or returned nothing,
|
|
1143
|
+
* so an explicit `res.json(...)` is never double-sent.
|
|
1144
|
+
*/
|
|
1145
|
+
function coerceHandlerResult(res: Tina4Response, result: unknown): void {
|
|
1146
|
+
if (res.raw.writableEnded || res.raw.headersSent) return;
|
|
1147
|
+
if (result === undefined || result === null) return;
|
|
1148
|
+
if (result === (res as unknown)) return; // handler returned the response itself
|
|
1149
|
+
(res as unknown as (data: unknown) => void)(result);
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1132
1152
|
async function renderIfTemplateRoute(
|
|
1133
1153
|
match: { template?: string },
|
|
1134
1154
|
res: Tina4Response,
|
|
@@ -1200,7 +1220,9 @@ async function runMatchedRoute(ctx: MatchedRouteContext): Promise<void> {
|
|
|
1200
1220
|
}
|
|
1201
1221
|
|
|
1202
1222
|
if (!handlerSkipped) {
|
|
1203
|
-
|
|
1223
|
+
const result = await invokeRouteHandler(match, req, res);
|
|
1224
|
+
await renderIfTemplateRoute(match, res, result);
|
|
1225
|
+
coerceHandlerResult(res, result);
|
|
1204
1226
|
}
|
|
1205
1227
|
|
|
1206
1228
|
// Global afterX hooks (logging / post-processing), over EVERY global
|
|
@@ -2320,8 +2342,9 @@ export async function startServer(config?: Tina4Config): Promise<{
|
|
|
2320
2342
|
const upPath = (req.url ?? "/").split("?")[0];
|
|
2321
2343
|
// Dev-reload channel (debug only).
|
|
2322
2344
|
if (isDevMode() && upPath === "/__dev_reload") {
|
|
2323
|
-
// ADR-0082: the reload socket answers only a loopback / TINA4_HOST Host
|
|
2324
|
-
|
|
2345
|
+
// ADR-0082: the reload socket answers only a loopback / TINA4_HOST Host,
|
|
2346
|
+
// from a raw socket peer the /__dev HTTP gate would also let in.
|
|
2347
|
+
if (!devHostAllowed(req.headers.host) || !devPeerAllowed(socket.remoteAddress)) {
|
|
2325
2348
|
try { socket.write("HTTP/1.1 403 Forbidden\r\n\r\n"); socket.destroy(); } catch { /* gone */ }
|
|
2326
2349
|
return;
|
|
2327
2350
|
}
|
|
@@ -2359,6 +2382,12 @@ export async function startServer(config?: Tina4Config): Promise<{
|
|
|
2359
2382
|
// promise resolves (a client can then rely on both families being up).
|
|
2360
2383
|
const siblingServers = await startLoopbackSiblings(port, host, dispatch);
|
|
2361
2384
|
|
|
2385
|
+
// Raw TCP services (feature 142, ADR-0102 D1) bind on THIS event loop,
|
|
2386
|
+
// beside the HTTP server — one process serves both the device gateway and
|
|
2387
|
+
// its dashboard. Each binds its own port; a worker that finds the port
|
|
2388
|
+
// already bound skips silently (single-owner). Drained on shutdown below.
|
|
2389
|
+
await startAllTcpServices(host);
|
|
2390
|
+
|
|
2362
2391
|
const displayHost = host === "0.0.0.0" ? "localhost" : host;
|
|
2363
2392
|
const isDebug = isTruthy(process.env.TINA4_DEBUG);
|
|
2364
2393
|
const logLevel = (process.env.TINA4_LOG_LEVEL ?? "DEBUG").toUpperCase();
|
|
@@ -2544,6 +2573,11 @@ ${reset}
|
|
|
2544
2573
|
Log.info(`Closed ${wsClosed} WebSocket connection(s) with 1001 going away`);
|
|
2545
2574
|
}
|
|
2546
2575
|
|
|
2576
|
+
// Raw TCP services stop accepting and drain their live device
|
|
2577
|
+
// connections (firing on_close) alongside the HTTP/WebSocket drain.
|
|
2578
|
+
stopAcceptingAllTcpServices();
|
|
2579
|
+
await drainAllTcpServices();
|
|
2580
|
+
|
|
2547
2581
|
// Race the drain against the shutdown budget. Whatever is still in
|
|
2548
2582
|
// flight when the budget expires gets force-closed: SIGKILL is what
|
|
2549
2583
|
// arrives next, so a bounded drain is strictly better than an
|
|
@@ -2612,6 +2646,9 @@ ${reset}
|
|
|
2612
2646
|
process.off("SIGINT", onSigint);
|
|
2613
2647
|
// Clear any registered background timers so graceful shutdown actually exits.
|
|
2614
2648
|
stopAllBackgroundTasks();
|
|
2649
|
+
// Release raw TCP listeners + connections on an explicit close() too.
|
|
2650
|
+
stopAcceptingAllTcpServices();
|
|
2651
|
+
void drainAllTcpServices();
|
|
2615
2652
|
if (aiServer) aiServer.close();
|
|
2616
2653
|
server.close();
|
|
2617
2654
|
// Sibling loopback listeners share the port — close them alongside the
|
|
@@ -0,0 +1,484 @@
|
|
|
1
|
+
// Copyright (c) 2026 Code Infinity
|
|
2
|
+
// SPDX-License-Identifier: MPL-2.0
|
|
3
|
+
// This Source Code Form is subject to the terms of the Mozilla Public
|
|
4
|
+
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
5
|
+
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Raw TCP service — a user-facing, non-HTTP, long-lived binary TCP listener.
|
|
9
|
+
*
|
|
10
|
+
* Governed by ADR-0102 (feature 142), and the Python reference tina4_python/tcp.
|
|
11
|
+
* A Tina4 app exposes its own protocol — a GPS/GPRS car-tracker gateway
|
|
12
|
+
* (GT06/TK103/Concox/Teltonika) is the driving case — in the SAME process as its
|
|
13
|
+
* HTTP dashboard, reusing config, logging, ORM and queue.
|
|
14
|
+
*
|
|
15
|
+
* const svc = tcpService(5023, {
|
|
16
|
+
* onData(conn, data) {
|
|
17
|
+
* const frame = parse(data); // the APP frames the stream
|
|
18
|
+
* if (frame.isLogin) conn.identify(frame.imei);
|
|
19
|
+
* conn.send(ackFor(frame)); // ACK on the same socket
|
|
20
|
+
* },
|
|
21
|
+
* });
|
|
22
|
+
*
|
|
23
|
+
* // server -> device push from an HTTP route:
|
|
24
|
+
* tcp("trackers").sendTo(imei, buildCommand("set_interval", 30));
|
|
25
|
+
*
|
|
26
|
+
* The listener runs on the SAME event loop as the HTTP server (D1 in-process),
|
|
27
|
+
* via `net.createServer`. The framework owns the socket hard-parts: lifecycle,
|
|
28
|
+
* max_connections refusal, an idle reaper (default OFF for long-lived device
|
|
29
|
+
* sockets), graceful-shutdown drain, bounded write backpressure, and
|
|
30
|
+
* single-owner bind under N workers.
|
|
31
|
+
*
|
|
32
|
+
* Non-goals in v1 (ADR-0102): no CRC/length framing helper beyond on_line, no
|
|
33
|
+
* TLS termination, no UDP, no replacement for the WebSocket surface.
|
|
34
|
+
*/
|
|
35
|
+
import { createServer, type Server, type Socket } from "node:net";
|
|
36
|
+
import { randomUUID } from "node:crypto";
|
|
37
|
+
import { Log } from "./logger.js";
|
|
38
|
+
|
|
39
|
+
/** A stalled reader is dropped once this many bytes are queued unsent. */
|
|
40
|
+
const DEFAULT_MAX_BACKLOG = 1 << 20; // 1 MiB
|
|
41
|
+
|
|
42
|
+
export type TcpConnectHandler = (conn: TcpConnection) => void | Promise<void>;
|
|
43
|
+
export type TcpDataHandler = (conn: TcpConnection, data: Buffer) => void | Promise<void>;
|
|
44
|
+
export type TcpCloseHandler = (conn: TcpConnection) => void | Promise<void>;
|
|
45
|
+
export type TcpLineHandler = (conn: TcpConnection, line: Buffer) => void | Promise<void>;
|
|
46
|
+
|
|
47
|
+
export interface TcpServiceOptions {
|
|
48
|
+
name?: string;
|
|
49
|
+
onConnect?: TcpConnectHandler;
|
|
50
|
+
onData?: TcpDataHandler;
|
|
51
|
+
onClose?: TcpCloseHandler;
|
|
52
|
+
onLine?: TcpLineHandler;
|
|
53
|
+
/** Seconds; 0 (default) disables the idle reaper (device sockets are long-lived). */
|
|
54
|
+
idleTimeout?: number;
|
|
55
|
+
/** The (N+1)th connection past this is refused; unset = unbounded. */
|
|
56
|
+
maxConnections?: number;
|
|
57
|
+
/** Per-connection outstanding-write ceiling in bytes (default TINA4_TCP_MAX_BACKLOG or 1 MiB). */
|
|
58
|
+
maxBacklog?: number;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function resolveMaxBacklog(explicit?: number): number {
|
|
62
|
+
if (explicit !== undefined) return explicit > 0 ? explicit : DEFAULT_MAX_BACKLOG;
|
|
63
|
+
const raw = (process.env.TINA4_TCP_MAX_BACKLOG ?? "").trim();
|
|
64
|
+
if (raw === "") return DEFAULT_MAX_BACKLOG;
|
|
65
|
+
const value = Number.parseInt(raw, 10);
|
|
66
|
+
return Number.isFinite(value) && value > 0 ? value : DEFAULT_MAX_BACKLOG;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* One live TCP connection — the uniform connection object (ADR-0102 D5). The
|
|
71
|
+
* SAME surface exists in all four frameworks so the primitive ports.
|
|
72
|
+
*/
|
|
73
|
+
export class TcpConnection {
|
|
74
|
+
/** The registry id (the IMEI), or null until identify() is called. */
|
|
75
|
+
id: string | null = null;
|
|
76
|
+
/** Per-connection mutable state bag — the app's parse buffer, auth flag. */
|
|
77
|
+
context: Record<string, unknown> = {};
|
|
78
|
+
/** The raw TCP peer address ("127.0.0.1:54321"), never a forwarded header. */
|
|
79
|
+
readonly remoteAddr: string;
|
|
80
|
+
|
|
81
|
+
lastActivity = Date.now();
|
|
82
|
+
lineBuffer: Buffer = Buffer.alloc(0);
|
|
83
|
+
|
|
84
|
+
private closed = false;
|
|
85
|
+
private closeFired = false;
|
|
86
|
+
|
|
87
|
+
constructor(
|
|
88
|
+
readonly socket: Socket,
|
|
89
|
+
private readonly service: TcpService,
|
|
90
|
+
) {
|
|
91
|
+
this.remoteAddr = `${socket.remoteAddress ?? ""}:${socket.remotePort ?? 0}`;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
get isClosed(): boolean {
|
|
95
|
+
return this.closed;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Register this live connection under an app-chosen id (the IMEI). A second
|
|
100
|
+
* connection identifying with the same id SUPERSEDES the first in the
|
|
101
|
+
* registry — exactly a device that dropped and reconnected.
|
|
102
|
+
*/
|
|
103
|
+
identify(appId: string | number): this {
|
|
104
|
+
this.id = String(appId);
|
|
105
|
+
this.service._registerId(this.id, this);
|
|
106
|
+
return this;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Write raw bytes to THIS socket. Returns true when queued/sent, false when
|
|
111
|
+
* the connection is closed or dropped for backpressure. A stalled reader
|
|
112
|
+
* (never draining) is bounded: once more than the service's maxBacklog bytes
|
|
113
|
+
* are outstanding, the connection is dropped rather than buffered without end
|
|
114
|
+
* (mirrors the WebSocket TINA4_WS_MAX_BACKLOG posture).
|
|
115
|
+
*/
|
|
116
|
+
send(data: Buffer | string): boolean {
|
|
117
|
+
if (this.closed) return false;
|
|
118
|
+
const buffer = typeof data === "string" ? Buffer.from(data) : data;
|
|
119
|
+
this.socket.write(buffer);
|
|
120
|
+
if (this.socket.writableLength > this.service.maxBacklog) {
|
|
121
|
+
Log.warning(
|
|
122
|
+
`tcp_service '${this.service.name}': dropping a stalled reader — ` +
|
|
123
|
+
`${this.socket.writableLength} bytes queued exceeds the ` +
|
|
124
|
+
`${this.service.maxBacklog}-byte backlog limit`,
|
|
125
|
+
);
|
|
126
|
+
this.close();
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
return true;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Close this connection. on_close fires exactly once (from the socket's close
|
|
134
|
+
* event) and the registry entry is removed.
|
|
135
|
+
*/
|
|
136
|
+
close(): void {
|
|
137
|
+
if (this.closed) return;
|
|
138
|
+
this.closed = true;
|
|
139
|
+
// Send FIN first so the peer sees a clean EOF, THEN fully tear down (which
|
|
140
|
+
// fires the socket "close" event -> on_close). A bare destroy() can surface
|
|
141
|
+
// as RST on Linux, which the peer reads as an error rather than end-of-stream,
|
|
142
|
+
// so the client never observes the connection closing.
|
|
143
|
+
try {
|
|
144
|
+
this.socket.end(() => this.socket.destroy());
|
|
145
|
+
} catch {
|
|
146
|
+
this.socket.destroy();
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** @internal mark activity for the idle reaper. */
|
|
151
|
+
_touch(): void {
|
|
152
|
+
this.lastActivity = Date.now();
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** @internal fire on_close exactly once (called from the service removal path). */
|
|
156
|
+
_fireClose(): void {
|
|
157
|
+
if (this.closeFired) return;
|
|
158
|
+
this.closeFired = true;
|
|
159
|
+
this.closed = true;
|
|
160
|
+
const handler = this.service._callbacks.onClose;
|
|
161
|
+
if (!handler) return;
|
|
162
|
+
try {
|
|
163
|
+
void Promise.resolve(handler(this)).catch((error: unknown) => {
|
|
164
|
+
Log.error(`tcp_service '${this.service.name}' onClose error: ${String(error)}`);
|
|
165
|
+
});
|
|
166
|
+
} catch (error) {
|
|
167
|
+
Log.error(`tcp_service '${this.service.name}' onClose error: ${String(error)}`);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** A named raw TCP listener and its connection registry (ADR-0102). */
|
|
173
|
+
export class TcpService {
|
|
174
|
+
readonly name: string;
|
|
175
|
+
readonly port: number;
|
|
176
|
+
readonly maxBacklog: number;
|
|
177
|
+
/** @internal the callback bag, read by TcpConnection. */
|
|
178
|
+
readonly _callbacks: Required<Pick<TcpServiceOptions, never>> & {
|
|
179
|
+
onConnect?: TcpConnectHandler;
|
|
180
|
+
onData?: TcpDataHandler;
|
|
181
|
+
onClose?: TcpCloseHandler;
|
|
182
|
+
onLine?: TcpLineHandler;
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
private readonly idleTimeout: number;
|
|
186
|
+
private readonly maxConnections: number | null;
|
|
187
|
+
private readonly connections = new Set<TcpConnection>();
|
|
188
|
+
private readonly byId = new Map<string, TcpConnection>();
|
|
189
|
+
private server: Server | null = null;
|
|
190
|
+
private owner = false;
|
|
191
|
+
private boundPortValue: number | null = null;
|
|
192
|
+
private reaper: NodeJS.Timeout | null = null;
|
|
193
|
+
|
|
194
|
+
constructor(port: number, options: TcpServiceOptions = {}) {
|
|
195
|
+
this.port = port;
|
|
196
|
+
this.name = options.name ?? "default";
|
|
197
|
+
this._callbacks = {
|
|
198
|
+
onConnect: options.onConnect,
|
|
199
|
+
onData: options.onData,
|
|
200
|
+
onClose: options.onClose,
|
|
201
|
+
onLine: options.onLine,
|
|
202
|
+
};
|
|
203
|
+
// Default OFF: tracker sockets are deliberately long-lived and mostly idle
|
|
204
|
+
// between location packets, so a default reaper would kill healthy devices.
|
|
205
|
+
this.idleTimeout = options.idleTimeout ?? 0;
|
|
206
|
+
this.maxConnections = options.maxConnections ?? null;
|
|
207
|
+
this.maxBacklog = resolveMaxBacklog(options.maxBacklog);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
get isOwner(): boolean {
|
|
211
|
+
return this.owner;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** The port actually bound (resolves an ephemeral port=0 to the real one). */
|
|
215
|
+
get boundPort(): number {
|
|
216
|
+
return this.boundPortValue ?? this.port;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
count(): number {
|
|
220
|
+
return this.connections.size;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// ── Registry (D4 — server -> device push) ──────────────────────────────────
|
|
224
|
+
|
|
225
|
+
/** @internal */
|
|
226
|
+
_registerId(appId: string, conn: TcpConnection): void {
|
|
227
|
+
this.byId.set(appId, conn); // supersede: the live reconnection wins
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** The live connection for an app id, or null if unknown or closed. */
|
|
231
|
+
connection(appId: string | number): TcpConnection | null {
|
|
232
|
+
const conn = this.byId.get(String(appId));
|
|
233
|
+
if (!conn || conn.isClosed) return null;
|
|
234
|
+
return conn;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Write bytes to exactly the connection identified by appId. A send to an
|
|
239
|
+
* unknown or closed id is a NO-OP that returns false — never a throw.
|
|
240
|
+
*/
|
|
241
|
+
sendTo(appId: string | number, data: Buffer | string): boolean {
|
|
242
|
+
const conn = this.connection(appId);
|
|
243
|
+
if (!conn) return false;
|
|
244
|
+
return conn.send(data);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Write bytes to every live connection. Returns how many received it. */
|
|
248
|
+
broadcast(data: Buffer | string): number {
|
|
249
|
+
let delivered = 0;
|
|
250
|
+
for (const conn of [...this.connections]) {
|
|
251
|
+
if (conn.send(data)) delivered += 1;
|
|
252
|
+
}
|
|
253
|
+
return delivered;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// ── Lifecycle ───────────────────────────────────────────────────────────────
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Bind the listener on host:port on the event loop. SO_REUSEPORT is OFF, so
|
|
260
|
+
* under a multi-worker deployment exactly ONE worker wins the bind; a worker
|
|
261
|
+
* that finds the port already bound skips silently (single-owner, D1).
|
|
262
|
+
* Resolves true when THIS call bound the port.
|
|
263
|
+
*/
|
|
264
|
+
start(host = "0.0.0.0"): Promise<boolean> {
|
|
265
|
+
if (this.server) return Promise.resolve(this.owner);
|
|
266
|
+
return new Promise((resolve) => {
|
|
267
|
+
const server = createServer((socket) => this.handleConnection(socket));
|
|
268
|
+
this.server = server;
|
|
269
|
+
const onError = (error: NodeJS.ErrnoException): void => {
|
|
270
|
+
if (error.code === "EADDRINUSE" || error.code === "EADDRNOTAVAIL") {
|
|
271
|
+
this.owner = false;
|
|
272
|
+
this.server = null;
|
|
273
|
+
Log.info(
|
|
274
|
+
`tcp_service '${this.name}' port ${this.port} is already bound by another worker — ` +
|
|
275
|
+
`single-owner, this worker will not bind (${error.code})`,
|
|
276
|
+
);
|
|
277
|
+
resolve(false);
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
Log.error(`tcp_service '${this.name}' failed to start: ${error.message}`);
|
|
281
|
+
this.server = null;
|
|
282
|
+
resolve(false);
|
|
283
|
+
};
|
|
284
|
+
server.once("error", onError);
|
|
285
|
+
server.listen(this.port, host, () => {
|
|
286
|
+
server.off("error", onError);
|
|
287
|
+
server.on("error", (error) => Log.error(`tcp_service '${this.name}' error: ${String(error)}`));
|
|
288
|
+
this.owner = true;
|
|
289
|
+
const addr = server.address();
|
|
290
|
+
this.boundPortValue = typeof addr === "object" && addr ? addr.port : this.port;
|
|
291
|
+
Log.info(`tcp_service '${this.name}' listening on ${host}:${this.boundPortValue}`);
|
|
292
|
+
this.startReaper();
|
|
293
|
+
resolve(true);
|
|
294
|
+
});
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
private handleConnection(socket: Socket): void {
|
|
299
|
+
// Refuse past the limit BEFORE the connection joins the registry.
|
|
300
|
+
if (this.maxConnections !== null && this.connections.size >= this.maxConnections) {
|
|
301
|
+
socket.destroy();
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
const conn = new TcpConnection(socket, this);
|
|
305
|
+
this.connections.add(conn);
|
|
306
|
+
|
|
307
|
+
socket.on("data", (chunk: Buffer) => {
|
|
308
|
+
// Pause while an async handler runs so chunks are delivered in order
|
|
309
|
+
// (parity with the Python reference awaiting each on_data).
|
|
310
|
+
socket.pause();
|
|
311
|
+
void this.dispatch(conn, chunk).finally(() => {
|
|
312
|
+
if (!conn.isClosed) socket.resume();
|
|
313
|
+
});
|
|
314
|
+
});
|
|
315
|
+
socket.on("close", () => this.remove(conn));
|
|
316
|
+
socket.on("error", () => {
|
|
317
|
+
/* a reset/broken pipe surfaces as 'close' next; never crash the loop */
|
|
318
|
+
});
|
|
319
|
+
|
|
320
|
+
const onConnect = this._callbacks.onConnect;
|
|
321
|
+
if (onConnect) {
|
|
322
|
+
void Promise.resolve(onConnect(conn)).catch((error: unknown) => {
|
|
323
|
+
Log.error(`tcp_service '${this.name}' onConnect error: ${String(error)}`);
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
private async dispatch(conn: TcpConnection, chunk: Buffer): Promise<void> {
|
|
329
|
+
conn._touch();
|
|
330
|
+
const { onData, onLine } = this._callbacks;
|
|
331
|
+
if (onData) {
|
|
332
|
+
// Raw bytes, exactly as received — never newline-split, never decoded.
|
|
333
|
+
try {
|
|
334
|
+
await onData(conn, chunk);
|
|
335
|
+
} catch (error) {
|
|
336
|
+
Log.error(`tcp_service '${this.name}' onData error: ${String(error)}`);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
if (onLine) {
|
|
340
|
+
conn.lineBuffer = Buffer.concat([conn.lineBuffer, chunk]);
|
|
341
|
+
let newline = conn.lineBuffer.indexOf(0x0a);
|
|
342
|
+
while (newline !== -1) {
|
|
343
|
+
let line = conn.lineBuffer.subarray(0, newline);
|
|
344
|
+
conn.lineBuffer = conn.lineBuffer.subarray(newline + 1);
|
|
345
|
+
if (line.length > 0 && line[line.length - 1] === 0x0d) {
|
|
346
|
+
line = line.subarray(0, line.length - 1); // strip a trailing \r
|
|
347
|
+
}
|
|
348
|
+
try {
|
|
349
|
+
await onLine(conn, line);
|
|
350
|
+
} catch (error) {
|
|
351
|
+
Log.error(`tcp_service '${this.name}' onLine error: ${String(error)}`);
|
|
352
|
+
}
|
|
353
|
+
newline = conn.lineBuffer.indexOf(0x0a);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** @internal remove a connection and fire on_close exactly once. */
|
|
359
|
+
remove(conn: TcpConnection): void {
|
|
360
|
+
const existed = this.connections.delete(conn);
|
|
361
|
+
if (conn.id !== null && this.byId.get(conn.id) === conn) {
|
|
362
|
+
// Only drop the id when THIS connection still owns it; a newer connection
|
|
363
|
+
// that superseded it keeps the id.
|
|
364
|
+
this.byId.delete(conn.id);
|
|
365
|
+
}
|
|
366
|
+
if (existed) conn._fireClose();
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// ── Idle reaper (D1 consumer shape — default OFF) ───────────────────────────
|
|
370
|
+
|
|
371
|
+
private startReaper(): void {
|
|
372
|
+
if (this.idleTimeout <= 0 || this.reaper) return;
|
|
373
|
+
const intervalMs = Math.max(50, Math.min(1000, (this.idleTimeout / 2) * 1000));
|
|
374
|
+
this.reaper = setInterval(() => this.reapIdle(), intervalMs);
|
|
375
|
+
this.reaper.unref();
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
private reapIdle(): void {
|
|
379
|
+
const now = Date.now();
|
|
380
|
+
const limitMs = this.idleTimeout * 1000;
|
|
381
|
+
for (const conn of [...this.connections]) {
|
|
382
|
+
if (now - conn.lastActivity >= limitMs) conn.close();
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/** Stop accepting new connections (close the listener). Live conns stay. */
|
|
387
|
+
stopAccepting(): void {
|
|
388
|
+
if (this.reaper) {
|
|
389
|
+
clearInterval(this.reaper);
|
|
390
|
+
this.reaper = null;
|
|
391
|
+
}
|
|
392
|
+
if (this.server && this.owner) {
|
|
393
|
+
this.server.close();
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/** Close every live connection (firing on_close) and release the listener. */
|
|
398
|
+
async drain(): Promise<void> {
|
|
399
|
+
this.stopAccepting();
|
|
400
|
+
for (const conn of [...this.connections]) conn.close();
|
|
401
|
+
if (this.server) {
|
|
402
|
+
await new Promise<void>((resolve) => {
|
|
403
|
+
this.server!.close(() => resolve());
|
|
404
|
+
this.server!.unref();
|
|
405
|
+
}).catch(() => undefined);
|
|
406
|
+
this.server = null;
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** Stop accepting and drain in one call (used by direct callers/tests). */
|
|
411
|
+
async stop(): Promise<void> {
|
|
412
|
+
await this.drain();
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// ── Public surface: registry facade + server-driven lifecycle hooks ───────────
|
|
417
|
+
|
|
418
|
+
const services = new Map<string, TcpService>();
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* Register a named raw TCP service; the server binds it on boot (D1). Options
|
|
422
|
+
* are read once here. Reachable anywhere via `tcp(name)`.
|
|
423
|
+
*/
|
|
424
|
+
export function tcpService(port: number, options: TcpServiceOptions = {}): TcpService {
|
|
425
|
+
const service = new TcpService(port, options);
|
|
426
|
+
services.set(service.name, service);
|
|
427
|
+
return service;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/**
|
|
431
|
+
* The registry for a named service, for server -> device push. Throws for an
|
|
432
|
+
* unknown service name — a programming error, unlike a send to an unknown
|
|
433
|
+
* device id, which is a runtime no-op.
|
|
434
|
+
*/
|
|
435
|
+
export function tcp(name = "default"): TcpService {
|
|
436
|
+
const service = services.get(name);
|
|
437
|
+
if (!service) {
|
|
438
|
+
const known = services.size === 0 ? "(none registered)" : [...services.keys()].join(", ");
|
|
439
|
+
throw new Error(`no tcp_service named '${name}' is registered; known services: ${known}`);
|
|
440
|
+
}
|
|
441
|
+
return service;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
export function registeredTcpServices(): TcpService[] {
|
|
445
|
+
return [...services.values()];
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/** Drop every registered service (test isolation; not used in production). */
|
|
449
|
+
export function clearTcpRegistry(): void {
|
|
450
|
+
services.clear();
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/** Start every registered service on boot (called by startServer). */
|
|
454
|
+
export async function startAllTcpServices(host = "0.0.0.0"): Promise<void> {
|
|
455
|
+
for (const service of registeredTcpServices()) {
|
|
456
|
+
try {
|
|
457
|
+
await service.start(host);
|
|
458
|
+
} catch (error) {
|
|
459
|
+
Log.error(`tcp_service '${service.name}' failed to start: ${String(error)}`);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/** Stop every service accepting (shutdown step 1). */
|
|
465
|
+
export function stopAcceptingAllTcpServices(): void {
|
|
466
|
+
for (const service of registeredTcpServices()) {
|
|
467
|
+
try {
|
|
468
|
+
service.stopAccepting();
|
|
469
|
+
} catch (error) {
|
|
470
|
+
Log.error(`tcp_service '${service.name}' stop-accepting failed: ${String(error)}`);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/** Drain and release every service's connections (shutdown drain step). */
|
|
476
|
+
export async function drainAllTcpServices(): Promise<void> {
|
|
477
|
+
for (const service of registeredTcpServices()) {
|
|
478
|
+
try {
|
|
479
|
+
await service.drain();
|
|
480
|
+
} catch (error) {
|
|
481
|
+
Log.error(`tcp_service '${service.name}' drain failed: ${String(error)}`);
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
}
|