@cosyte/mllp 0.1.14 → 0.1.15
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/CHANGELOG.md +10 -0
- package/README.md +13 -8
- package/dist/ack-from-hl7/index.cjs.map +1 -1
- package/dist/ack-from-hl7/index.d.cts +2 -1
- package/dist/ack-from-hl7/index.d.ts +2 -1
- package/dist/ack-from-hl7/index.mjs.map +1 -1
- package/dist/arbitraries/index.cjs +6 -15
- package/dist/arbitraries/index.cjs.map +1 -1
- package/dist/arbitraries/index.d.cts +5 -4
- package/dist/arbitraries/index.d.ts +5 -4
- package/dist/arbitraries/index.mjs +6 -15
- package/dist/arbitraries/index.mjs.map +1 -1
- package/dist/index.cjs +279 -63
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +183 -43
- package/dist/index.d.ts +183 -43
- package/dist/index.mjs +279 -63
- package/dist/index.mjs.map +1 -1
- package/dist/testing/index.cjs.map +1 -1
- package/dist/testing/index.d.cts +2 -2
- package/dist/testing/index.d.ts +2 -2
- package/dist/testing/index.mjs.map +1 -1
- package/package.json +5 -4
package/dist/index.cjs
CHANGED
|
@@ -398,14 +398,12 @@ var FrameReader = class {
|
|
|
398
398
|
return;
|
|
399
399
|
}
|
|
400
400
|
if (byte === VT) {
|
|
401
|
-
this.
|
|
402
|
-
"
|
|
401
|
+
this._refuse(
|
|
402
|
+
"MLLP_PAYLOAD_CONTAINS_VT",
|
|
403
403
|
this._byteOffset,
|
|
404
|
-
|
|
404
|
+
VT,
|
|
405
|
+
`VT (0x0B) inside a frame at offset ${this._byteOffset}; the frame is refused whole`
|
|
405
406
|
);
|
|
406
|
-
this._discard();
|
|
407
|
-
this._state = "READING_PAYLOAD";
|
|
408
|
-
return;
|
|
409
407
|
}
|
|
410
408
|
if (this._writePos >= this._maxFrameSize) this._throwTooLarge();
|
|
411
409
|
this._appendByte(byte);
|
|
@@ -482,14 +480,12 @@ var FrameReader = class {
|
|
|
482
480
|
`Strict mode: FS without CR at offset ${this._byteOffset}`
|
|
483
481
|
);
|
|
484
482
|
}
|
|
485
|
-
this.
|
|
486
|
-
"
|
|
487
|
-
this._byteOffset,
|
|
488
|
-
|
|
483
|
+
this._refuse(
|
|
484
|
+
"MLLP_PAYLOAD_CONTAINS_FS",
|
|
485
|
+
this._byteOffset - 1,
|
|
486
|
+
FS,
|
|
487
|
+
`FS (0x1C) inside a frame at offset ${this._byteOffset - 1}; the frame is refused whole`
|
|
489
488
|
);
|
|
490
|
-
this._deliverFrame();
|
|
491
|
-
this._state = "SCANNING_FOR_VT";
|
|
492
|
-
return;
|
|
493
489
|
}
|
|
494
490
|
const snippet = Buffer.from([byte]);
|
|
495
491
|
throw new MllpFramingError(
|
|
@@ -533,6 +529,17 @@ var FrameReader = class {
|
|
|
533
529
|
this._frameWarnings = [];
|
|
534
530
|
this._opts.onFrame(payload, frameStart, frameWarnings);
|
|
535
531
|
}
|
|
532
|
+
/**
|
|
533
|
+
* Refuse the current frame whole: forget its bytes and its warnings, go back to scanning for a
|
|
534
|
+
* VT, and throw. The error names the framing byte (`delimiter`) and its offset, never a byte of
|
|
535
|
+
* the frame's content, and nothing of the frame is delivered.
|
|
536
|
+
*/
|
|
537
|
+
_refuse(code, byteOffset, delimiter, message) {
|
|
538
|
+
this._discard();
|
|
539
|
+
this._frameWarnings = [];
|
|
540
|
+
this._state = "SCANNING_FOR_VT";
|
|
541
|
+
throw new MllpFramingError(code, byteOffset, Buffer.from([delimiter]), message);
|
|
542
|
+
}
|
|
536
543
|
/** Emit a warning via the `onWarning` callback, swallowing any handler exceptions. */
|
|
537
544
|
_emitWarning(code, byteOffset, message) {
|
|
538
545
|
const warning = createWarning(code, byteOffset, message);
|
|
@@ -1023,6 +1030,20 @@ var Connection = class extends events.EventEmitter {
|
|
|
1023
1030
|
_leftDraining = new Promise((resolve) => {
|
|
1024
1031
|
this._leaveDraining = resolve;
|
|
1025
1032
|
});
|
|
1033
|
+
/**
|
|
1034
|
+
* Work answering a frame this connection delivered, still running, with what it owes the peer.
|
|
1035
|
+
* See {@link Connection.holdOpenFor}.
|
|
1036
|
+
*/
|
|
1037
|
+
_answering = /* @__PURE__ */ new Map();
|
|
1038
|
+
/**
|
|
1039
|
+
* Set once a fatal framing error has been met, or {@link Connection.stopReading} called: from
|
|
1040
|
+
* then on no byte the peer sends is read.
|
|
1041
|
+
*/
|
|
1042
|
+
_refusing = false;
|
|
1043
|
+
/** When the `close()` drain began (`Date.now()`), or `undefined` when no `close()` is draining. */
|
|
1044
|
+
_closeBegan;
|
|
1045
|
+
/** Ends the wait after a fatal framing error: destroys the transport once the bound passes. */
|
|
1046
|
+
_refusalBound;
|
|
1026
1047
|
/**
|
|
1027
1048
|
* beforeClose hook, no-op default that resolves immediately.
|
|
1028
1049
|
*
|
|
@@ -1054,6 +1075,7 @@ var Connection = class extends events.EventEmitter {
|
|
|
1054
1075
|
}
|
|
1055
1076
|
});
|
|
1056
1077
|
this._transport.onData((chunk) => {
|
|
1078
|
+
if (this._refusing) return;
|
|
1057
1079
|
this._bytesIn += chunk.length;
|
|
1058
1080
|
this._lastByteInAt = /* @__PURE__ */ new Date();
|
|
1059
1081
|
try {
|
|
@@ -1149,9 +1171,13 @@ var Connection = class extends events.EventEmitter {
|
|
|
1149
1171
|
*
|
|
1150
1172
|
* - If `CONNECTING` or `RECONNECTING`: cancels the pending attempt, transitions
|
|
1151
1173
|
* directly to `CLOSED`, and calls `transport.destroy()`.
|
|
1152
|
-
* - If `CONNECTED`: transitions to `DRAINING`, calls `beforeClose(drainTimeoutMs)
|
|
1153
|
-
*
|
|
1154
|
-
*
|
|
1174
|
+
* - If `CONNECTED`: transitions to `DRAINING`, calls `beforeClose(drainTimeoutMs)` and
|
|
1175
|
+
* waits for it and for every piece of work passed to {@link Connection.holdOpenFor} that is
|
|
1176
|
+
* still running, then `DRAINING → DISCONNECTED` and ends the transport gracefully, so what
|
|
1177
|
+
* that work wrote reaches the peer. If the drain timeout elapses first: `DRAINING → CLOSED`
|
|
1178
|
+
* and the transport is destroyed. Work still running when the drain ends that way (the
|
|
1179
|
+
* timeout or a `destroy()`) is abandoned, and an `MllpConnectionError` with `phase: 'close'`
|
|
1180
|
+
* on `'error'` says how many were left and that what they would write is not sent.
|
|
1155
1181
|
* - If `DRAINING`: waits for the existing drain to complete (idempotent).
|
|
1156
1182
|
*
|
|
1157
1183
|
* Every pending `close()` resolves as soon as the connection leaves `DRAINING`, by whatever
|
|
@@ -1177,6 +1203,7 @@ var Connection = class extends events.EventEmitter {
|
|
|
1177
1203
|
if (this._state === "DRAINING") {
|
|
1178
1204
|
return this._drainPromise ?? Promise.resolve();
|
|
1179
1205
|
}
|
|
1206
|
+
this._closeBegan = Date.now();
|
|
1180
1207
|
this._transition("DRAINING");
|
|
1181
1208
|
this._drainPromise = this._drainWithTimeout(timeout).finally(() => {
|
|
1182
1209
|
this._drainPromise = null;
|
|
@@ -1184,13 +1211,13 @@ var Connection = class extends events.EventEmitter {
|
|
|
1184
1211
|
return this._drainPromise;
|
|
1185
1212
|
}
|
|
1186
1213
|
/**
|
|
1187
|
-
* Race `beforeClose()` against the drain timeout.
|
|
1214
|
+
* Race `beforeClose()` and the held work against the drain timeout.
|
|
1188
1215
|
*
|
|
1189
1216
|
* On normal completion: `DRAINING → DISCONNECTED` + `transport.close()`.
|
|
1190
1217
|
* On timeout: `DRAINING → CLOSED` + `transport.destroy()`.
|
|
1191
1218
|
*/
|
|
1192
1219
|
async _drainWithTimeout(timeoutMs) {
|
|
1193
|
-
const drainPromise = this.beforeClose(timeoutMs);
|
|
1220
|
+
const drainPromise = Promise.all([this.beforeClose(timeoutMs), this._heldWorkSettled()]);
|
|
1194
1221
|
let handle;
|
|
1195
1222
|
const timeoutPromise = new Promise((resolve) => {
|
|
1196
1223
|
handle = setTimeout(() => {
|
|
@@ -1206,6 +1233,7 @@ var Connection = class extends events.EventEmitter {
|
|
|
1206
1233
|
]);
|
|
1207
1234
|
if (this._state !== "DRAINING") return;
|
|
1208
1235
|
if (result === "timeout") {
|
|
1236
|
+
this._reportAbandonedAfter("drain timeout");
|
|
1209
1237
|
this._transition("CLOSED", "drain timeout");
|
|
1210
1238
|
this._transport.destroy();
|
|
1211
1239
|
} else {
|
|
@@ -1232,9 +1260,75 @@ var Connection = class extends events.EventEmitter {
|
|
|
1232
1260
|
*/
|
|
1233
1261
|
destroy(reason) {
|
|
1234
1262
|
if (this._state === "CLOSED") return;
|
|
1263
|
+
if (this._state === "DRAINING") {
|
|
1264
|
+
this._reportAbandonedAfter(reason?.message ?? "destroy()");
|
|
1265
|
+
}
|
|
1235
1266
|
this._transition("CLOSED", reason?.message ?? "destroy()");
|
|
1236
1267
|
this._transport.destroy(reason);
|
|
1237
1268
|
}
|
|
1269
|
+
/**
|
|
1270
|
+
* Hold the connection open, on `close()` or a fatal framing error, until `work` settles.
|
|
1271
|
+
*
|
|
1272
|
+
* Pass the work that answers a frame this connection delivered: the handler and the write of
|
|
1273
|
+
* its acknowledgement. A `close()` waits for every piece of work passed here to settle before
|
|
1274
|
+
* it ends the transport, so an acknowledgement written by that work still goes out. When a
|
|
1275
|
+
* later frame on the same connection has a fatal framing error, the connection reads nothing
|
|
1276
|
+
* more, waits the same way, and only then closes, so the acknowledgement of a frame delivered
|
|
1277
|
+
* before the refused one still goes out. Either wait is bounded by `drainTimeoutMs` (default 30
|
|
1278
|
+
* seconds): work that has not settled by then is abandoned and the connection is destroyed.
|
|
1279
|
+
* `MllpServer` passes every message's work here itself; a caller driving a bare `Connection`
|
|
1280
|
+
* may do the same.
|
|
1281
|
+
*
|
|
1282
|
+
* `options.kind` says what the work owes the peer, which decides whether `close()` waits for it
|
|
1283
|
+
* and how an abandoned piece is reported:
|
|
1284
|
+
*
|
|
1285
|
+
* - `'ack'` (the default): the work writes the frame's acknowledgement as its last step, so
|
|
1286
|
+
* while it runs the acknowledgement has not been sent. `close()` waits for it; abandoned, it is
|
|
1287
|
+
* counted as a message delivered whose acknowledgement was not sent.
|
|
1288
|
+
* - `'manual'`: the work writes the acknowledgement itself at a point of its own choosing (a
|
|
1289
|
+
* manual-mode handler). `close()` waits for it until it settles; abandoned, it is counted as a
|
|
1290
|
+
* handler whose acknowledgement may not have been sent.
|
|
1291
|
+
* - `'observer'`: the work writes no acknowledgement (an `onMessage` observer in custom-ACK
|
|
1292
|
+
* mode). `close()` does not wait for it; still running when a `close()` is abandoned, it is
|
|
1293
|
+
* named separately as an observer still running. A fatal framing error still waits for it.
|
|
1294
|
+
*
|
|
1295
|
+
* A rejection of `work` is not reported here; it only ends the wait for it.
|
|
1296
|
+
*
|
|
1297
|
+
* @param work - The work answering one delivered frame.
|
|
1298
|
+
* @param options - `kind`: what the work owes the peer (default `'ack'`).
|
|
1299
|
+
*
|
|
1300
|
+
* @example
|
|
1301
|
+
* ```typescript
|
|
1302
|
+
* conn.on('message', ({ payload }) => {
|
|
1303
|
+
* conn.holdOpenFor(commit(payload).then(() => conn.send(encodeFrame(ackFor(payload)))));
|
|
1304
|
+
* });
|
|
1305
|
+
* ```
|
|
1306
|
+
*/
|
|
1307
|
+
holdOpenFor(work, options) {
|
|
1308
|
+
const done = () => {
|
|
1309
|
+
this._answering.delete(work);
|
|
1310
|
+
};
|
|
1311
|
+
this._answering.set(work, options?.kind ?? "ack");
|
|
1312
|
+
work.then(done, done);
|
|
1313
|
+
}
|
|
1314
|
+
/**
|
|
1315
|
+
* Read nothing more from the peer: every byte that arrives from now on is dropped unread, and
|
|
1316
|
+
* no further frame is delivered. It cannot be undone.
|
|
1317
|
+
*
|
|
1318
|
+
* `MllpServer.close()` calls this on each connection before closing it, so no new message
|
|
1319
|
+
* reaches a handler while the ones already running finish and their acknowledgements are
|
|
1320
|
+
* written. A client must not call it before a `close()` that waits for acknowledgements, since
|
|
1321
|
+
* it would then never read them.
|
|
1322
|
+
*
|
|
1323
|
+
* @example
|
|
1324
|
+
* ```typescript
|
|
1325
|
+
* conn.stopReading();
|
|
1326
|
+
* await conn.close();
|
|
1327
|
+
* ```
|
|
1328
|
+
*/
|
|
1329
|
+
stopReading() {
|
|
1330
|
+
this._refusing = true;
|
|
1331
|
+
}
|
|
1238
1332
|
/**
|
|
1239
1333
|
* Return a JSON-serializable observability snapshot.
|
|
1240
1334
|
*
|
|
@@ -1272,6 +1366,61 @@ var Connection = class extends events.EventEmitter {
|
|
|
1272
1366
|
// ---------------------------------------------------------------------------
|
|
1273
1367
|
// Private FSM helpers
|
|
1274
1368
|
// ---------------------------------------------------------------------------
|
|
1369
|
+
/**
|
|
1370
|
+
* Settle once no work passed to {@link Connection.holdOpenFor} that owes an acknowledgement is
|
|
1371
|
+
* running; an `'observer'` is not waited for. Work registered while waiting (a frame decoded
|
|
1372
|
+
* from bytes already read) is waited for too.
|
|
1373
|
+
*/
|
|
1374
|
+
async _heldWorkSettled() {
|
|
1375
|
+
for (; ; ) {
|
|
1376
|
+
const owing = [...this._answering].filter(([, kind]) => kind !== "observer");
|
|
1377
|
+
if (owing.length === 0) return;
|
|
1378
|
+
await Promise.allSettled(owing.map(([work]) => work));
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
1381
|
+
/**
|
|
1382
|
+
* Report, on `'error'`, the held work a `close()` drain abandons because the drain ended before
|
|
1383
|
+
* that work settled. It counts per delivered message: work that would have written an
|
|
1384
|
+
* acknowledgement (not sent), a manual-mode handler (its acknowledgement may not have been
|
|
1385
|
+
* sent), and, separately, observers that owe none. Nothing is reported when no `close()` is
|
|
1386
|
+
* draining or nothing is still running.
|
|
1387
|
+
*
|
|
1388
|
+
* @param how - How the drain ended, as it reads after "close() ended ".
|
|
1389
|
+
* @param reason - What ended it, the message of the report's `cause`.
|
|
1390
|
+
*/
|
|
1391
|
+
_reportAbandonedWork(how, reason) {
|
|
1392
|
+
if (this._closeBegan === void 0) return;
|
|
1393
|
+
const count = { ack: 0, manual: 0, observer: 0 };
|
|
1394
|
+
for (const kind of this._answering.values()) count[kind] += 1;
|
|
1395
|
+
const parts = [];
|
|
1396
|
+
if (count.ack > 0) {
|
|
1397
|
+
parts.push(
|
|
1398
|
+
count.ack === 1 ? "1 message was delivered and its acknowledgement was not sent" : `${String(count.ack)} messages were delivered and their acknowledgements were not sent`
|
|
1399
|
+
);
|
|
1400
|
+
}
|
|
1401
|
+
if (count.manual > 0) {
|
|
1402
|
+
parts.push(
|
|
1403
|
+
count.manual === 1 ? "1 manual-mode handler was still running, so its acknowledgement may not have been sent" : `${String(count.manual)} manual-mode handlers were still running, so their acknowledgements may not have been sent`
|
|
1404
|
+
);
|
|
1405
|
+
}
|
|
1406
|
+
if (count.observer > 0) {
|
|
1407
|
+
parts.push(
|
|
1408
|
+
count.observer === 1 ? "1 observer that owes no acknowledgement was still running" : `${String(count.observer)} observers that owe no acknowledgement were still running`
|
|
1409
|
+
);
|
|
1410
|
+
}
|
|
1411
|
+
if (count.ack + count.manual === 0) return;
|
|
1412
|
+
this._emitErrorIfListened(
|
|
1413
|
+
new MllpConnectionError(`close() ended ${how}: ${parts.join("; ")}`, {
|
|
1414
|
+
cause: new Error(reason),
|
|
1415
|
+
phase: "close"
|
|
1416
|
+
})
|
|
1417
|
+
);
|
|
1418
|
+
}
|
|
1419
|
+
/** Report the work a `close()` drain abandons at the bound or on a `destroy()`. */
|
|
1420
|
+
_reportAbandonedAfter(reason) {
|
|
1421
|
+
const elapsedMs = Date.now() - (this._closeBegan ?? Date.now());
|
|
1422
|
+
this._reportAbandonedWork(`after ${String(elapsedMs)} ms (${reason})`, reason);
|
|
1423
|
+
}
|
|
1275
1424
|
_transition(to, reason) {
|
|
1276
1425
|
const from = this._state;
|
|
1277
1426
|
const legal = LEGAL_TRANSITIONS.get(from);
|
|
@@ -1303,7 +1452,9 @@ var Connection = class extends events.EventEmitter {
|
|
|
1303
1452
|
}
|
|
1304
1453
|
}
|
|
1305
1454
|
_onTransportClose() {
|
|
1455
|
+
clearTimeout(this._refusalBound);
|
|
1306
1456
|
if (this._state === "DRAINING") {
|
|
1457
|
+
this._reportAbandonedWork("when the sender closed the connection", "peer closed");
|
|
1307
1458
|
this._transition("DISCONNECTED");
|
|
1308
1459
|
return;
|
|
1309
1460
|
}
|
|
@@ -1338,7 +1489,7 @@ var Connection = class extends events.EventEmitter {
|
|
|
1338
1489
|
}
|
|
1339
1490
|
}
|
|
1340
1491
|
/**
|
|
1341
|
-
* Handle a fatal framing error thrown out of `FrameReader.push
|
|
1492
|
+
* Handle a fatal framing error thrown out of `FrameReader.push`.
|
|
1342
1493
|
*
|
|
1343
1494
|
* Contract: surface it as a connection `'error'` (frozen payload, `phase: 'receive'`,
|
|
1344
1495
|
* `connectionCause: 'framing-fatal'`, the original `MllpFramingError` preserved as `cause` so
|
|
@@ -1356,8 +1507,21 @@ var Connection = class extends events.EventEmitter {
|
|
|
1356
1507
|
* forever, and the backoff would become an unbounded reconnect storm against an interface
|
|
1357
1508
|
* engine that is already unwell. A compatibility failure is not a network blip.
|
|
1358
1509
|
*
|
|
1359
|
-
*
|
|
1360
|
-
*
|
|
1510
|
+
* Frames delivered before the refused one are still answered. Their handlers may still be
|
|
1511
|
+
* running (an acknowledgement is written after its handler settles, so even a synchronous
|
|
1512
|
+
* handler's is not out yet), and closing at once dropped every one of those acknowledgements:
|
|
1513
|
+
* the sender resent a message already committed, and it was processed twice. So when work
|
|
1514
|
+
* passed to {@link Connection.holdOpenFor} is still running, the connection reads nothing
|
|
1515
|
+
* more, moves to `DRAINING`, waits for that work to settle, then closes gracefully (`CLOSED`,
|
|
1516
|
+
* the transport ended so the acknowledgements written are flushed). The wait is bounded by
|
|
1517
|
+
* `drainTimeoutMs`: past it the connection is destroyed, settled or not, so a handler that never
|
|
1518
|
+
* settles cannot hold the socket open. With nothing running it is destroyed at once.
|
|
1519
|
+
*
|
|
1520
|
+
* If a peer's quirk is *expected*, the decoder's tolerance opt-ins are the supported answer:
|
|
1521
|
+
* `allowLeadingWhitespace` (padding or keepalive bytes before a frame), `allowMissingLeadingVt`,
|
|
1522
|
+
* `allowFsOnly` (a bare FS that the next frame's VT follows) and `allowLfAfterFs` turn their
|
|
1523
|
+
* throw into a warning. No opt-in accepts other bytes between frames, or a stray FS or VT inside
|
|
1524
|
+
* one: those are always refused.
|
|
1361
1525
|
*/
|
|
1362
1526
|
_onFatalFramingError(err) {
|
|
1363
1527
|
if (this._state === "CLOSED") return;
|
|
@@ -1368,7 +1532,24 @@ var Connection = class extends events.EventEmitter {
|
|
|
1368
1532
|
connectionCause: "framing-fatal"
|
|
1369
1533
|
})
|
|
1370
1534
|
);
|
|
1371
|
-
this.
|
|
1535
|
+
if (this._answering.size === 0 || this._state !== "CONNECTED") {
|
|
1536
|
+
this.destroy(err);
|
|
1537
|
+
return;
|
|
1538
|
+
}
|
|
1539
|
+
this._refusing = true;
|
|
1540
|
+
const boundMs = this._opts.drainTimeoutMs ?? 3e4;
|
|
1541
|
+
this._transition("DRAINING", err.message);
|
|
1542
|
+
this._drainPromise = this._leftDraining.then(() => void 0);
|
|
1543
|
+
this._refusalBound = setTimeout(() => {
|
|
1544
|
+
this._transition("CLOSED", err.message);
|
|
1545
|
+
this._transport.destroy(err);
|
|
1546
|
+
}, boundMs);
|
|
1547
|
+
this._refusalBound.unref();
|
|
1548
|
+
void Promise.allSettled([...this._answering.keys()]).then(() => {
|
|
1549
|
+
if (this._state !== "DRAINING") return;
|
|
1550
|
+
this._transition("CLOSED", err.message);
|
|
1551
|
+
this._transport.close();
|
|
1552
|
+
});
|
|
1372
1553
|
}
|
|
1373
1554
|
/**
|
|
1374
1555
|
* Backstop for a NON-framing throw escaping `FrameReader.push`, i.e. our own bug, or a
|
|
@@ -1391,6 +1572,7 @@ var Connection = class extends events.EventEmitter {
|
|
|
1391
1572
|
const phase = this._state === "CONNECTING" ? "connect" : this._state === "RECONNECTING" ? "reconnect" : this._state === "DRAINING" ? "close" : "receive";
|
|
1392
1573
|
if (this._state === "CLOSED" || this._state === "DISCONNECTED") return;
|
|
1393
1574
|
this._emitErrorIfListened(new MllpConnectionError(err.message, { cause: err, phase }));
|
|
1575
|
+
this._reportAbandonedWork(`when the connection failed (${err.message})`, err.message);
|
|
1394
1576
|
const target = this._state === "CONNECTING" || this._state === "RECONNECTING" ? "CLOSED" : "DISCONNECTED";
|
|
1395
1577
|
this._transition(target, `error: ${err.message}`);
|
|
1396
1578
|
}
|
|
@@ -1893,6 +2075,11 @@ var MllpServer = class extends events.EventEmitter {
|
|
|
1893
2075
|
/** `true` when `ServerOptions.tls` is set, `_netServer` is actually a `tls.Server`. */
|
|
1894
2076
|
_isTls;
|
|
1895
2077
|
_listening = false;
|
|
2078
|
+
/**
|
|
2079
|
+
* `true` from a `close()` until the next `listen()`: a socket accepted meanwhile (a TLS
|
|
2080
|
+
* handshake that began before the close and finished during it) is closed at once, never served.
|
|
2081
|
+
*/
|
|
2082
|
+
_closing = false;
|
|
1896
2083
|
/** Single-flight guard: `true` while a `listen()` call is settling. */
|
|
1897
2084
|
_listenInFlight = false;
|
|
1898
2085
|
/**
|
|
@@ -2148,6 +2335,7 @@ var MllpServer = class extends events.EventEmitter {
|
|
|
2148
2335
|
);
|
|
2149
2336
|
}
|
|
2150
2337
|
this._listenInFlight = true;
|
|
2338
|
+
this._closing = false;
|
|
2151
2339
|
return new Promise((resolve, reject) => {
|
|
2152
2340
|
let settled = false;
|
|
2153
2341
|
const settle = (outcome, opts) => {
|
|
@@ -2274,10 +2462,23 @@ var MllpServer = class extends events.EventEmitter {
|
|
|
2274
2462
|
* Stop accepting new connections and gracefully close all active connections.
|
|
2275
2463
|
*
|
|
2276
2464
|
* Sequence:
|
|
2277
|
-
* 1. `net.Server.close()`, stops accepting new connections immediately
|
|
2465
|
+
* 1. `net.Server.close()`, stops accepting new connections immediately. A socket the listener
|
|
2466
|
+
* still hands over (a TLS handshake that began before `close()` and ends during it) is
|
|
2467
|
+
* destroyed at once, before any byte of it is read.
|
|
2278
2468
|
* 2. If `_connections` is empty: resolves immediately (no drain needed)
|
|
2279
|
-
* 3.
|
|
2280
|
-
*
|
|
2469
|
+
* 3. Every connection stops reading: bytes the peer sends from now on are dropped unread, so no
|
|
2470
|
+
* new message reaches a handler.
|
|
2471
|
+
* 4. Every connection waits for its handlers still running and the acknowledgements they write
|
|
2472
|
+
* (`AA`, a negative ACK for a handler that rejects, a custom builder's bytes), then ends its
|
|
2473
|
+
* socket gracefully so those acknowledgements reach the sender. In manual mode the wait lasts
|
|
2474
|
+
* until the handler's promise settles: a `conn.send()` made after that is not waited for. In
|
|
2475
|
+
* custom-ACK mode the `onMessage` observer is not waited for: it writes no acknowledgement.
|
|
2476
|
+
* 5. The wait is bounded by `drainTimeoutMs`. A connection still waiting then is destroyed, and
|
|
2477
|
+
* the server's `'error'` event carries an `MllpConnectionError` with `phase: 'close'` saying
|
|
2478
|
+
* how many messages were delivered without their acknowledgement being sent, how many
|
|
2479
|
+
* manual-mode handlers may not have sent theirs, and how many observers were still running.
|
|
2480
|
+
* The same report is made when the sender closes the connection, or half-closes it (the
|
|
2481
|
+
* server's sockets are not half-open, so our side ends with it), before that work settles.
|
|
2281
2482
|
*
|
|
2282
2483
|
* Calling `close()` while a `listen()` is still in flight proactively
|
|
2283
2484
|
* settles that `listen()` with a typed `MllpConnectionError` rejection
|
|
@@ -2304,6 +2505,7 @@ var MllpServer = class extends events.EventEmitter {
|
|
|
2304
2505
|
return Promise.reject(new DOMException("Aborted", "AbortError"));
|
|
2305
2506
|
}
|
|
2306
2507
|
this._pendingListenSettle?.();
|
|
2508
|
+
this._closing = true;
|
|
2307
2509
|
this._netServer.close();
|
|
2308
2510
|
this._listening = false;
|
|
2309
2511
|
if (this._connections.size === 0) {
|
|
@@ -2346,10 +2548,13 @@ var MllpServer = class extends events.EventEmitter {
|
|
|
2346
2548
|
*/
|
|
2347
2549
|
async _drainAll(drainTimeoutMs) {
|
|
2348
2550
|
const snapshot = [...this._connections];
|
|
2349
|
-
const closePromises = snapshot.map((conn) =>
|
|
2551
|
+
const closePromises = snapshot.map((conn) => {
|
|
2552
|
+
conn.stopReading();
|
|
2553
|
+
return conn.close({ drainTimeoutMs });
|
|
2554
|
+
});
|
|
2350
2555
|
const timeoutHandle = setTimeout(() => {
|
|
2351
2556
|
for (const conn of this._connections) {
|
|
2352
|
-
conn.destroy();
|
|
2557
|
+
conn.destroy(new Error("drain timeout"));
|
|
2353
2558
|
}
|
|
2354
2559
|
}, drainTimeoutMs);
|
|
2355
2560
|
timeoutHandle.unref();
|
|
@@ -2436,6 +2641,10 @@ var MllpServer = class extends events.EventEmitter {
|
|
|
2436
2641
|
// Private: per-socket setup
|
|
2437
2642
|
// ---------------------------------------------------------------------------
|
|
2438
2643
|
_onSocketAccepted(socket) {
|
|
2644
|
+
if (this._closing) {
|
|
2645
|
+
socket.destroy();
|
|
2646
|
+
return;
|
|
2647
|
+
}
|
|
2439
2648
|
if (this._opts.keepaliveIntervalMs !== void 0) {
|
|
2440
2649
|
socket.setKeepAlive(true, this._opts.keepaliveIntervalMs);
|
|
2441
2650
|
}
|
|
@@ -2446,10 +2655,12 @@ var MllpServer = class extends events.EventEmitter {
|
|
|
2446
2655
|
...this._opts.framing ?? {}
|
|
2447
2656
|
};
|
|
2448
2657
|
const connOpts = this._opts.onWarning !== void 0 ? { transport, framing: mergedFraming, onWarning: this._opts.onWarning } : { transport, framing: mergedFraming };
|
|
2449
|
-
const conn = new Connection(
|
|
2658
|
+
const conn = new Connection({
|
|
2659
|
+
...connOpts,
|
|
2660
|
+
drainTimeoutMs: this._opts.drainTimeoutMs ?? 3e4
|
|
2661
|
+
});
|
|
2450
2662
|
const release = this._capRelease.get(socket);
|
|
2451
2663
|
if (release !== void 0) socket.once("close", release);
|
|
2452
|
-
conn.beforeClose = () => Promise.resolve();
|
|
2453
2664
|
conn.on("error", (errEvent) => {
|
|
2454
2665
|
this._emitErrorIfListened(errEvent);
|
|
2455
2666
|
});
|
|
@@ -2503,12 +2714,12 @@ var MllpServer = class extends events.EventEmitter {
|
|
|
2503
2714
|
}
|
|
2504
2715
|
const autoAck = this._opts.autoAck;
|
|
2505
2716
|
if (autoAck === "AA") {
|
|
2506
|
-
|
|
2717
|
+
conn.holdOpenFor(this._sendCommitAck(payload, meta, conn));
|
|
2507
2718
|
} else if (autoAck !== void 0) {
|
|
2508
|
-
this._observeMessage(payload, meta, conn);
|
|
2509
|
-
|
|
2719
|
+
this._observeMessage(payload, meta, conn, "observer");
|
|
2720
|
+
conn.holdOpenFor(this._sendCustomAck(autoAck, payload, meta, conn));
|
|
2510
2721
|
} else {
|
|
2511
|
-
this._observeMessage(payload, meta, conn);
|
|
2722
|
+
this._observeMessage(payload, meta, conn, "manual");
|
|
2512
2723
|
}
|
|
2513
2724
|
}
|
|
2514
2725
|
);
|
|
@@ -2575,7 +2786,7 @@ var MllpServer = class extends events.EventEmitter {
|
|
|
2575
2786
|
if (handler === void 0) {
|
|
2576
2787
|
this._dispatchAck(
|
|
2577
2788
|
conn,
|
|
2578
|
-
buildRawAckFrom(inbound, this._resolveAutoAckPositive(inbound,
|
|
2789
|
+
buildRawAckFrom(inbound, this._resolveAutoAckPositive(inbound, conn, selectCode))
|
|
2579
2790
|
);
|
|
2580
2791
|
return;
|
|
2581
2792
|
}
|
|
@@ -2584,7 +2795,7 @@ var MllpServer = class extends events.EventEmitter {
|
|
|
2584
2795
|
try {
|
|
2585
2796
|
await handler(payload, meta, conn);
|
|
2586
2797
|
settled = readInbound(payload);
|
|
2587
|
-
code = this._resolveAutoAckPositive(settled,
|
|
2798
|
+
code = this._resolveAutoAckPositive(settled, conn, selectCode);
|
|
2588
2799
|
} catch (err) {
|
|
2589
2800
|
const nack = resolveNackCode(err);
|
|
2590
2801
|
code = selectCode(nack);
|
|
@@ -2607,30 +2818,18 @@ var MllpServer = class extends events.EventEmitter {
|
|
|
2607
2818
|
* cannot carry a correlatable positive ACK, so `AA` never names a control ID the sender
|
|
2608
2819
|
* cannot match (→ timeout → resend → **duplicate clinical message**).
|
|
2609
2820
|
*
|
|
2610
|
-
*
|
|
2611
|
-
*
|
|
2612
|
-
*
|
|
2613
|
-
*
|
|
2614
|
-
*
|
|
2615
|
-
* event) rather than a silent code change inside the builder.
|
|
2616
|
-
* - **`MLLP_TRAILING_BYTES`** in the frame's warnings, a mid-payload `VT` made the
|
|
2617
|
-
* decoder discard accumulated bytes and deliver only the fragment after it. The
|
|
2618
|
-
* clinical message was destroyed in transit, so even a fragment that happens to carry
|
|
2619
|
-
* a readable MSH must not be positively acknowledged. This condition is invisible to
|
|
2620
|
-
* `buildRawAck` (it sees only the fragment), which is why it lives here. The code is
|
|
2621
|
-
* **reserved** for that discard (see the decoder's `_readPayload`) and is emitted while
|
|
2622
|
-
* accumulating the delivered frame, so it is frame-scoped: it names *this* payload's own
|
|
2623
|
-
* discard, never a neighbouring frame's trailing junk.
|
|
2624
|
-
*
|
|
2625
|
-
* `'discarded-bytes'` takes precedence in the reason when both hold, it is the root cause.
|
|
2821
|
+
* The disqualifier is **`rawAckUncorrelatable(payload)`**: no readable `MSH`, an empty
|
|
2822
|
+
* MSH-10, or a batch/concatenated-message shape. This is the SAME predicate `buildRawAck`
|
|
2823
|
+
* enforces on the wire; it is re-checked here so the downgrade is **observable** (a `'nack'`
|
|
2824
|
+
* event) rather than a silent code change inside the builder. A frame with a `VT` or a stray
|
|
2825
|
+
* `FS` inside it never gets here: the decoder refuses it whole and the connection closes.
|
|
2626
2826
|
*
|
|
2627
2827
|
* `selectCode` puts the resolved disposition in the half of HL7 Table 0008 the inbound
|
|
2628
2828
|
* asked for; it is the identity for a message that asked for nothing.
|
|
2629
2829
|
*/
|
|
2630
|
-
_resolveAutoAckPositive(inbound,
|
|
2631
|
-
|
|
2632
|
-
|
|
2633
|
-
const reason = discarded ? "discarded-bytes" : "uncorrelatable-inbound";
|
|
2830
|
+
_resolveAutoAckPositive(inbound, conn, selectCode) {
|
|
2831
|
+
if (!uncorrelatable(inbound)) return selectCode("AA");
|
|
2832
|
+
const reason = "uncorrelatable-inbound";
|
|
2634
2833
|
const code = selectCode("AE");
|
|
2635
2834
|
this._emitContained(
|
|
2636
2835
|
"nack",
|
|
@@ -2706,13 +2905,14 @@ var MllpServer = class extends events.EventEmitter {
|
|
|
2706
2905
|
* connection (a handler error never crashes the server) rather than escaping as
|
|
2707
2906
|
* an unhandled rejection. The error text is never placed on the wire.
|
|
2708
2907
|
*/
|
|
2709
|
-
_observeMessage(payload, meta, conn) {
|
|
2908
|
+
_observeMessage(payload, meta, conn, kind) {
|
|
2710
2909
|
const handler = this._opts.onMessage;
|
|
2711
2910
|
if (handler === void 0) return;
|
|
2712
|
-
|
|
2911
|
+
const work = Promise.resolve().then(() => handler(payload, meta, conn)).catch((err) => {
|
|
2713
2912
|
const connErr = err instanceof Error ? err : new Error(String(err));
|
|
2714
2913
|
safeEmitError(conn, Object.freeze({ connectionId: conn.connectionId, error: connErr }));
|
|
2715
2914
|
});
|
|
2915
|
+
conn.holdOpenFor(work, { kind });
|
|
2716
2916
|
}
|
|
2717
2917
|
/**
|
|
2718
2918
|
* The custom-builder path for `autoAck: fn`. Awaits the builder and dispatches its
|
|
@@ -2729,10 +2929,12 @@ var MllpServer = class extends events.EventEmitter {
|
|
|
2729
2929
|
}
|
|
2730
2930
|
}
|
|
2731
2931
|
/**
|
|
2732
|
-
* Frame an ACK payload and write it to the connection.
|
|
2733
|
-
*
|
|
2734
|
-
* a `MllpConnectionError({ phase: 'send' })`
|
|
2735
|
-
*
|
|
2932
|
+
* Frame an ACK payload and write it to the connection. When the connection has already
|
|
2933
|
+
* closed (a handler that settled after `server.close()` gave up on it, or after the peer
|
|
2934
|
+
* left), the ACK is not sent and a `MllpConnectionError({ phase: 'send' })` saying so is
|
|
2935
|
+
* emitted on the connection. `Connection.send()` returns `false` under backpressure (socket
|
|
2936
|
+
* write buffer full); that is reported the same way, as backpressure. Either way the peer
|
|
2937
|
+
* will time out waiting and may retry. The server never crashes.
|
|
2736
2938
|
*/
|
|
2737
2939
|
_dispatchAck(conn, ackPayload) {
|
|
2738
2940
|
let framed;
|
|
@@ -2749,6 +2951,19 @@ var MllpServer = class extends events.EventEmitter {
|
|
|
2749
2951
|
);
|
|
2750
2952
|
return;
|
|
2751
2953
|
}
|
|
2954
|
+
if (conn.state === "CLOSED" || conn.state === "DISCONNECTED") {
|
|
2955
|
+
safeEmitError(
|
|
2956
|
+
conn,
|
|
2957
|
+
Object.freeze({
|
|
2958
|
+
connectionId: conn.connectionId,
|
|
2959
|
+
error: new MllpConnectionError(
|
|
2960
|
+
"ACK not sent: the connection closed before the handler settled",
|
|
2961
|
+
{ cause: new Error("connection closed"), phase: "send" }
|
|
2962
|
+
)
|
|
2963
|
+
})
|
|
2964
|
+
);
|
|
2965
|
+
return;
|
|
2966
|
+
}
|
|
2752
2967
|
const sent = conn.send(framed);
|
|
2753
2968
|
if (!sent) {
|
|
2754
2969
|
safeEmitError(
|
|
@@ -4640,7 +4855,8 @@ var MllpClient = class extends events.EventEmitter {
|
|
|
4640
4855
|
* @example
|
|
4641
4856
|
* ```typescript
|
|
4642
4857
|
* const ack = await client.send(payloadBuffer);
|
|
4643
|
-
*
|
|
4858
|
+
* // Log the acknowledgement's size, never its bytes: they echo your MSH-10.
|
|
4859
|
+
* logger.info({ ackBytes: ack.length });
|
|
4644
4860
|
* ```
|
|
4645
4861
|
*
|
|
4646
4862
|
* @param payload Raw bytes; MLLP framing is added internally via `encodeFrame`.
|
|
@@ -5604,7 +5820,7 @@ async function runDifferential(options = {}) {
|
|
|
5604
5820
|
}
|
|
5605
5821
|
|
|
5606
5822
|
// src/index.ts
|
|
5607
|
-
var VERSION = "0.1.
|
|
5823
|
+
var VERSION = "0.1.15";
|
|
5608
5824
|
|
|
5609
5825
|
exports.ATNA_CIPHER_LIST = ATNA_CIPHER_LIST;
|
|
5610
5826
|
exports.ATNA_CIPHER_SUITES = ATNA_CIPHER_SUITES;
|