appmesh 3.1.19 → 3.1.21

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "appmesh",
3
- "version": "3.1.19",
3
+ "version": "3.1.21",
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,6 +17,10 @@ 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",
@@ -26,6 +30,8 @@ const CONSTANTS = Object.freeze({
26
30
  HTTP_HEADER_KEY_X_FILE_GROUP: "X-File-Group",
27
31
  HTTP_HEADER_KEY_X_OUTPUT_POSITION: "X-Output-Position",
28
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",
29
35
  HTTP_HEADER_KEY_X_INPUT_CLOSE: "X-Input-Close",
30
36
  HTTP_HEADER_KEY_X_SUBSCRIPTION_ID: "X-Subscription-Id",
31
37
  HTTP_HEADER_KEY_X_APPMESH_PROCESS_KEY: "X-AppMesh-Process-Key",
@@ -224,6 +230,82 @@ function parseDuration(duration) {
224
230
  return seconds;
225
231
  }
226
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
+
227
309
  /**
228
310
  * Case-insensitive header lookup (axios lowercases names; the TCP transport keeps the daemon's case).
229
311
  * @param {Object} headers - Response headers
@@ -966,36 +1048,122 @@ class AppMeshClient {
966
1048
 
967
1049
  /**
968
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.
969
1054
  * @param {Object} app - App configuration
970
1055
  * @param {Function} [stdoutHandler=defaultOutputHandler] - Stdout handler callback(data, position)
971
1056
  * @param {number|string} [maxTime] - Max runtime
972
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.
973
1060
  * @returns {Promise<number|null>} Exit code parsed from `X-Exit-Code`, or `null` when absent
1061
+ * @throws {AppMeshRequestError} The output exceeds `maxOutputBytes`.
974
1062
  */
975
1063
  async runAppSync(app, stdoutHandler = defaultOutputHandler, maxTime = CONSTANTS.DEFAULT_RUN_APP_TIMEOUT_SECONDS,
976
- lifecycle = CONSTANTS.DEFAULT_RUN_APP_LIFECYCLE_SECONDS) {
1064
+ lifecycle = CONSTANTS.DEFAULT_RUN_APP_LIFECYCLE_SECONDS, maxOutputBytes = null) {
977
1065
  const params = {
978
1066
  timeout: parseDuration(maxTime),
979
1067
  lifecycle: parseDuration(lifecycle)
980
1068
  };
981
1069
 
982
- const response = await this._request("post", "/appmesh/app/syncrun", app, { params });
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
+ });
983
1074
  let exitCode = null;
984
1075
 
985
- if (stdoutHandler) {
986
- stdoutHandler(response.data, 0);
987
- }
988
1076
  if (response.status === 200) {
989
1077
  // axios lowercases header names; the TCP transport keeps the daemon's exact case
990
1078
  const exitCodeHeader = _getHeader(response.headers, CONSTANTS.HTTP_HEADER_KEY_X_EXIT_CODE);
991
1079
  if (exitCodeHeader) {
992
1080
  exitCode = parseInt(exitCodeHeader, 10);
993
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
+ const bytes = _toBytes(response.data);
1098
+ if (maxOutputBytes !== null && maxOutputBytes !== undefined && bytes.byteLength > maxOutputBytes) {
1099
+ throw new AppMeshRequestError(
1100
+ `run output exceeds maxOutputBytes=${maxOutputBytes} (${bytes.byteLength} bytes)`,
1101
+ response.status
1102
+ );
1103
+ }
1104
+
1105
+ if (stdoutHandler) {
1106
+ stdoutHandler(_decodeBytes(bytes, _charsetOf(_responseContentType(response))), 0);
994
1107
  }
995
1108
 
996
1109
  return exitCode;
997
1110
  }
998
1111
 
1112
+ /**
1113
+ * Page the output that follows a full sync-run reply and delete the run instance.
1114
+ * @param {Object} first - The sync-run response: raw bytes in `data`, charset in `Content-Type`
1115
+ * @param {string} runName - Run instance name (`X-App-Name`)
1116
+ * @param {number|null} maxOutputBytes - Byte ceiling, `null` for no limit
1117
+ * @param {number} position - Byte offset to continue from (`X-Output-Position` of the reply)
1118
+ * @returns {Promise<string>} The complete output, decoded once in the charset of `first`
1119
+ * @throws {AppMeshRequestError} The output exceeds `maxOutputBytes`; the run is kept.
1120
+ * @private
1121
+ */
1122
+ async _readTruncatedRunOutput(first, runName, maxOutputBytes, position) {
1123
+ const chunks = [_toBytes(first.data)];
1124
+ if (!Number.isFinite(position)) {
1125
+ // No offset header: continue right after the first page.
1126
+ position = chunks[0].byteLength;
1127
+ }
1128
+ const exceeds = () => {
1129
+ const total = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);
1130
+ if (maxOutputBytes !== null && maxOutputBytes !== undefined && total > maxOutputBytes) {
1131
+ throw new AppMeshRequestError(
1132
+ `run output exceeds maxOutputBytes=${maxOutputBytes}; the rest stays readable on application ` +
1133
+ `'${runName}' for ${CONSTANTS.SYNC_RUN_TRUNCATED_RETENTION_SECONDS} seconds`,
1134
+ first.status);
1135
+ }
1136
+ };
1137
+ exceeds();
1138
+ let complete = false;
1139
+ try {
1140
+ while (true) {
1141
+ const page = await this._request("get", `/appmesh/app/${runName}/output`, null, {
1142
+ params: { stdout_position: String(position) }, config: { responseType: "arraybuffer" }
1143
+ });
1144
+ const bytes = _toBytes(page.data);
1145
+ chunks.push(bytes);
1146
+ // Offset advances by raw bytes; the ceiling is checked before the short page ends the loop.
1147
+ position += bytes.byteLength;
1148
+ exceeds();
1149
+ if (bytes.byteLength < CONSTANTS.SYNC_RUN_OUTPUT_PAGE_BYTES) {
1150
+ complete = true;
1151
+ break;
1152
+ }
1153
+ }
1154
+ } finally {
1155
+ // Best effort: the daemon removes the run when the retention ends.
1156
+ if (complete) {
1157
+ try {
1158
+ await this.deleteApp(runName);
1159
+ } catch (error) {
1160
+ console.warn(`Warning: Failed to remove sync run application '${runName}':`, error.message);
1161
+ }
1162
+ }
1163
+ }
1164
+ return _decodeBytes(_concatBytes(chunks), _charsetOf(_responseContentType(first)));
1165
+ }
1166
+
999
1167
  /**
1000
1168
  * Run an app asynchronously and return a handle for later polling.
1001
1169
  * @param {Object} app - App config
@@ -1688,7 +1856,9 @@ class AppMeshClient {
1688
1856
  /**
1689
1857
  * Open a server-sent-events stream as a streamed response. Plain HTTP by design: SSE
1690
1858
  * frames cannot ride a framed (TCP/WSS) transport, so framed subclasses redirect this
1691
- * hook to direct HTTPS (the WSS file data side-channel shape).
1859
+ * hook to direct HTTPS (the WSS file data side-channel shape). `forwardingHost` is carried
1860
+ * like on any request: the agent REST listener (default port 6060) relays the stream; the
1861
+ * engine's own listener answers a forwarded stream with 400.
1692
1862
  *
1693
1863
  * @private
1694
1864
  * @param {string} method - HTTP method ('get' or 'post')
@@ -1731,9 +1901,20 @@ class AppMeshClient {
1731
1901
  for await (const chunk of response.data) chunks.push(chunk);
1732
1902
  detail = Buffer.concat(chunks).toString("utf8");
1733
1903
  } catch (_) { /* socket already gone — raise a status-only error */ }
