tina4-nodejs 3.13.156 → 3.13.158
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 +1304 -616
- package/packages/core/dist/index.js +1313 -616
- 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 +19 -3
- 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 +1306 -618
- 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/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);
|
|
@@ -2320,8 +2321,9 @@ export async function startServer(config?: Tina4Config): Promise<{
|
|
|
2320
2321
|
const upPath = (req.url ?? "/").split("?")[0];
|
|
2321
2322
|
// Dev-reload channel (debug only).
|
|
2322
2323
|
if (isDevMode() && upPath === "/__dev_reload") {
|
|
2323
|
-
// ADR-0082: the reload socket answers only a loopback / TINA4_HOST Host
|
|
2324
|
-
|
|
2324
|
+
// ADR-0082: the reload socket answers only a loopback / TINA4_HOST Host,
|
|
2325
|
+
// from a raw socket peer the /__dev HTTP gate would also let in.
|
|
2326
|
+
if (!devHostAllowed(req.headers.host) || !devPeerAllowed(socket.remoteAddress)) {
|
|
2325
2327
|
try { socket.write("HTTP/1.1 403 Forbidden\r\n\r\n"); socket.destroy(); } catch { /* gone */ }
|
|
2326
2328
|
return;
|
|
2327
2329
|
}
|
|
@@ -2359,6 +2361,12 @@ export async function startServer(config?: Tina4Config): Promise<{
|
|
|
2359
2361
|
// promise resolves (a client can then rely on both families being up).
|
|
2360
2362
|
const siblingServers = await startLoopbackSiblings(port, host, dispatch);
|
|
2361
2363
|
|
|
2364
|
+
// Raw TCP services (feature 142, ADR-0102 D1) bind on THIS event loop,
|
|
2365
|
+
// beside the HTTP server — one process serves both the device gateway and
|
|
2366
|
+
// its dashboard. Each binds its own port; a worker that finds the port
|
|
2367
|
+
// already bound skips silently (single-owner). Drained on shutdown below.
|
|
2368
|
+
await startAllTcpServices(host);
|
|
2369
|
+
|
|
2362
2370
|
const displayHost = host === "0.0.0.0" ? "localhost" : host;
|
|
2363
2371
|
const isDebug = isTruthy(process.env.TINA4_DEBUG);
|
|
2364
2372
|
const logLevel = (process.env.TINA4_LOG_LEVEL ?? "DEBUG").toUpperCase();
|
|
@@ -2544,6 +2552,11 @@ ${reset}
|
|
|
2544
2552
|
Log.info(`Closed ${wsClosed} WebSocket connection(s) with 1001 going away`);
|
|
2545
2553
|
}
|
|
2546
2554
|
|
|
2555
|
+
// Raw TCP services stop accepting and drain their live device
|
|
2556
|
+
// connections (firing on_close) alongside the HTTP/WebSocket drain.
|
|
2557
|
+
stopAcceptingAllTcpServices();
|
|
2558
|
+
await drainAllTcpServices();
|
|
2559
|
+
|
|
2547
2560
|
// Race the drain against the shutdown budget. Whatever is still in
|
|
2548
2561
|
// flight when the budget expires gets force-closed: SIGKILL is what
|
|
2549
2562
|
// arrives next, so a bounded drain is strictly better than an
|
|
@@ -2612,6 +2625,9 @@ ${reset}
|
|
|
2612
2625
|
process.off("SIGINT", onSigint);
|
|
2613
2626
|
// Clear any registered background timers so graceful shutdown actually exits.
|
|
2614
2627
|
stopAllBackgroundTasks();
|
|
2628
|
+
// Release raw TCP listeners + connections on an explicit close() too.
|
|
2629
|
+
stopAcceptingAllTcpServices();
|
|
2630
|
+
void drainAllTcpServices();
|
|
2615
2631
|
if (aiServer) aiServer.close();
|
|
2616
2632
|
server.close();
|
|
2617
2633
|
// 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
|
+
}
|
|
@@ -1313,6 +1313,116 @@ function isEscapableStructured(value) {
|
|
|
1313
1313
|
function toOutputString(value) {
|
|
1314
1314
|
return String(value);
|
|
1315
1315
|
}
|
|
1316
|
+
var FrondSyntaxError = class extends Error {
|
|
1317
|
+
constructor(message) {
|
|
1318
|
+
super(message);
|
|
1319
|
+
this.name = "FrondSyntaxError";
|
|
1320
|
+
}
|
|
1321
|
+
};
|
|
1322
|
+
var PHP_MONTHS = [
|
|
1323
|
+
"January",
|
|
1324
|
+
"February",
|
|
1325
|
+
"March",
|
|
1326
|
+
"April",
|
|
1327
|
+
"May",
|
|
1328
|
+
"June",
|
|
1329
|
+
"July",
|
|
1330
|
+
"August",
|
|
1331
|
+
"September",
|
|
1332
|
+
"October",
|
|
1333
|
+
"November",
|
|
1334
|
+
"December"
|
|
1335
|
+
];
|
|
1336
|
+
var PHP_DAYS = [
|
|
1337
|
+
"Sunday",
|
|
1338
|
+
"Monday",
|
|
1339
|
+
"Tuesday",
|
|
1340
|
+
"Wednesday",
|
|
1341
|
+
"Thursday",
|
|
1342
|
+
"Friday",
|
|
1343
|
+
"Saturday"
|
|
1344
|
+
];
|
|
1345
|
+
function phpDate(dt, fmt) {
|
|
1346
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
1347
|
+
const hours = dt.getHours();
|
|
1348
|
+
const h12 = hours % 12 || 12;
|
|
1349
|
+
const dow = dt.getDay();
|
|
1350
|
+
const iso = dow === 0 ? 7 : dow;
|
|
1351
|
+
let out = "";
|
|
1352
|
+
for (let i = 0; i < fmt.length; i++) {
|
|
1353
|
+
const c = fmt[i];
|
|
1354
|
+
if (c === "\\" && i + 1 < fmt.length) {
|
|
1355
|
+
out += fmt[i + 1];
|
|
1356
|
+
i++;
|
|
1357
|
+
continue;
|
|
1358
|
+
}
|
|
1359
|
+
switch (c) {
|
|
1360
|
+
case "Y":
|
|
1361
|
+
out += String(dt.getFullYear());
|
|
1362
|
+
break;
|
|
1363
|
+
case "y":
|
|
1364
|
+
out += pad(dt.getFullYear() % 100);
|
|
1365
|
+
break;
|
|
1366
|
+
case "m":
|
|
1367
|
+
out += pad(dt.getMonth() + 1);
|
|
1368
|
+
break;
|
|
1369
|
+
case "n":
|
|
1370
|
+
out += String(dt.getMonth() + 1);
|
|
1371
|
+
break;
|
|
1372
|
+
case "d":
|
|
1373
|
+
out += pad(dt.getDate());
|
|
1374
|
+
break;
|
|
1375
|
+
case "j":
|
|
1376
|
+
out += String(dt.getDate());
|
|
1377
|
+
break;
|
|
1378
|
+
case "H":
|
|
1379
|
+
out += pad(hours);
|
|
1380
|
+
break;
|
|
1381
|
+
case "G":
|
|
1382
|
+
out += String(hours);
|
|
1383
|
+
break;
|
|
1384
|
+
case "h":
|
|
1385
|
+
out += pad(h12);
|
|
1386
|
+
break;
|
|
1387
|
+
case "g":
|
|
1388
|
+
out += String(h12);
|
|
1389
|
+
break;
|
|
1390
|
+
case "i":
|
|
1391
|
+
out += pad(dt.getMinutes());
|
|
1392
|
+
break;
|
|
1393
|
+
case "s":
|
|
1394
|
+
out += pad(dt.getSeconds());
|
|
1395
|
+
break;
|
|
1396
|
+
case "A":
|
|
1397
|
+
out += hours < 12 ? "AM" : "PM";
|
|
1398
|
+
break;
|
|
1399
|
+
case "a":
|
|
1400
|
+
out += hours < 12 ? "am" : "pm";
|
|
1401
|
+
break;
|
|
1402
|
+
case "D":
|
|
1403
|
+
out += PHP_DAYS[dow].slice(0, 3);
|
|
1404
|
+
break;
|
|
1405
|
+
case "l":
|
|
1406
|
+
out += PHP_DAYS[dow];
|
|
1407
|
+
break;
|
|
1408
|
+
case "M":
|
|
1409
|
+
out += PHP_MONTHS[dt.getMonth()].slice(0, 3);
|
|
1410
|
+
break;
|
|
1411
|
+
case "F":
|
|
1412
|
+
out += PHP_MONTHS[dt.getMonth()];
|
|
1413
|
+
break;
|
|
1414
|
+
case "N":
|
|
1415
|
+
out += String(iso);
|
|
1416
|
+
break;
|
|
1417
|
+
case "w":
|
|
1418
|
+
out += String(dow);
|
|
1419
|
+
break;
|
|
1420
|
+
default:
|
|
1421
|
+
out += c;
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
return out;
|
|
1425
|
+
}
|
|
1316
1426
|
function dateFilter(value, fmt) {
|
|
1317
1427
|
let dt;
|
|
1318
1428
|
if (value instanceof Date) {
|
|
@@ -1325,6 +1435,7 @@ function dateFilter(value, fmt) {
|
|
|
1325
1435
|
} else {
|
|
1326
1436
|
return String(value);
|
|
1327
1437
|
}
|
|
1438
|
+
if (!fmt.includes("%")) return phpDate(dt, fmt);
|
|
1328
1439
|
return fmt.replace(/%Y/g, String(dt.getFullYear())).replace(/%m/g, String(dt.getMonth() + 1).padStart(2, "0")).replace(/%d/g, String(dt.getDate()).padStart(2, "0")).replace(/%H/g, String(dt.getHours()).padStart(2, "0")).replace(/%M/g, String(dt.getMinutes()).padStart(2, "0")).replace(/%S/g, String(dt.getSeconds()).padStart(2, "0")).replace(/%I/g, String(dt.getHours() % 12 || 12).padStart(2, "0")).replace(/%p/g, dt.getHours() >= 12 ? "PM" : "AM").replace(/%B/g, dt.toLocaleString("en-US", { month: "long" })).replace(/%b/g, dt.toLocaleString("en-US", { month: "short" })).replace(/%A/g, dt.toLocaleString("en-US", { weekday: "long" })).replace(/%a/g, dt.toLocaleString("en-US", { weekday: "short" }));
|
|
1329
1440
|
}
|
|
1330
1441
|
function wordwrap(text, width) {
|
|
@@ -1955,7 +2066,9 @@ var Frond = class _Frond {
|
|
|
1955
2066
|
}
|
|
1956
2067
|
}
|
|
1957
2068
|
if (depth > 0) {
|
|
1958
|
-
|
|
2069
|
+
throw new FrondSyntaxError(
|
|
2070
|
+
`{% block ${name} %} is never closed (missing or malformed {% endblock %})`
|
|
2071
|
+
);
|
|
1959
2072
|
}
|
|
1960
2073
|
}
|
|
1961
2074
|
return blocks;
|
|
@@ -2022,9 +2135,9 @@ var Frond = class _Frond {
|
|
|
2022
2135
|
}
|
|
2023
2136
|
}
|
|
2024
2137
|
if (!closeMatch) {
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2138
|
+
throw new FrondSyntaxError(
|
|
2139
|
+
`{% block ${name} %} is never closed (missing or malformed {% endblock %})`
|
|
2140
|
+
);
|
|
2028
2141
|
}
|
|
2029
2142
|
const parentContent = source.slice(contentStart, closeMatch.index);
|
|
2030
2143
|
const blockSource = blocks[name] ?? parentContent;
|
|
@@ -2979,6 +3092,7 @@ var Frond = class _Frond {
|
|
|
2979
3092
|
};
|
|
2980
3093
|
export {
|
|
2981
3094
|
Frond,
|
|
3095
|
+
FrondSyntaxError,
|
|
2982
3096
|
escapeHtml,
|
|
2983
3097
|
setCspNonceProvider,
|
|
2984
3098
|
setFormTokenSessionProvider
|