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