1734
- const message = detail
1904
+ let message = detail
1735
1905
  ? this._extractErrorMessage(detail)
1736
1906
  : `SSE request failed with status ${response.status}`;
1907
+ if (this.forwardingHost) {
1908
+ if (response.status === 400) {
1909
+ // Only the engine's own listener refuses X-Target-Host on a stream route.
1910
+ message += `; streaming through node forwarding (forwardingHost=${this.forwardingHost}) is relayed by` +
1911
+ ` the agent REST listener (default port 6060): point the client at it, not at the engine listener`;
1912
+ } else if (response.status === 404 || response.status === 405) {
1913
+ // A forwarded stream that lands on the target's TCP listener finds no stream route.
1914
+ message += `; a forwarded stream needs X-Target-Host to name the target without its TCP port` +
1915
+ ` (forwardingHost=${this.forwardingHost}): use a bare host or the target's agent REST port (6060)`;
1916
+ }
1917
+ }
1737
1918
  throw new AppMeshError(message, response.status, detail || null);
1738
1919
  }
1739
1920
  return response;
@@ -1750,28 +1931,23 @@ class AppMeshClient {
1750
1931
  return "Unknown error";
1751
1932
  }
1752
1933
 
1934
+ if (typeof Buffer !== "undefined" && Buffer.isBuffer(responseData)) {
1935
+ // Binary-typed body over the TCP transport: same handling as an ArrayBuffer.
1936
+ return this._extractErrorMessage(responseData.toString("utf8"));
1937
+ }
1938
+
1753
1939
  if (responseData instanceof ArrayBuffer) {
1754
1940
  try {
1755
1941
  const textDecoder = new TextDecoder("utf-8");
1756
1942
  const text = textDecoder.decode(responseData);
1757
- try {
1758
- const parsedJson = JSON.parse(text);
1759
- return parsedJson.message || parsedJson.error || "Binary response error";
1760
- } catch (e) {
1761
- return text; // not json, return raw text
1762
- }
1943
+ return text ? this._extractJsonErrorText(text) : "Unknown error";
1763
1944
  } catch (e) {
1764
1945
  return 'Binary response error (could not decode)';
1765
1946
  }
1766
1947
  }
1767
1948
 
1768
1949
  if (typeof responseData === 'string') {
1769
- try {
1770
- const parsedJson = JSON.parse(responseData);
1771
- return parsedJson.message || parsedJson.error || responseData;
1772
- } catch (e) {
1773
- return responseData;
1774
- }
1950
+ return this._extractJsonErrorText(responseData);
1775
1951
  }
1776
1952
 
1777
1953
  if (typeof responseData === 'object') {
@@ -1781,6 +1957,21 @@ class AppMeshClient {
1781
1957
  return String(responseData);
1782
1958
  }
1783
1959
 
1960
+ _extractJsonErrorText(text) {
1961
+ try {
1962
+ const parsed = JSON.parse(text);
1963
+ if (parsed && typeof parsed === 'object') {
1964
+ return parsed.message || parsed.error || text;
1965
+ }
1966
+ if (typeof parsed === 'string') {
1967
+ return parsed;
1968
+ }
1969
+ return text;
1970
+ } catch (e) {
1971
+ return text;
1972
+ }
1973
+ }
1974
+
1784
1975
  /**
1785
1976
  * Comprehensive error handler for all client errors.
1786
1977
  * The default implementation only normalizes the error type; override this