appmesh 3.1.18 → 3.1.20
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/README.md +33 -5
- package/dist/appmesh.esm.js +1 -1
- package/package.json +2 -2
- package/src/appmesh.js +192 -8
- package/src/appmesh_tcp.js +162 -40
- package/src/worker.js +5 -5
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "appmesh",
|
|
3
|
-
"version": "3.1.
|
|
3
|
+
"version": "3.1.20",
|
|
4
4
|
"description": "JavaScript SDK for App Mesh (https://github.com/laoshanxi/app-mesh)",
|
|
5
5
|
"main": "./src/appmesh.js",
|
|
6
6
|
"module": "./dist/appmesh.esm.js",
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
"sideEffects": false,
|
|
9
9
|
"scripts": {
|
|
10
10
|
"lint": "prettier --write .",
|
|
11
|
-
"test": "node test/unit_test.js && node test/subscribe_test.js && node test/appmesh_test.js",
|
|
11
|
+
"test": "node test/unit_test.js && node test/syncrun_test.js && node test/subscribe_test.js && node test/stream_forward_test.js && node test/appmesh_test.js",
|
|
12
12
|
"test:subscribe": "node test/subscribe_test.js",
|
|
13
13
|
"build": "webpack --config webpack.config.cjs --mode production",
|
|
14
14
|
"prepare": "npm run build",
|
package/src/appmesh.js
CHANGED
|
@@ -17,14 +17,21 @@ const CONSTANTS = Object.freeze({
|
|
|
17
17
|
HTTP_USER_AGENT: "appmesh/javascript",
|
|
18
18
|
DEFAULT_RUN_APP_TIMEOUT_SECONDS: "P2D",
|
|
19
19
|
DEFAULT_RUN_APP_LIFECYCLE_SECONDS: "P2DT12H",
|
|
20
|
+
// A sync-run reply of this size is a full page; the daemon keeps that run for
|
|
21
|
+
// SYNC_RUN_TRUNCATED_RETENTION_SECONDS so the client can read the rest.
|
|
22
|
+
SYNC_RUN_OUTPUT_PAGE_BYTES: 5 * 1024 * 1024,
|
|
23
|
+
SYNC_RUN_TRUNCATED_RETENTION_SECONDS: 600,
|
|
20
24
|
HTTP_HEADER_KEY_AUTH: "Authorization",
|
|
21
25
|
HTTP_HEADER_KEY_X_TARGET_HOST: "X-Target-Host",
|
|
22
26
|
HTTP_HEADER_KEY_X_FILE_PATH: "X-File-Path",
|
|
27
|
+
HTTP_HEADER_KEY_X_FILE_OVERWRITE: "X-File-Overwrite",
|
|
23
28
|
HTTP_HEADER_KEY_X_FILE_MODE: "X-File-Mode",
|
|
24
29
|
HTTP_HEADER_KEY_X_FILE_USER: "X-File-User",
|
|
25
30
|
HTTP_HEADER_KEY_X_FILE_GROUP: "X-File-Group",
|
|
26
31
|
HTTP_HEADER_KEY_X_OUTPUT_POSITION: "X-Output-Position",
|
|
27
32
|
HTTP_HEADER_KEY_X_EXIT_CODE: "X-Exit-Code",
|
|
33
|
+
HTTP_HEADER_KEY_X_OUTPUT_TRUNCATED: "X-Output-Truncated",
|
|
34
|
+
HTTP_HEADER_KEY_X_APP_NAME: "X-App-Name",
|
|
28
35
|
HTTP_HEADER_KEY_X_INPUT_CLOSE: "X-Input-Close",
|
|
29
36
|
HTTP_HEADER_KEY_X_SUBSCRIPTION_ID: "X-Subscription-Id",
|
|
30
37
|
HTTP_HEADER_KEY_X_APPMESH_PROCESS_KEY: "X-AppMesh-Process-Key",
|
|
@@ -223,6 +230,82 @@ function parseDuration(duration) {
|
|
|
223
230
|
return seconds;
|
|
224
231
|
}
|
|
225
232
|
|
|
233
|
+
/**
|
|
234
|
+
* Normalize a response body to raw bytes. Buffer stays a Buffer (Node, also the TCP
|
|
235
|
+
* transport); ArrayBuffer / typed arrays become a Uint8Array view over the same memory;
|
|
236
|
+
* anything else (a string from a stubbed transport) is UTF-8 encoded.
|
|
237
|
+
* @param {*} data - Response body
|
|
238
|
+
* @returns {Uint8Array} Raw body bytes
|
|
239
|
+
* @private
|
|
240
|
+
*/
|
|
241
|
+
function _toBytes(data) {
|
|
242
|
+
if (typeof Buffer !== "undefined" && Buffer.isBuffer(data)) return data;
|
|
243
|
+
if (data instanceof ArrayBuffer) return new Uint8Array(data);
|
|
244
|
+
if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
245
|
+
return new TextEncoder().encode(data == null ? "" : String(data));
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Concatenate raw byte chunks.
|
|
250
|
+
* @param {Uint8Array[]} chunks - Byte chunks (Buffers or Uint8Arrays)
|
|
251
|
+
* @returns {Uint8Array} One contiguous byte sequence
|
|
252
|
+
* @private
|
|
253
|
+
*/
|
|
254
|
+
function _concatBytes(chunks) {
|
|
255
|
+
if (typeof Buffer !== "undefined") {
|
|
256
|
+
return Buffer.concat(chunks.map(c => Buffer.isBuffer(c) ? c : Buffer.from(c.buffer, c.byteOffset, c.byteLength)));
|
|
257
|
+
}
|
|
258
|
+
let total = 0;
|
|
259
|
+
for (const chunk of chunks) total += chunk.byteLength;
|
|
260
|
+
const joined = new Uint8Array(total);
|
|
261
|
+
let offset = 0;
|
|
262
|
+
for (const chunk of chunks) {
|
|
263
|
+
joined.set(chunk, offset);
|
|
264
|
+
offset += chunk.byteLength;
|
|
265
|
+
}
|
|
266
|
+
return joined;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* The Content-Type of a response: the header, or (framed transport) the body type
|
|
271
|
+
* the daemon put in the message instead of a header.
|
|
272
|
+
* @param {Object} response - Response object
|
|
273
|
+
* @returns {*} Content-Type value or undefined
|
|
274
|
+
* @private
|
|
275
|
+
*/
|
|
276
|
+
function _responseContentType(response) {
|
|
277
|
+
return _getHeader(response.headers, "content-type") || (response.contentType == null ? undefined : response.contentType);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* The charset of a Content-Type header value, or null when none is declared.
|
|
282
|
+
* @param {*} contentType - Content-Type header value
|
|
283
|
+
* @returns {string|null} Charset label as sent by the server
|
|
284
|
+
* @private
|
|
285
|
+
*/
|
|
286
|
+
function _charsetOf(contentType) {
|
|
287
|
+
const match = /charset\s*=\s*"?([\w!#$%&*+\-.^`|~]+)"?/i.exec(String(contentType || ""));
|
|
288
|
+
return match ? match[1] : null;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Decode bytes in the given charset (UTF-8 when null or unsupported by this runtime).
|
|
293
|
+
* Malformed sequences are replaced, like axios's own text decoding.
|
|
294
|
+
* @param {Uint8Array} bytes - Raw bytes
|
|
295
|
+
* @param {string|null} charset - Charset label
|
|
296
|
+
* @returns {string} Decoded text
|
|
297
|
+
* @private
|
|
298
|
+
*/
|
|
299
|
+
function _decodeBytes(bytes, charset) {
|
|
300
|
+
for (const label of [charset, "utf-8"]) {
|
|
301
|
+
if (!label) continue;
|
|
302
|
+
try {
|
|
303
|
+
return new TextDecoder(label).decode(bytes);
|
|
304
|
+
} catch (error) { /* unsupported label: fall back to UTF-8 */ }
|
|
305
|
+
}
|
|
306
|
+
return new TextDecoder("utf-8").decode(bytes);
|
|
307
|
+
}
|
|
308
|
+
|
|
226
309
|
/**
|
|
227
310
|
* Case-insensitive header lookup (axios lowercases names; the TCP transport keeps the daemon's case).
|
|
228
311
|
* @param {Object} headers - Response headers
|
|
@@ -965,36 +1048,114 @@ class AppMeshClient {
|
|
|
965
1048
|
|
|
966
1049
|
/**
|
|
967
1050
|
* Run an app synchronously and stream the returned stdout body to `stdoutHandler`.
|
|
1051
|
+
*
|
|
1052
|
+
* A reply is at most one page (SYNC_RUN_OUTPUT_PAGE_BYTES). A full page is followed by
|
|
1053
|
+
* the rest, read from the output endpoint: `stdoutHandler` gets the complete output once.
|
|
968
1054
|
* @param {Object} app - App configuration
|
|
969
1055
|
* @param {Function} [stdoutHandler=defaultOutputHandler] - Stdout handler callback(data, position)
|
|
970
1056
|
* @param {number|string} [maxTime] - Max runtime
|
|
971
1057
|
* @param {number|string} [lifecycle] - Lifecycle time
|
|
1058
|
+
* @param {number|null} [maxOutputBytes=null] - Ceiling on the total output in bytes
|
|
1059
|
+
* (`null`: unlimited). Exceeding it rejects; the run instance is then left in place.
|
|
972
1060
|
* @returns {Promise<number|null>} Exit code parsed from `X-Exit-Code`, or `null` when absent
|
|
1061
|
+
* @throws {AppMeshRequestError} The output exceeds `maxOutputBytes`.
|
|
973
1062
|
*/
|
|
974
1063
|
async runAppSync(app, stdoutHandler = defaultOutputHandler, maxTime = CONSTANTS.DEFAULT_RUN_APP_TIMEOUT_SECONDS,
|
|
975
|
-
lifecycle = CONSTANTS.DEFAULT_RUN_APP_LIFECYCLE_SECONDS) {
|
|
1064
|
+
lifecycle = CONSTANTS.DEFAULT_RUN_APP_LIFECYCLE_SECONDS, maxOutputBytes = null) {
|
|
976
1065
|
const params = {
|
|
977
1066
|
timeout: parseDuration(maxTime),
|
|
978
1067
|
lifecycle: parseDuration(lifecycle)
|
|
979
1068
|
};
|
|
980
1069
|
|
|
981
|
-
|
|
1070
|
+
// Raw bytes: pages are joined as bytes and decoded once (a character may span pages).
|
|
1071
|
+
const response = await this._request("post", "/appmesh/app/syncrun", app, {
|
|
1072
|
+
params, config: { responseType: "arraybuffer" }
|
|
1073
|
+
});
|
|
982
1074
|
let exitCode = null;
|
|
983
1075
|
|
|
984
|
-
if (stdoutHandler) {
|
|
985
|
-
stdoutHandler(response.data, 0);
|
|
986
|
-
}
|
|
987
1076
|
if (response.status === 200) {
|
|
988
1077
|
// axios lowercases header names; the TCP transport keeps the daemon's exact case
|
|
989
1078
|
const exitCodeHeader = _getHeader(response.headers, CONSTANTS.HTTP_HEADER_KEY_X_EXIT_CODE);
|
|
990
1079
|
if (exitCodeHeader) {
|
|
991
1080
|
exitCode = parseInt(exitCodeHeader, 10);
|
|
992
1081
|
}
|
|
1082
|
+
// A full page keeps the run instance alive for the client to page the rest.
|
|
1083
|
+
// Older daemons send neither header: the reply is the whole output.
|
|
1084
|
+
const runName = _getHeader(response.headers, CONSTANTS.HTTP_HEADER_KEY_X_APP_NAME);
|
|
1085
|
+
const truncated = _getHeader(response.headers, CONSTANTS.HTTP_HEADER_KEY_X_OUTPUT_TRUNCATED);
|
|
1086
|
+
if (runName && String(truncated) === "1") {
|
|
1087
|
+
const positionHeader = _getHeader(response.headers, CONSTANTS.HTTP_HEADER_KEY_X_OUTPUT_POSITION);
|
|
1088
|
+
const output = await this._readTruncatedRunOutput(response, runName, maxOutputBytes,
|
|
1089
|
+
positionHeader ? parseInt(positionHeader, 10) : NaN);
|
|
1090
|
+
if (stdoutHandler) {
|
|
1091
|
+
stdoutHandler(output, 0);
|
|
1092
|
+
}
|
|
1093
|
+
return exitCode;
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
if (stdoutHandler) {
|
|
1098
|
+
stdoutHandler(_decodeBytes(_toBytes(response.data), _charsetOf(_responseContentType(response))), 0);
|
|
993
1099
|
}
|
|
994
1100
|
|
|
995
1101
|
return exitCode;
|
|
996
1102
|
}
|
|
997
1103
|
|
|
1104
|
+
/**
|
|
1105
|
+
* Page the output that follows a full sync-run reply and delete the run instance.
|
|
1106
|
+
* @param {Object} first - The sync-run response: raw bytes in `data`, charset in `Content-Type`
|
|
1107
|
+
* @param {string} runName - Run instance name (`X-App-Name`)
|
|
1108
|
+
* @param {number|null} maxOutputBytes - Byte ceiling, `null` for no limit
|
|
1109
|
+
* @param {number} position - Byte offset to continue from (`X-Output-Position` of the reply)
|
|
1110
|
+
* @returns {Promise<string>} The complete output, decoded once in the charset of `first`
|
|
1111
|
+
* @throws {AppMeshRequestError} The output exceeds `maxOutputBytes`; the run is kept.
|
|
1112
|
+
* @private
|
|
1113
|
+
*/
|
|
1114
|
+
async _readTruncatedRunOutput(first, runName, maxOutputBytes, position) {
|
|
1115
|
+
const chunks = [_toBytes(first.data)];
|
|
1116
|
+
if (!Number.isFinite(position)) {
|
|
1117
|
+
// No offset header: continue right after the first page.
|
|
1118
|
+
position = chunks[0].byteLength;
|
|
1119
|
+
}
|
|
1120
|
+
const exceeds = () => {
|
|
1121
|
+
const total = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);
|
|
1122
|
+
if (maxOutputBytes !== null && maxOutputBytes !== undefined && total > maxOutputBytes) {
|
|
1123
|
+
throw new AppMeshRequestError(
|
|
1124
|
+
`run output exceeds maxOutputBytes=${maxOutputBytes}; the rest stays readable on application ` +
|
|
1125
|
+
`'${runName}' for ${CONSTANTS.SYNC_RUN_TRUNCATED_RETENTION_SECONDS} seconds`,
|
|
1126
|
+
first.status);
|
|
1127
|
+
}
|
|
1128
|
+
};
|
|
1129
|
+
exceeds();
|
|
1130
|
+
let complete = false;
|
|
1131
|
+
try {
|
|
1132
|
+
while (true) {
|
|
1133
|
+
const page = await this._request("get", `/appmesh/app/${runName}/output`, null, {
|
|
1134
|
+
params: { stdout_position: String(position) }, config: { responseType: "arraybuffer" }
|
|
1135
|
+
});
|
|
1136
|
+
const bytes = _toBytes(page.data);
|
|
1137
|
+
chunks.push(bytes);
|
|
1138
|
+
// Offset advances by raw bytes; the ceiling is checked before the short page ends the loop.
|
|
1139
|
+
position += bytes.byteLength;
|
|
1140
|
+
exceeds();
|
|
1141
|
+
if (bytes.byteLength < CONSTANTS.SYNC_RUN_OUTPUT_PAGE_BYTES) {
|
|
1142
|
+
complete = true;
|
|
1143
|
+
break;
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
} finally {
|
|
1147
|
+
// Best effort: the daemon removes the run when the retention ends.
|
|
1148
|
+
if (complete) {
|
|
1149
|
+
try {
|
|
1150
|
+
await this.deleteApp(runName);
|
|
1151
|
+
} catch (error) {
|
|
1152
|
+
console.warn(`Warning: Failed to remove sync run application '${runName}':`, error.message);
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
return _decodeBytes(_concatBytes(chunks), _charsetOf(_responseContentType(first)));
|
|
1157
|
+
}
|
|
1158
|
+
|
|
998
1159
|
/**
|
|
999
1160
|
* Run an app asynchronously and return a handle for later polling.
|
|
1000
1161
|
* @param {Object} app - App config
|
|
@@ -1348,8 +1509,10 @@ class AppMeshClient {
|
|
|
1348
1509
|
* @param {string} [filePath=null] - Remote target path; defaults to the basename of localFile
|
|
1349
1510
|
* @param {boolean} [applyAttrs=false] - In Node.js, send local permission bits plus
|
|
1350
1511
|
* user/group (names when resolvable locally, numeric ids otherwise)
|
|
1512
|
+
* @param {boolean} [overwrite=false] - Replace an existing remote file; the
|
|
1513
|
+
* default keeps the server's 409 refusal
|
|
1351
1514
|
*/
|
|
1352
|
-
async uploadFile(localFile, filePath = null, applyAttrs = false) {
|
|
1515
|
+
async uploadFile(localFile, filePath = null, applyAttrs = false, overwrite = false) {
|
|
1353
1516
|
if (!filePath) {
|
|
1354
1517
|
// Node.js passes a path string; browser passes a File (use its name)
|
|
1355
1518
|
const sourceName = typeof localFile === 'string' ? localFile : localFile && localFile.name;
|
|
@@ -1359,6 +1522,9 @@ class AppMeshClient {
|
|
|
1359
1522
|
filePath = sourceName.split(/[\\/]/).pop();
|
|
1360
1523
|
}
|
|
1361
1524
|
const headers = { [CONSTANTS.HTTP_HEADER_KEY_X_FILE_PATH]: encodeURIComponent(filePath) };
|
|
1525
|
+
if (overwrite) {
|
|
1526
|
+
headers[CONSTANTS.HTTP_HEADER_KEY_X_FILE_OVERWRITE] = 'true';
|
|
1527
|
+
}
|
|
1362
1528
|
let body;
|
|
1363
1529
|
|
|
1364
1530
|
if (ENV.isNode) {
|
|
@@ -1682,7 +1848,9 @@ class AppMeshClient {
|
|
|
1682
1848
|
/**
|
|
1683
1849
|
* Open a server-sent-events stream as a streamed response. Plain HTTP by design: SSE
|
|
1684
1850
|
* frames cannot ride a framed (TCP/WSS) transport, so framed subclasses redirect this
|
|
1685
|
-
* hook to direct HTTPS (the WSS file data side-channel shape).
|
|
1851
|
+
* hook to direct HTTPS (the WSS file data side-channel shape). `forwardingHost` is carried
|
|
1852
|
+
* like on any request: the agent REST listener (default port 6060) relays the stream; the
|
|
1853
|
+
* engine's own listener answers a forwarded stream with 400.
|
|
1686
1854
|
*
|
|
1687
1855
|
* @private
|
|
1688
1856
|
* @param {string} method - HTTP method ('get' or 'post')
|
|
@@ -1725,9 +1893,20 @@ class AppMeshClient {
|
|
|
1725
1893
|
for await (const chunk of response.data) chunks.push(chunk);
|
|
1726
1894
|
detail = Buffer.concat(chunks).toString("utf8");
|
|
1727
1895
|
} catch (_) { /* socket already gone — raise a status-only error */ }
|
|
1728
|
-
|
|
1896
|
+
let message = detail
|
|
1729
1897
|
? this._extractErrorMessage(detail)
|
|
1730
1898
|
: `SSE request failed with status ${response.status}`;
|
|
1899
|
+
if (this.forwardingHost) {
|
|
1900
|
+
if (response.status === 400) {
|
|
1901
|
+
// Only the engine's own listener refuses X-Target-Host on a stream route.
|
|
1902
|
+
message += `; streaming through node forwarding (forwardingHost=${this.forwardingHost}) is relayed by` +
|
|
1903
|
+
` the agent REST listener (default port 6060): point the client at it, not at the engine listener`;
|
|
1904
|
+
} else if (response.status === 404 || response.status === 405) {
|
|
1905
|
+
// A forwarded stream that lands on the target's TCP listener finds no stream route.
|
|
1906
|
+
message += `; a forwarded stream needs X-Target-Host to name the target without its TCP port` +
|
|
1907
|
+
` (forwardingHost=${this.forwardingHost}): use a bare host or the target's agent REST port (6060)`;
|
|
1908
|
+
}
|
|
1909
|
+
}
|
|
1731
1910
|
throw new AppMeshError(message, response.status, detail || null);
|
|
1732
1911
|
}
|
|
1733
1912
|
return response;
|
|
@@ -1744,6 +1923,11 @@ class AppMeshClient {
|
|
|
1744
1923
|
return "Unknown error";
|
|
1745
1924
|
}
|
|
1746
1925
|
|
|
1926
|
+
if (typeof Buffer !== "undefined" && Buffer.isBuffer(responseData)) {
|
|
1927
|
+
// Binary-typed body over the TCP transport: same handling as an ArrayBuffer.
|
|
1928
|
+
return this._extractErrorMessage(responseData.toString("utf8"));
|
|
1929
|
+
}
|
|
1930
|
+
|
|
1747
1931
|
if (responseData instanceof ArrayBuffer) {
|
|
1748
1932
|
try {
|
|
1749
1933
|
const textDecoder = new TextDecoder("utf-8");
|
package/src/appmesh_tcp.js
CHANGED
|
@@ -33,6 +33,7 @@ const HTTP_HEADER_KEY_X_RECV_FILE_SOCKET = 'X-Recv-File-Socket'
|
|
|
33
33
|
// Wire-header names come from the shared CONSTANTS block.
|
|
34
34
|
const HTTP_HEADER_KEY_USER_AGENT = CONSTANTS.HTTP_USER_AGENT_HEADER_NAME
|
|
35
35
|
const HTTP_HEADER_KEY_X_FILE_PATH = CONSTANTS.HTTP_HEADER_KEY_X_FILE_PATH
|
|
36
|
+
const HTTP_HEADER_KEY_X_FILE_OVERWRITE = CONSTANTS.HTTP_HEADER_KEY_X_FILE_OVERWRITE
|
|
36
37
|
const HTTP_HEADER_KEY_AUTH = CONSTANTS.HTTP_HEADER_KEY_AUTH
|
|
37
38
|
const HTTP_HEADER_KEY_X_TARGET_HOST = CONSTANTS.HTTP_HEADER_KEY_X_TARGET_HOST
|
|
38
39
|
const HTTP_HEADER_KEY_X_SUBSCRIPTION_ID = CONSTANTS.HTTP_HEADER_KEY_X_SUBSCRIPTION_ID
|
|
@@ -48,10 +49,10 @@ const HTTP_HEADER_KEY_X_FILE_GROUP = CONSTANTS.HTTP_HEADER_KEY_X_FILE_GROUP
|
|
|
48
49
|
*/
|
|
49
50
|
class TCPTransport {
|
|
50
51
|
/**
|
|
51
|
-
* @param {Array<string, number>} [address=['127.0.0.1',
|
|
52
|
+
* @param {Array<string, number>} [address=['127.0.0.1', 6062]] - Server address [host, port]
|
|
52
53
|
* @param {Object|false|null} [sslConfig=null] - TLS tri-state (see class doc)
|
|
53
54
|
*/
|
|
54
|
-
constructor (address = ['127.0.0.1',
|
|
55
|
+
constructor (address = ['127.0.0.1', 6062], sslConfig = null) {
|
|
55
56
|
this.address = address
|
|
56
57
|
this.sslConfig = sslConfig
|
|
57
58
|
this.socket = null
|
|
@@ -352,7 +353,7 @@ function _isAddressObject (value) {
|
|
|
352
353
|
*/
|
|
353
354
|
function _normalizeTcpAddress (address) {
|
|
354
355
|
if (_isAddressObject(address)) {
|
|
355
|
-
return [address.host ?? '127.0.0.1', address.port ??
|
|
356
|
+
return [address.host ?? '127.0.0.1', address.port ?? 6062]
|
|
356
357
|
}
|
|
357
358
|
return address
|
|
358
359
|
}
|
|
@@ -546,19 +547,24 @@ class AppMeshClientTCP extends AppMeshClient {
|
|
|
546
547
|
*
|
|
547
548
|
* @param {Object|false|null} [sslConfig=null] - TLS config; same tri-state as AppMeshClient
|
|
548
549
|
* (null=default CA, object=custom ca/cert/key, false=insecure).
|
|
549
|
-
* @param {Array<string, number>|{host: string, port: number}} [tcpAddress=['127.0.0.1',
|
|
550
|
-
* @param {number} [restPort=
|
|
551
|
-
* (followOutput / runTaskStream); also honored as a `restPort` key on the
|
|
550
|
+
* @param {Array<string, number>|{host: string, port: number}} [tcpAddress=['127.0.0.1', 6062]] - TCP server address
|
|
551
|
+
* @param {number} [restPort=6063] - REST port of the same daemon for the streaming side channel
|
|
552
|
+
* (followOutput / runTaskStream / streamRun) for local streams; also honored as a `restPort` key on the
|
|
553
|
+
* `{host, port}` address object
|
|
554
|
+
* @param {number} [agentPort=6060] - Agent REST port on the same host for the streaming side channel when
|
|
555
|
+
* `forwardingHost` is set (the engine listener does not stream through node forwarding, the agent relays it);
|
|
556
|
+
* also honored as an `agentPort` key on the `{host, port}` address object
|
|
552
557
|
*/
|
|
553
|
-
constructor (sslConfig = null, tcpAddress = ['127.0.0.1',
|
|
558
|
+
constructor (sslConfig = null, tcpAddress = ['127.0.0.1', 6062], restPort = null, agentPort = null) {
|
|
554
559
|
// Accept the address-first object form: new AppMeshClientTCP({host, port}, sslConfig)
|
|
555
560
|
if (_isAddressObject(sslConfig)) {
|
|
556
561
|
const addr = sslConfig
|
|
557
562
|
sslConfig = (Array.isArray(tcpAddress) || _isAddressObject(tcpAddress)) ? null : tcpAddress
|
|
558
563
|
tcpAddress = addr
|
|
559
564
|
}
|
|
560
|
-
if (_isAddressObject(tcpAddress)
|
|
561
|
-
restPort = tcpAddress.restPort
|
|
565
|
+
if (_isAddressObject(tcpAddress)) {
|
|
566
|
+
if (restPort == null) restPort = tcpAddress.restPort
|
|
567
|
+
if (agentPort == null) agentPort = tcpAddress.agentPort
|
|
562
568
|
}
|
|
563
569
|
tcpAddress = _normalizeTcpAddress(tcpAddress)
|
|
564
570
|
|
|
@@ -567,10 +573,18 @@ class AppMeshClientTCP extends AppMeshClient {
|
|
|
567
573
|
this.tcpTransport = new TCPTransport(tcpAddress, sslConfig)
|
|
568
574
|
this._demuxer = null
|
|
569
575
|
this._demuxerEnablePromise = null
|
|
576
|
+
// Upgrading from a legacy direct read to the demuxer must not put two
|
|
577
|
+
// readers on one socket; these track the transition and in-flight reads.
|
|
578
|
+
this._demuxerStarting = false
|
|
579
|
+
this._directReads = 0
|
|
580
|
+
this._directReadWaiters = []
|
|
570
581
|
// The SSE side channel (_sseRequest) dials the daemon's REST listener on the same host.
|
|
571
582
|
this._restHost = tcpAddress[0]
|
|
572
|
-
this._restPort = restPort ??
|
|
583
|
+
this._restPort = restPort ?? 6063
|
|
584
|
+
// A forwarded stream dials the agent REST listener instead (see _ensureRestChannel).
|
|
585
|
+
this._agentPort = agentPort ?? 6060
|
|
573
586
|
this._restChannelClient = null
|
|
587
|
+
this._agentChannelClient = null
|
|
574
588
|
}
|
|
575
589
|
|
|
576
590
|
/**
|
|
@@ -585,11 +599,14 @@ class AppMeshClientTCP extends AppMeshClient {
|
|
|
585
599
|
this.tcpTransport.close()
|
|
586
600
|
this.tcpTransport = null
|
|
587
601
|
}
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
602
|
+
for (const channel of [this._restChannelClient, this._agentChannelClient]) {
|
|
603
|
+
if (channel) {
|
|
604
|
+
// Release the streaming side channel's keep-alive sockets.
|
|
605
|
+
channel._client.defaults.httpsAgent?.destroy?.()
|
|
606
|
+
}
|
|
592
607
|
}
|
|
608
|
+
this._restChannelClient = null
|
|
609
|
+
this._agentChannelClient = null
|
|
593
610
|
}
|
|
594
611
|
|
|
595
612
|
/**
|
|
@@ -598,6 +615,13 @@ class AppMeshClientTCP extends AppMeshClient {
|
|
|
598
615
|
* @override
|
|
599
616
|
*/
|
|
600
617
|
async _request (method, path, body = null, options = {}) {
|
|
618
|
+
// A subscribe upgrade in progress owns the read side; wait for it so this
|
|
619
|
+
// request is routed by UUID instead of racing the new reader for frames
|
|
620
|
+
// (the subscribe ack could otherwise resolve this request, stranding
|
|
621
|
+
// subscribe). The wait precedes construction so signatures stay fresh.
|
|
622
|
+
if (this._demuxerStarting) {
|
|
623
|
+
await this._demuxerEnablePromise
|
|
624
|
+
}
|
|
601
625
|
if (!this.tcpTransport.connected()) {
|
|
602
626
|
await this.tcpTransport.connect()
|
|
603
627
|
}
|
|
@@ -619,9 +643,7 @@ class AppMeshClientTCP extends AppMeshClient {
|
|
|
619
643
|
}
|
|
620
644
|
|
|
621
645
|
if (this.forwardingHost) {
|
|
622
|
-
request.headers[HTTP_HEADER_KEY_X_TARGET_HOST] = this.
|
|
623
|
-
? this.forwardingHost
|
|
624
|
-
: `${this.forwardingHost}:${this.tcpTransport.address[1]}`
|
|
646
|
+
request.headers[HTTP_HEADER_KEY_X_TARGET_HOST] = this._forwardTargetHeader()
|
|
625
647
|
}
|
|
626
648
|
|
|
627
649
|
if (options.headers) {
|
|
@@ -676,21 +698,37 @@ class AppMeshClientTCP extends AppMeshClient {
|
|
|
676
698
|
}
|
|
677
699
|
response = await respPromise
|
|
678
700
|
} else {
|
|
679
|
-
//
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
if (
|
|
683
|
-
this.
|
|
684
|
-
|
|
701
|
+
// An upgrade claimed the read side while this request was being built;
|
|
702
|
+
// nothing has been sent yet, so rebuild behind the upgrade (fresh token
|
|
703
|
+
// and signature) and route by UUID instead of opening a second reader.
|
|
704
|
+
if (this._demuxerStarting) {
|
|
705
|
+
await this._demuxerEnablePromise
|
|
706
|
+
return this._request(method, path, body, options)
|
|
707
|
+
}
|
|
708
|
+
// Legacy synchronous mode: read directly. Track the read so a concurrent
|
|
709
|
+
// subscribe waits for this response before starting the demuxer.
|
|
710
|
+
this._directReads++
|
|
711
|
+
try {
|
|
712
|
+
this.tcpTransport.sendMessage(serialized)
|
|
713
|
+
const respData = await this.tcpTransport.receiveMessage()
|
|
714
|
+
if (!respData || respData.length === 0) {
|
|
715
|
+
this.tcpTransport.close()
|
|
716
|
+
throw new Error('Socket connection broken')
|
|
717
|
+
}
|
|
718
|
+
response = new ResponseMessage().deserialize(respData)
|
|
719
|
+
} finally {
|
|
720
|
+
this._releaseDirectRead()
|
|
685
721
|
}
|
|
686
|
-
response = new ResponseMessage().deserialize(respData)
|
|
687
722
|
}
|
|
688
723
|
|
|
689
724
|
// Convert to standard response format matching axios structure
|
|
725
|
+
const ctKey = Object.keys(response.headers || {}).find(k => k.toLowerCase() === 'content-type')
|
|
690
726
|
const result = {
|
|
691
727
|
status: response.httpStatus,
|
|
692
728
|
statusText: this._getStatusText(response.httpStatus),
|
|
693
729
|
headers: response.headers,
|
|
730
|
+
// The daemon puts the MIME type in body_msg_type, not a header; expose it like axios's.
|
|
731
|
+
contentType: response.bodyMsgType || (ctKey ? response.headers[ctKey] : undefined),
|
|
694
732
|
data: this._decodeBody(response, options),
|
|
695
733
|
config: options
|
|
696
734
|
}
|
|
@@ -783,29 +821,73 @@ class AppMeshClientTCP extends AppMeshClient {
|
|
|
783
821
|
}
|
|
784
822
|
|
|
785
823
|
/**
|
|
786
|
-
*
|
|
824
|
+
* The X-Target-Host value every request of this client carries, the framed ones and the
|
|
825
|
+
* streaming side channel alike: as given when it has a port, else the target's port is the
|
|
826
|
+
* one this client dials.
|
|
827
|
+
* @private
|
|
828
|
+
*/
|
|
829
|
+
_forwardTargetHeader () {
|
|
830
|
+
if (!this.forwardingHost) return null
|
|
831
|
+
return this.forwardingHost.includes(':')
|
|
832
|
+
? this.forwardingHost
|
|
833
|
+
: `${this.forwardingHost}:${this.tcpTransport.address[1]}`
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
/**
|
|
837
|
+
* Lazily build the direct-HTTPS client the streaming side channel uses, and keep its token
|
|
838
|
+
* provider, signer and forward target in step with this client.
|
|
839
|
+
* @private
|
|
840
|
+
*/
|
|
841
|
+
_syncSideChannel (client) {
|
|
842
|
+
// Re-sync on every use so a later setBearerToken()/enableRequestSignature() reaches the side channel too.
|
|
843
|
+
if (this._tokenProvider && client._tokenProvider !== this._tokenProvider) {
|
|
844
|
+
client.setTokenProvider(this._tokenProvider)
|
|
845
|
+
}
|
|
846
|
+
if (client._requestSigner !== this._requestSigner) {
|
|
847
|
+
client._requestSigner = this._requestSigner
|
|
848
|
+
}
|
|
849
|
+
// Sent as given on the agent hop, without the TCP port the framed requests append:
|
|
850
|
+
// an explicit port names the target's TCP listener, which does not serve streams.
|
|
851
|
+
const target = this.forwardingHost || null
|
|
852
|
+
if (client.forwardingHost !== target) client.forwardingHost = target
|
|
853
|
+
return client
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
/**
|
|
857
|
+
* The side-channel client a local stream dials: the engine's REST listener on the same host.
|
|
787
858
|
* @private
|
|
788
859
|
*/
|
|
789
860
|
_ensureRestChannel () {
|
|
790
861
|
if (!this._restChannelClient) {
|
|
791
862
|
this._restChannelClient = new AppMeshClient(`https://${this._restHost}:${this._restPort}`, this._sslConfig)
|
|
792
863
|
}
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
864
|
+
return this._syncSideChannel(this._restChannelClient)
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
/**
|
|
868
|
+
* The side-channel client a forwarded stream dials: the agent REST listener on the same
|
|
869
|
+
* host. The engine listener answers X-Target-Host on a stream route with 400, the agent
|
|
870
|
+
* relays the stream through node forwarding, so the target node runs the task.
|
|
871
|
+
* @private
|
|
872
|
+
*/
|
|
873
|
+
_ensureAgentChannel () {
|
|
874
|
+
if (!this._agentChannelClient) {
|
|
875
|
+
this._agentChannelClient = new AppMeshClient(`https://${this._restHost}:${this._agentPort}`, this._sslConfig)
|
|
796
876
|
}
|
|
797
|
-
return this.
|
|
877
|
+
return this._syncSideChannel(this._agentChannelClient)
|
|
798
878
|
}
|
|
799
879
|
|
|
800
880
|
/**
|
|
801
|
-
* Open an SSE stream over direct HTTPS
|
|
802
|
-
*
|
|
803
|
-
*
|
|
881
|
+
* Open an SSE stream over direct HTTPS: the framed transport answers one buffered frame and
|
|
882
|
+
* cannot carry a chunked event stream (bypassed like the WSS file data channel); plain
|
|
883
|
+
* request/response routes stay on the framed transport. A forwarded stream (`forwardingHost`
|
|
884
|
+
* set) goes to the agent REST listener with X-Target-Host, a local one to the engine listener.
|
|
804
885
|
* @private
|
|
805
886
|
* @override
|
|
806
887
|
*/
|
|
807
888
|
async _sseRequest (method, path, options = {}) {
|
|
808
|
-
|
|
889
|
+
const channel = this.forwardingHost ? this._ensureAgentChannel() : this._ensureRestChannel()
|
|
890
|
+
return channel._sseRequest(method, path, options)
|
|
809
891
|
}
|
|
810
892
|
|
|
811
893
|
/**
|
|
@@ -899,9 +981,11 @@ class AppMeshClientTCP extends AppMeshClient {
|
|
|
899
981
|
* @param {string} [filePath=null] - Remote destination path; defaults to the basename of localFile
|
|
900
982
|
* @param {boolean} [applyAttrs=false] - Send local mode and best-effort user/group name
|
|
901
983
|
* metadata so the server can recreate permissions and ownership when supported
|
|
984
|
+
* @param {boolean} [overwrite=false] - Replace an existing remote file; the
|
|
985
|
+
* default keeps the server's 409 refusal
|
|
902
986
|
* @override
|
|
903
987
|
*/
|
|
904
|
-
async uploadFile(localFile, filePath = null, applyAttrs = false) {
|
|
988
|
+
async uploadFile(localFile, filePath = null, applyAttrs = false, overwrite = false) {
|
|
905
989
|
this._ensureNoActiveDemuxer()
|
|
906
990
|
if (!filePath) filePath = localFile.split(/[\\/]/).pop()
|
|
907
991
|
if (!fs.existsSync(localFile)) {
|
|
@@ -913,6 +997,9 @@ class AppMeshClientTCP extends AppMeshClient {
|
|
|
913
997
|
'Content-Type': 'text/plain',
|
|
914
998
|
[HTTP_HEADER_KEY_X_SEND_FILE_SOCKET]: 'true'
|
|
915
999
|
}
|
|
1000
|
+
if (overwrite) {
|
|
1001
|
+
headers[HTTP_HEADER_KEY_X_FILE_OVERWRITE] = 'true'
|
|
1002
|
+
}
|
|
916
1003
|
|
|
917
1004
|
// Add file attributes
|
|
918
1005
|
if (applyAttrs) {
|
|
@@ -953,6 +1040,9 @@ class AppMeshClientTCP extends AppMeshClient {
|
|
|
953
1040
|
/**
|
|
954
1041
|
* Subscribe to app events over TCP.
|
|
955
1042
|
*
|
|
1043
|
+
* Resolves when the daemon acknowledges the subscription; it does not wait
|
|
1044
|
+
* for the first event. Later events are delivered to `callback`.
|
|
1045
|
+
*
|
|
956
1046
|
* @param {string} appName - Application name, or "*" for all apps.
|
|
957
1047
|
* @param {string[]} [events] - Event types: "START", "EXIT", "STDOUT", etc.
|
|
958
1048
|
* @param {function} callback - Called with event object for each received event.
|
|
@@ -1041,6 +1131,28 @@ class AppMeshClientTCP extends AppMeshClient {
|
|
|
1041
1131
|
}
|
|
1042
1132
|
}
|
|
1043
1133
|
|
|
1134
|
+
/**
|
|
1135
|
+
* Resolve when no legacy direct read owns the socket.
|
|
1136
|
+
* @private
|
|
1137
|
+
*/
|
|
1138
|
+
_waitForDirectReads () {
|
|
1139
|
+
if (this._directReads === 0) return Promise.resolve()
|
|
1140
|
+
return new Promise(resolve => this._directReadWaiters.push(resolve))
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
/**
|
|
1144
|
+
* Account for a finished legacy direct read and wake a waiting upgrade.
|
|
1145
|
+
* @private
|
|
1146
|
+
*/
|
|
1147
|
+
_releaseDirectRead () {
|
|
1148
|
+
this._directReads--
|
|
1149
|
+
if (this._directReads === 0 && this._directReadWaiters.length > 0) {
|
|
1150
|
+
const waiters = this._directReadWaiters
|
|
1151
|
+
this._directReadWaiters = []
|
|
1152
|
+
for (const resolve of waiters) resolve()
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1044
1156
|
/**
|
|
1045
1157
|
* Enable demuxer for concurrent request-response and event routing.
|
|
1046
1158
|
* Serialized: two concurrent subscribe() calls on an unconnected transport
|
|
@@ -1054,13 +1166,23 @@ class AppMeshClientTCP extends AppMeshClient {
|
|
|
1054
1166
|
await this._demuxerEnablePromise
|
|
1055
1167
|
return
|
|
1056
1168
|
}
|
|
1169
|
+
// Set before any await so requests starting during the upgrade route through
|
|
1170
|
+
// the demuxer instead of opening a second, competing direct read.
|
|
1171
|
+
this._demuxerStarting = true
|
|
1057
1172
|
this._demuxerEnablePromise = (async () => {
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1173
|
+
try {
|
|
1174
|
+
if (!this.tcpTransport.connected()) {
|
|
1175
|
+
await this.tcpTransport.connect()
|
|
1176
|
+
}
|
|
1177
|
+
// A legacy direct read consumes frames itself; starting the demuxer now
|
|
1178
|
+
// would race it and can strand either response forever.
|
|
1179
|
+
await this._waitForDirectReads()
|
|
1180
|
+
if (!this._demuxer || !this._demuxer._running) {
|
|
1181
|
+
this._demuxer = new MessageDemuxer(this.tcpTransport)
|
|
1182
|
+
this._demuxer.start()
|
|
1183
|
+
}
|
|
1184
|
+
} finally {
|
|
1185
|
+
this._demuxerStarting = false
|
|
1064
1186
|
}
|
|
1065
1187
|
})()
|
|
1066
1188
|
try {
|